1f22ef01cSRoman Divacky //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 2f22ef01cSRoman Divacky // 3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure 4f22ef01cSRoman Divacky // 5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source 6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details. 7f22ef01cSRoman Divacky // 8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 9f22ef01cSRoman Divacky // 10f22ef01cSRoman Divacky // This coordinates the per-module state used while generating code. 11f22ef01cSRoman Divacky // 12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 13f22ef01cSRoman Divacky 14f22ef01cSRoman Divacky #include "CodeGenModule.h" 150623d748SDimitry Andric #include "CGBlocks.h" 166122f3e6SDimitry Andric #include "CGCUDARuntime.h" 17e580952dSDimitry Andric #include "CGCXXABI.h" 18139f7f9bSDimitry Andric #include "CGCall.h" 19139f7f9bSDimitry Andric #include "CGDebugInfo.h" 20f22ef01cSRoman Divacky #include "CGObjCRuntime.h" 216122f3e6SDimitry Andric #include "CGOpenCLRuntime.h" 2259d1ed5bSDimitry Andric #include "CGOpenMPRuntime.h" 23e7145dcbSDimitry Andric #include "CGOpenMPRuntimeNVPTX.h" 24139f7f9bSDimitry Andric #include "CodeGenFunction.h" 2559d1ed5bSDimitry Andric #include "CodeGenPGO.h" 26139f7f9bSDimitry Andric #include "CodeGenTBAA.h" 2739d628a0SDimitry Andric #include "CoverageMappingGen.h" 28f22ef01cSRoman Divacky #include "TargetInfo.h" 29f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h" 30f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h" 31f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h" 32139f7f9bSDimitry Andric #include "clang/AST/DeclObjC.h" 33ffd1746dSEd Schouten #include "clang/AST/DeclTemplate.h" 342754fe60SDimitry Andric #include "clang/AST/Mangle.h" 35f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h" 36f8254f43SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h" 37dff0c46cSDimitry Andric #include "clang/Basic/Builtins.h" 38139f7f9bSDimitry Andric #include "clang/Basic/CharInfo.h" 39f22ef01cSRoman Divacky #include "clang/Basic/Diagnostic.h" 40139f7f9bSDimitry Andric #include "clang/Basic/Module.h" 41f22ef01cSRoman Divacky #include "clang/Basic/SourceManager.h" 42f22ef01cSRoman Divacky #include "clang/Basic/TargetInfo.h" 43f785676fSDimitry Andric #include "clang/Basic/Version.h" 44139f7f9bSDimitry Andric #include "clang/Frontend/CodeGenOptions.h" 45f785676fSDimitry Andric #include "clang/Sema/SemaDiagnostic.h" 46dff0c46cSDimitry Andric #include "llvm/ADT/APSInt.h" 47f22ef01cSRoman Divacky #include "llvm/ADT/Triple.h" 4859d1ed5bSDimitry Andric #include "llvm/IR/CallSite.h" 49139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h" 50139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h" 51139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h" 52139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h" 53139f7f9bSDimitry Andric #include "llvm/IR/Module.h" 5459d1ed5bSDimitry Andric #include "llvm/ProfileData/InstrProfReader.h" 55139f7f9bSDimitry Andric #include "llvm/Support/ConvertUTF.h" 56f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h" 570623d748SDimitry Andric #include "llvm/Support/MD5.h" 58139f7f9bSDimitry Andric 59f22ef01cSRoman Divacky using namespace clang; 60f22ef01cSRoman Divacky using namespace CodeGen; 61f22ef01cSRoman Divacky 626122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata"; 636122f3e6SDimitry Andric 6459d1ed5bSDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 65284c1978SDimitry Andric switch (CGM.getTarget().getCXXABI().getKind()) { 66139f7f9bSDimitry Andric case TargetCXXABI::GenericAArch64: 67139f7f9bSDimitry Andric case TargetCXXABI::GenericARM: 68139f7f9bSDimitry Andric case TargetCXXABI::iOS: 6959d1ed5bSDimitry Andric case TargetCXXABI::iOS64: 700623d748SDimitry Andric case TargetCXXABI::WatchOS: 71ef6fa9e2SDimitry Andric case TargetCXXABI::GenericMIPS: 72139f7f9bSDimitry Andric case TargetCXXABI::GenericItanium: 730623d748SDimitry Andric case TargetCXXABI::WebAssembly: 7459d1ed5bSDimitry Andric return CreateItaniumCXXABI(CGM); 75139f7f9bSDimitry Andric case TargetCXXABI::Microsoft: 7659d1ed5bSDimitry Andric return CreateMicrosoftCXXABI(CGM); 77e580952dSDimitry Andric } 78e580952dSDimitry Andric 79e580952dSDimitry Andric llvm_unreachable("invalid C++ ABI kind"); 80e580952dSDimitry Andric } 81e580952dSDimitry Andric 823dac3a9bSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO, 833dac3a9bSDimitry Andric const PreprocessorOptions &PPO, 843dac3a9bSDimitry Andric const CodeGenOptions &CGO, llvm::Module &M, 8539d628a0SDimitry Andric DiagnosticsEngine &diags, 8639d628a0SDimitry Andric CoverageSourceInfo *CoverageInfo) 873dac3a9bSDimitry Andric : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO), 883dac3a9bSDimitry Andric PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), 890623d748SDimitry Andric Target(C.getTargetInfo()), ABI(createCXXABI(*this)), 90e7145dcbSDimitry Andric VMContext(M.getContext()), Types(*this), VTables(*this), 91e7145dcbSDimitry Andric SanitizerMD(new SanitizerMetadata(*this)) { 92dff0c46cSDimitry Andric 93dff0c46cSDimitry Andric // Initialize the type cache. 94dff0c46cSDimitry Andric llvm::LLVMContext &LLVMContext = M.getContext(); 95dff0c46cSDimitry Andric VoidTy = llvm::Type::getVoidTy(LLVMContext); 96dff0c46cSDimitry Andric Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 97dff0c46cSDimitry Andric Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 98dff0c46cSDimitry Andric Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 99dff0c46cSDimitry Andric Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 100dff0c46cSDimitry Andric FloatTy = llvm::Type::getFloatTy(LLVMContext); 101dff0c46cSDimitry Andric DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 102dff0c46cSDimitry Andric PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 103dff0c46cSDimitry Andric PointerAlignInBytes = 104dff0c46cSDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 1050623d748SDimitry Andric IntAlignInBytes = 1060623d748SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 107dff0c46cSDimitry Andric IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 108dff0c46cSDimitry Andric IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits); 109dff0c46cSDimitry Andric Int8PtrTy = Int8Ty->getPointerTo(0); 110dff0c46cSDimitry Andric Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 111dff0c46cSDimitry Andric 112139f7f9bSDimitry Andric RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 11339d628a0SDimitry Andric BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC(); 114139f7f9bSDimitry Andric 115dff0c46cSDimitry Andric if (LangOpts.ObjC1) 1163b0f4066SDimitry Andric createObjCRuntime(); 117dff0c46cSDimitry Andric if (LangOpts.OpenCL) 1186122f3e6SDimitry Andric createOpenCLRuntime(); 11959d1ed5bSDimitry Andric if (LangOpts.OpenMP) 12059d1ed5bSDimitry Andric createOpenMPRuntime(); 121dff0c46cSDimitry Andric if (LangOpts.CUDA) 1226122f3e6SDimitry Andric createCUDARuntime(); 123f22ef01cSRoman Divacky 1247ae0e2c9SDimitry Andric // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 12539d628a0SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 1267ae0e2c9SDimitry Andric (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 127e7145dcbSDimitry Andric TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(), 128e7145dcbSDimitry Andric getCXXABI().getMangleContext())); 1292754fe60SDimitry Andric 1303b0f4066SDimitry Andric // If debug info or coverage generation is enabled, create the CGDebugInfo 1313b0f4066SDimitry Andric // object. 132e7145dcbSDimitry Andric if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo || 133e7145dcbSDimitry Andric CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) 134e7145dcbSDimitry Andric DebugInfo.reset(new CGDebugInfo(*this)); 1352754fe60SDimitry Andric 1362754fe60SDimitry Andric Block.GlobalUniqueCount = 0; 1372754fe60SDimitry Andric 1380623d748SDimitry Andric if (C.getLangOpts().ObjC1) 139e7145dcbSDimitry Andric ObjCData.reset(new ObjCEntrypoints()); 14059d1ed5bSDimitry Andric 141e7145dcbSDimitry Andric if (CodeGenOpts.hasProfileClangUse()) { 142e7145dcbSDimitry Andric auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 143e7145dcbSDimitry Andric CodeGenOpts.ProfileInstrumentUsePath); 144e7145dcbSDimitry Andric if (auto E = ReaderOrErr.takeError()) { 14559d1ed5bSDimitry Andric unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 1463dac3a9bSDimitry Andric "Could not read profile %0: %1"); 147e7145dcbSDimitry Andric llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { 148e7145dcbSDimitry Andric getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath 149e7145dcbSDimitry Andric << EI.message(); 150e7145dcbSDimitry Andric }); 15133956c43SDimitry Andric } else 15233956c43SDimitry Andric PGOReader = std::move(ReaderOrErr.get()); 15359d1ed5bSDimitry Andric } 15439d628a0SDimitry Andric 15539d628a0SDimitry Andric // If coverage mapping generation is enabled, create the 15639d628a0SDimitry Andric // CoverageMappingModuleGen object. 15739d628a0SDimitry Andric if (CodeGenOpts.CoverageMapping) 15839d628a0SDimitry Andric CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 159f22ef01cSRoman Divacky } 160f22ef01cSRoman Divacky 161e7145dcbSDimitry Andric CodeGenModule::~CodeGenModule() {} 162f22ef01cSRoman Divacky 163f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() { 1647ae0e2c9SDimitry Andric // This is just isGNUFamily(), but we want to force implementors of 1657ae0e2c9SDimitry Andric // new ABIs to decide how best to do this. 1667ae0e2c9SDimitry Andric switch (LangOpts.ObjCRuntime.getKind()) { 1677ae0e2c9SDimitry Andric case ObjCRuntime::GNUstep: 1687ae0e2c9SDimitry Andric case ObjCRuntime::GCC: 1697ae0e2c9SDimitry Andric case ObjCRuntime::ObjFW: 170e7145dcbSDimitry Andric ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 1717ae0e2c9SDimitry Andric return; 1727ae0e2c9SDimitry Andric 1737ae0e2c9SDimitry Andric case ObjCRuntime::FragileMacOSX: 1747ae0e2c9SDimitry Andric case ObjCRuntime::MacOSX: 1757ae0e2c9SDimitry Andric case ObjCRuntime::iOS: 1760623d748SDimitry Andric case ObjCRuntime::WatchOS: 177e7145dcbSDimitry Andric ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 1787ae0e2c9SDimitry Andric return; 1797ae0e2c9SDimitry Andric } 1807ae0e2c9SDimitry Andric llvm_unreachable("bad runtime kind"); 1816122f3e6SDimitry Andric } 1826122f3e6SDimitry Andric 1836122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() { 184e7145dcbSDimitry Andric OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 1856122f3e6SDimitry Andric } 1866122f3e6SDimitry Andric 18759d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() { 188e7145dcbSDimitry Andric // Select a specialized code generation class based on the target, if any. 189e7145dcbSDimitry Andric // If it does not exist use the default implementation. 190e7145dcbSDimitry Andric switch (getTarget().getTriple().getArch()) { 191e7145dcbSDimitry Andric 192e7145dcbSDimitry Andric case llvm::Triple::nvptx: 193e7145dcbSDimitry Andric case llvm::Triple::nvptx64: 194e7145dcbSDimitry Andric assert(getLangOpts().OpenMPIsDevice && 195e7145dcbSDimitry Andric "OpenMP NVPTX is only prepared to deal with device code."); 196e7145dcbSDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this)); 197e7145dcbSDimitry Andric break; 198e7145dcbSDimitry Andric default: 199e7145dcbSDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 200e7145dcbSDimitry Andric break; 201e7145dcbSDimitry Andric } 20259d1ed5bSDimitry Andric } 20359d1ed5bSDimitry Andric 2046122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() { 205e7145dcbSDimitry Andric CUDARuntime.reset(CreateNVCUDARuntime(*this)); 206f22ef01cSRoman Divacky } 207f22ef01cSRoman Divacky 20839d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 20939d628a0SDimitry Andric Replacements[Name] = C; 21039d628a0SDimitry Andric } 21139d628a0SDimitry Andric 212f785676fSDimitry Andric void CodeGenModule::applyReplacements() { 2138f0fd8f6SDimitry Andric for (auto &I : Replacements) { 2148f0fd8f6SDimitry Andric StringRef MangledName = I.first(); 2158f0fd8f6SDimitry Andric llvm::Constant *Replacement = I.second; 216f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 217f785676fSDimitry Andric if (!Entry) 218f785676fSDimitry Andric continue; 21959d1ed5bSDimitry Andric auto *OldF = cast<llvm::Function>(Entry); 22059d1ed5bSDimitry Andric auto *NewF = dyn_cast<llvm::Function>(Replacement); 221f785676fSDimitry Andric if (!NewF) { 22259d1ed5bSDimitry Andric if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 22359d1ed5bSDimitry Andric NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 22459d1ed5bSDimitry Andric } else { 22559d1ed5bSDimitry Andric auto *CE = cast<llvm::ConstantExpr>(Replacement); 226f785676fSDimitry Andric assert(CE->getOpcode() == llvm::Instruction::BitCast || 227f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::GetElementPtr); 228f785676fSDimitry Andric NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 229f785676fSDimitry Andric } 23059d1ed5bSDimitry Andric } 231f785676fSDimitry Andric 232f785676fSDimitry Andric // Replace old with new, but keep the old order. 233f785676fSDimitry Andric OldF->replaceAllUsesWith(Replacement); 234f785676fSDimitry Andric if (NewF) { 235f785676fSDimitry Andric NewF->removeFromParent(); 2360623d748SDimitry Andric OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 2370623d748SDimitry Andric NewF); 238f785676fSDimitry Andric } 239f785676fSDimitry Andric OldF->eraseFromParent(); 240f785676fSDimitry Andric } 241f785676fSDimitry Andric } 242f785676fSDimitry Andric 2430623d748SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 2440623d748SDimitry Andric GlobalValReplacements.push_back(std::make_pair(GV, C)); 2450623d748SDimitry Andric } 2460623d748SDimitry Andric 2470623d748SDimitry Andric void CodeGenModule::applyGlobalValReplacements() { 2480623d748SDimitry Andric for (auto &I : GlobalValReplacements) { 2490623d748SDimitry Andric llvm::GlobalValue *GV = I.first; 2500623d748SDimitry Andric llvm::Constant *C = I.second; 2510623d748SDimitry Andric 2520623d748SDimitry Andric GV->replaceAllUsesWith(C); 2530623d748SDimitry Andric GV->eraseFromParent(); 2540623d748SDimitry Andric } 2550623d748SDimitry Andric } 2560623d748SDimitry Andric 25759d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a 25859d1ed5bSDimitry Andric // linear structure. 259e7145dcbSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal( 260e7145dcbSDimitry Andric const llvm::GlobalIndirectSymbol &GIS) { 261e7145dcbSDimitry Andric llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited; 262e7145dcbSDimitry Andric const llvm::Constant *C = &GIS; 26359d1ed5bSDimitry Andric for (;;) { 26459d1ed5bSDimitry Andric C = C->stripPointerCasts(); 26559d1ed5bSDimitry Andric if (auto *GO = dyn_cast<llvm::GlobalObject>(C)) 26659d1ed5bSDimitry Andric return GO; 26759d1ed5bSDimitry Andric // stripPointerCasts will not walk over weak aliases. 268e7145dcbSDimitry Andric auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C); 269e7145dcbSDimitry Andric if (!GIS2) 27059d1ed5bSDimitry Andric return nullptr; 271e7145dcbSDimitry Andric if (!Visited.insert(GIS2).second) 27259d1ed5bSDimitry Andric return nullptr; 273e7145dcbSDimitry Andric C = GIS2->getIndirectSymbol(); 27459d1ed5bSDimitry Andric } 27559d1ed5bSDimitry Andric } 27659d1ed5bSDimitry Andric 277f785676fSDimitry Andric void CodeGenModule::checkAliases() { 27859d1ed5bSDimitry Andric // Check if the constructed aliases are well formed. It is really unfortunate 27959d1ed5bSDimitry Andric // that we have to do this in CodeGen, but we only construct mangled names 28059d1ed5bSDimitry Andric // and aliases during codegen. 281f785676fSDimitry Andric bool Error = false; 28259d1ed5bSDimitry Andric DiagnosticsEngine &Diags = getDiags(); 2838f0fd8f6SDimitry Andric for (const GlobalDecl &GD : Aliases) { 28459d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 285e7145dcbSDimitry Andric SourceLocation Location; 286e7145dcbSDimitry Andric bool IsIFunc = D->hasAttr<IFuncAttr>(); 287e7145dcbSDimitry Andric if (const Attr *A = D->getDefiningAttr()) 288e7145dcbSDimitry Andric Location = A->getLocation(); 289e7145dcbSDimitry Andric else 290e7145dcbSDimitry Andric llvm_unreachable("Not an alias or ifunc?"); 291f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 292f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 293e7145dcbSDimitry Andric auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry); 29459d1ed5bSDimitry Andric const llvm::GlobalValue *GV = getAliasedGlobal(*Alias); 29559d1ed5bSDimitry Andric if (!GV) { 296f785676fSDimitry Andric Error = true; 297e7145dcbSDimitry Andric Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 29859d1ed5bSDimitry Andric } else if (GV->isDeclaration()) { 299f785676fSDimitry Andric Error = true; 300e7145dcbSDimitry Andric Diags.Report(Location, diag::err_alias_to_undefined) 301e7145dcbSDimitry Andric << IsIFunc << IsIFunc; 302e7145dcbSDimitry Andric } else if (IsIFunc) { 303e7145dcbSDimitry Andric // Check resolver function type. 304e7145dcbSDimitry Andric llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>( 305e7145dcbSDimitry Andric GV->getType()->getPointerElementType()); 306e7145dcbSDimitry Andric assert(FTy); 307e7145dcbSDimitry Andric if (!FTy->getReturnType()->isPointerTy()) 308e7145dcbSDimitry Andric Diags.Report(Location, diag::err_ifunc_resolver_return); 309e7145dcbSDimitry Andric if (FTy->getNumParams()) 310e7145dcbSDimitry Andric Diags.Report(Location, diag::err_ifunc_resolver_params); 31159d1ed5bSDimitry Andric } 31259d1ed5bSDimitry Andric 313e7145dcbSDimitry Andric llvm::Constant *Aliasee = Alias->getIndirectSymbol(); 31459d1ed5bSDimitry Andric llvm::GlobalValue *AliaseeGV; 31559d1ed5bSDimitry Andric if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 31659d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 31759d1ed5bSDimitry Andric else 31859d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 31959d1ed5bSDimitry Andric 32059d1ed5bSDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 32159d1ed5bSDimitry Andric StringRef AliasSection = SA->getName(); 32259d1ed5bSDimitry Andric if (AliasSection != AliaseeGV->getSection()) 32359d1ed5bSDimitry Andric Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 324e7145dcbSDimitry Andric << AliasSection << IsIFunc << IsIFunc; 32559d1ed5bSDimitry Andric } 32659d1ed5bSDimitry Andric 32759d1ed5bSDimitry Andric // We have to handle alias to weak aliases in here. LLVM itself disallows 32859d1ed5bSDimitry Andric // this since the object semantics would not match the IL one. For 32959d1ed5bSDimitry Andric // compatibility with gcc we implement it by just pointing the alias 33059d1ed5bSDimitry Andric // to its aliasee's aliasee. We also warn, since the user is probably 33159d1ed5bSDimitry Andric // expecting the link to be weak. 332e7145dcbSDimitry Andric if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) { 333e7145dcbSDimitry Andric if (GA->isInterposable()) { 334e7145dcbSDimitry Andric Diags.Report(Location, diag::warn_alias_to_weak_alias) 335e7145dcbSDimitry Andric << GV->getName() << GA->getName() << IsIFunc; 33659d1ed5bSDimitry Andric Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 337e7145dcbSDimitry Andric GA->getIndirectSymbol(), Alias->getType()); 338e7145dcbSDimitry Andric Alias->setIndirectSymbol(Aliasee); 33959d1ed5bSDimitry Andric } 340f785676fSDimitry Andric } 341f785676fSDimitry Andric } 342f785676fSDimitry Andric if (!Error) 343f785676fSDimitry Andric return; 344f785676fSDimitry Andric 3458f0fd8f6SDimitry Andric for (const GlobalDecl &GD : Aliases) { 346f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 347f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 348e7145dcbSDimitry Andric auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry); 349f785676fSDimitry Andric Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 350f785676fSDimitry Andric Alias->eraseFromParent(); 351f785676fSDimitry Andric } 352f785676fSDimitry Andric } 353f785676fSDimitry Andric 35459d1ed5bSDimitry Andric void CodeGenModule::clear() { 35559d1ed5bSDimitry Andric DeferredDeclsToEmit.clear(); 35633956c43SDimitry Andric if (OpenMPRuntime) 35733956c43SDimitry Andric OpenMPRuntime->clear(); 35859d1ed5bSDimitry Andric } 35959d1ed5bSDimitry Andric 36059d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 36159d1ed5bSDimitry Andric StringRef MainFile) { 36259d1ed5bSDimitry Andric if (!hasDiagnostics()) 36359d1ed5bSDimitry Andric return; 36459d1ed5bSDimitry Andric if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 36559d1ed5bSDimitry Andric if (MainFile.empty()) 36659d1ed5bSDimitry Andric MainFile = "<stdin>"; 36759d1ed5bSDimitry Andric Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 36859d1ed5bSDimitry Andric } else 36959d1ed5bSDimitry Andric Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing 37059d1ed5bSDimitry Andric << Mismatched; 37159d1ed5bSDimitry Andric } 37259d1ed5bSDimitry Andric 373f22ef01cSRoman Divacky void CodeGenModule::Release() { 374f22ef01cSRoman Divacky EmitDeferred(); 3750623d748SDimitry Andric applyGlobalValReplacements(); 376f785676fSDimitry Andric applyReplacements(); 377f785676fSDimitry Andric checkAliases(); 378f22ef01cSRoman Divacky EmitCXXGlobalInitFunc(); 379f22ef01cSRoman Divacky EmitCXXGlobalDtorFunc(); 380284c1978SDimitry Andric EmitCXXThreadLocalInitFunc(); 3816122f3e6SDimitry Andric if (ObjCRuntime) 3826122f3e6SDimitry Andric if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 383f22ef01cSRoman Divacky AddGlobalCtor(ObjCInitFunction); 38433956c43SDimitry Andric if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice && 38533956c43SDimitry Andric CUDARuntime) { 38633956c43SDimitry Andric if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction()) 38733956c43SDimitry Andric AddGlobalCtor(CudaCtorFunction); 38833956c43SDimitry Andric if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction()) 38933956c43SDimitry Andric AddGlobalDtor(CudaDtorFunction); 39033956c43SDimitry Andric } 391ea942507SDimitry Andric if (OpenMPRuntime) 392ea942507SDimitry Andric if (llvm::Function *OpenMPRegistrationFunction = 393ea942507SDimitry Andric OpenMPRuntime->emitRegistrationFunction()) 394ea942507SDimitry Andric AddGlobalCtor(OpenMPRegistrationFunction, 0); 3950623d748SDimitry Andric if (PGOReader) { 396e7145dcbSDimitry Andric getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext)); 3970623d748SDimitry Andric if (PGOStats.hasDiagnostics()) 39859d1ed5bSDimitry Andric PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 3990623d748SDimitry Andric } 400f22ef01cSRoman Divacky EmitCtorList(GlobalCtors, "llvm.global_ctors"); 401f22ef01cSRoman Divacky EmitCtorList(GlobalDtors, "llvm.global_dtors"); 4026122f3e6SDimitry Andric EmitGlobalAnnotations(); 403284c1978SDimitry Andric EmitStaticExternCAliases(); 40439d628a0SDimitry Andric EmitDeferredUnusedCoverageMappings(); 40539d628a0SDimitry Andric if (CoverageMapping) 40639d628a0SDimitry Andric CoverageMapping->emit(); 407e7145dcbSDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 408e7145dcbSDimitry Andric CodeGenFunction(*this).EmitCfiCheckFail(); 40959d1ed5bSDimitry Andric emitLLVMUsed(); 410e7145dcbSDimitry Andric if (SanStats) 411e7145dcbSDimitry Andric SanStats->finish(); 412ffd1746dSEd Schouten 413f785676fSDimitry Andric if (CodeGenOpts.Autolink && 414f785676fSDimitry Andric (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 415139f7f9bSDimitry Andric EmitModuleLinkOptions(); 416139f7f9bSDimitry Andric } 4170623d748SDimitry Andric if (CodeGenOpts.DwarfVersion) { 418f785676fSDimitry Andric // We actually want the latest version when there are conflicts. 419f785676fSDimitry Andric // We can change from Warning to Latest if such mode is supported. 420f785676fSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 421f785676fSDimitry Andric CodeGenOpts.DwarfVersion); 4220623d748SDimitry Andric } 4230623d748SDimitry Andric if (CodeGenOpts.EmitCodeView) { 4240623d748SDimitry Andric // Indicate that we want CodeView in the metadata. 4250623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 4260623d748SDimitry Andric } 4270623d748SDimitry Andric if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 4280623d748SDimitry Andric // We don't support LTO with 2 with different StrictVTablePointers 4290623d748SDimitry Andric // FIXME: we could support it by stripping all the information introduced 4300623d748SDimitry Andric // by StrictVTablePointers. 4310623d748SDimitry Andric 4320623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 4330623d748SDimitry Andric 4340623d748SDimitry Andric llvm::Metadata *Ops[2] = { 4350623d748SDimitry Andric llvm::MDString::get(VMContext, "StrictVTablePointers"), 4360623d748SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 4370623d748SDimitry Andric llvm::Type::getInt32Ty(VMContext), 1))}; 4380623d748SDimitry Andric 4390623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Require, 4400623d748SDimitry Andric "StrictVTablePointersRequirement", 4410623d748SDimitry Andric llvm::MDNode::get(VMContext, Ops)); 4420623d748SDimitry Andric } 443f785676fSDimitry Andric if (DebugInfo) 44459d1ed5bSDimitry Andric // We support a single version in the linked module. The LLVM 44559d1ed5bSDimitry Andric // parser will drop debug info with a different version number 44659d1ed5bSDimitry Andric // (and warn about it, too). 44759d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 448f785676fSDimitry Andric llvm::DEBUG_METADATA_VERSION); 449139f7f9bSDimitry Andric 45059d1ed5bSDimitry Andric // We need to record the widths of enums and wchar_t, so that we can generate 45159d1ed5bSDimitry Andric // the correct build attributes in the ARM backend. 45259d1ed5bSDimitry Andric llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 45359d1ed5bSDimitry Andric if ( Arch == llvm::Triple::arm 45459d1ed5bSDimitry Andric || Arch == llvm::Triple::armeb 45559d1ed5bSDimitry Andric || Arch == llvm::Triple::thumb 45659d1ed5bSDimitry Andric || Arch == llvm::Triple::thumbeb) { 45759d1ed5bSDimitry Andric // Width of wchar_t in bytes 45859d1ed5bSDimitry Andric uint64_t WCharWidth = 45959d1ed5bSDimitry Andric Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 46059d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 46159d1ed5bSDimitry Andric 46259d1ed5bSDimitry Andric // The minimum width of an enum in bytes 46359d1ed5bSDimitry Andric uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 46459d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 46559d1ed5bSDimitry Andric } 46659d1ed5bSDimitry Andric 4670623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 4680623d748SDimitry Andric // Indicate that we want cross-DSO control flow integrity checks. 4690623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 4700623d748SDimitry Andric } 4710623d748SDimitry Andric 472e7145dcbSDimitry Andric if (LangOpts.CUDAIsDevice && getTarget().getTriple().isNVPTX()) { 473e7145dcbSDimitry Andric // Indicate whether __nvvm_reflect should be configured to flush denormal 474e7145dcbSDimitry Andric // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 475e7145dcbSDimitry Andric // property.) 476e7145dcbSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 477e7145dcbSDimitry Andric LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0); 47839d628a0SDimitry Andric } 47939d628a0SDimitry Andric 480e7145dcbSDimitry Andric if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 481e7145dcbSDimitry Andric assert(PLevel < 3 && "Invalid PIC Level"); 482e7145dcbSDimitry Andric getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 483e7145dcbSDimitry Andric if (Context.getLangOpts().PIE) 484e7145dcbSDimitry Andric getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 48539d628a0SDimitry Andric } 48639d628a0SDimitry Andric 4872754fe60SDimitry Andric SimplifyPersonality(); 4882754fe60SDimitry Andric 489ffd1746dSEd Schouten if (getCodeGenOpts().EmitDeclMetadata) 490ffd1746dSEd Schouten EmitDeclMetadata(); 491bd5abe19SDimitry Andric 492bd5abe19SDimitry Andric if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 493bd5abe19SDimitry Andric EmitCoverageFile(); 4946122f3e6SDimitry Andric 4956122f3e6SDimitry Andric if (DebugInfo) 4966122f3e6SDimitry Andric DebugInfo->finalize(); 497f785676fSDimitry Andric 498f785676fSDimitry Andric EmitVersionIdentMetadata(); 49959d1ed5bSDimitry Andric 50059d1ed5bSDimitry Andric EmitTargetMetadata(); 501f22ef01cSRoman Divacky } 502f22ef01cSRoman Divacky 5033b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 5043b0f4066SDimitry Andric // Make sure that this type is translated. 5053b0f4066SDimitry Andric Types.UpdateCompletedType(TD); 5063b0f4066SDimitry Andric } 5073b0f4066SDimitry Andric 508e7145dcbSDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 509e7145dcbSDimitry Andric // Make sure that this type is translated. 510e7145dcbSDimitry Andric Types.RefreshTypeCacheForClass(RD); 511e7145dcbSDimitry Andric } 512e7145dcbSDimitry Andric 5132754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 5142754fe60SDimitry Andric if (!TBAA) 51559d1ed5bSDimitry Andric return nullptr; 5162754fe60SDimitry Andric return TBAA->getTBAAInfo(QTy); 5172754fe60SDimitry Andric } 5182754fe60SDimitry Andric 519dff0c46cSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 520dff0c46cSDimitry Andric if (!TBAA) 52159d1ed5bSDimitry Andric return nullptr; 522dff0c46cSDimitry Andric return TBAA->getTBAAInfoForVTablePtr(); 523dff0c46cSDimitry Andric } 524dff0c46cSDimitry Andric 5253861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 5263861d79fSDimitry Andric if (!TBAA) 52759d1ed5bSDimitry Andric return nullptr; 5283861d79fSDimitry Andric return TBAA->getTBAAStructInfo(QTy); 5293861d79fSDimitry Andric } 5303861d79fSDimitry Andric 531139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy, 532139f7f9bSDimitry Andric llvm::MDNode *AccessN, 533139f7f9bSDimitry Andric uint64_t O) { 534139f7f9bSDimitry Andric if (!TBAA) 53559d1ed5bSDimitry Andric return nullptr; 536139f7f9bSDimitry Andric return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O); 537139f7f9bSDimitry Andric } 538139f7f9bSDimitry Andric 539f785676fSDimitry Andric /// Decorate the instruction with a TBAA tag. For both scalar TBAA 540f785676fSDimitry Andric /// and struct-path aware TBAA, the tag has the same format: 541f785676fSDimitry Andric /// base type, access type and offset. 542284c1978SDimitry Andric /// When ConvertTypeToTag is true, we create a tag based on the scalar type. 5430623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 544284c1978SDimitry Andric llvm::MDNode *TBAAInfo, 545284c1978SDimitry Andric bool ConvertTypeToTag) { 546f785676fSDimitry Andric if (ConvertTypeToTag && TBAA) 547284c1978SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, 548284c1978SDimitry Andric TBAA->getTBAAScalarTagInfo(TBAAInfo)); 549284c1978SDimitry Andric else 5502754fe60SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 5512754fe60SDimitry Andric } 5522754fe60SDimitry Andric 5530623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup( 5540623d748SDimitry Andric llvm::Instruction *I, const CXXRecordDecl *RD) { 5550623d748SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 5560623d748SDimitry Andric auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD); 5570623d748SDimitry Andric // Check if we have to wrap MDString in MDNode. 5580623d748SDimitry Andric if (!MetaDataNode) 5590623d748SDimitry Andric MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD); 5600623d748SDimitry Andric I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode); 5610623d748SDimitry Andric } 5620623d748SDimitry Andric 56359d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) { 56459d1ed5bSDimitry Andric unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 56559d1ed5bSDimitry Andric getDiags().Report(Context.getFullLoc(loc), diagID) << message; 566f22ef01cSRoman Divacky } 567f22ef01cSRoman Divacky 568f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 569f22ef01cSRoman Divacky /// specified stmt yet. 570f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 5716122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 572f22ef01cSRoman Divacky "cannot compile this %0 yet"); 573f22ef01cSRoman Divacky std::string Msg = Type; 574f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 575f22ef01cSRoman Divacky << Msg << S->getSourceRange(); 576f22ef01cSRoman Divacky } 577f22ef01cSRoman Divacky 578f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 579f22ef01cSRoman Divacky /// specified decl yet. 580f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 5816122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 582f22ef01cSRoman Divacky "cannot compile this %0 yet"); 583f22ef01cSRoman Divacky std::string Msg = Type; 584f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 585f22ef01cSRoman Divacky } 586f22ef01cSRoman Divacky 58717a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 58817a519f9SDimitry Andric return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 58917a519f9SDimitry Andric } 59017a519f9SDimitry Andric 591f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 5922754fe60SDimitry Andric const NamedDecl *D) const { 593f22ef01cSRoman Divacky // Internal definitions always have default visibility. 594f22ef01cSRoman Divacky if (GV->hasLocalLinkage()) { 595f22ef01cSRoman Divacky GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 596f22ef01cSRoman Divacky return; 597f22ef01cSRoman Divacky } 598f22ef01cSRoman Divacky 5992754fe60SDimitry Andric // Set visibility for definitions. 600139f7f9bSDimitry Andric LinkageInfo LV = D->getLinkageAndVisibility(); 601139f7f9bSDimitry Andric if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 602139f7f9bSDimitry Andric GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 603f22ef01cSRoman Divacky } 604f22ef01cSRoman Divacky 6057ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 6067ae0e2c9SDimitry Andric return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 6077ae0e2c9SDimitry Andric .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 6087ae0e2c9SDimitry Andric .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 6097ae0e2c9SDimitry Andric .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 6107ae0e2c9SDimitry Andric .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 6117ae0e2c9SDimitry Andric } 6127ae0e2c9SDimitry Andric 6137ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 6147ae0e2c9SDimitry Andric CodeGenOptions::TLSModel M) { 6157ae0e2c9SDimitry Andric switch (M) { 6167ae0e2c9SDimitry Andric case CodeGenOptions::GeneralDynamicTLSModel: 6177ae0e2c9SDimitry Andric return llvm::GlobalVariable::GeneralDynamicTLSModel; 6187ae0e2c9SDimitry Andric case CodeGenOptions::LocalDynamicTLSModel: 6197ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalDynamicTLSModel; 6207ae0e2c9SDimitry Andric case CodeGenOptions::InitialExecTLSModel: 6217ae0e2c9SDimitry Andric return llvm::GlobalVariable::InitialExecTLSModel; 6227ae0e2c9SDimitry Andric case CodeGenOptions::LocalExecTLSModel: 6237ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalExecTLSModel; 6247ae0e2c9SDimitry Andric } 6257ae0e2c9SDimitry Andric llvm_unreachable("Invalid TLS model!"); 6267ae0e2c9SDimitry Andric } 6277ae0e2c9SDimitry Andric 62839d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 629284c1978SDimitry Andric assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 6307ae0e2c9SDimitry Andric 63139d628a0SDimitry Andric llvm::GlobalValue::ThreadLocalMode TLM; 6323861d79fSDimitry Andric TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 6337ae0e2c9SDimitry Andric 6347ae0e2c9SDimitry Andric // Override the TLS model if it is explicitly specified. 63559d1ed5bSDimitry Andric if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 6367ae0e2c9SDimitry Andric TLM = GetLLVMTLSModel(Attr->getModel()); 6377ae0e2c9SDimitry Andric } 6387ae0e2c9SDimitry Andric 6397ae0e2c9SDimitry Andric GV->setThreadLocalMode(TLM); 6407ae0e2c9SDimitry Andric } 6417ae0e2c9SDimitry Andric 6426122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 643444ed5c5SDimitry Andric GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 644444ed5c5SDimitry Andric 645444ed5c5SDimitry Andric // Some ABIs don't have constructor variants. Make sure that base and 646444ed5c5SDimitry Andric // complete constructors get mangled the same. 647444ed5c5SDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 648444ed5c5SDimitry Andric if (!getTarget().getCXXABI().hasConstructorVariants()) { 649444ed5c5SDimitry Andric CXXCtorType OrigCtorType = GD.getCtorType(); 650444ed5c5SDimitry Andric assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 651444ed5c5SDimitry Andric if (OrigCtorType == Ctor_Base) 652444ed5c5SDimitry Andric CanonicalGD = GlobalDecl(CD, Ctor_Complete); 653444ed5c5SDimitry Andric } 654444ed5c5SDimitry Andric } 655444ed5c5SDimitry Andric 656444ed5c5SDimitry Andric StringRef &FoundStr = MangledDeclNames[CanonicalGD]; 65759d1ed5bSDimitry Andric if (!FoundStr.empty()) 65859d1ed5bSDimitry Andric return FoundStr; 659f22ef01cSRoman Divacky 66059d1ed5bSDimitry Andric const auto *ND = cast<NamedDecl>(GD.getDecl()); 661dff0c46cSDimitry Andric SmallString<256> Buffer; 66259d1ed5bSDimitry Andric StringRef Str; 66359d1ed5bSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 6642754fe60SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 66559d1ed5bSDimitry Andric if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) 6662754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 66759d1ed5bSDimitry Andric else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) 6682754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 669ffd1746dSEd Schouten else 6702754fe60SDimitry Andric getCXXABI().getMangleContext().mangleName(ND, Out); 67159d1ed5bSDimitry Andric Str = Out.str(); 67259d1ed5bSDimitry Andric } else { 67359d1ed5bSDimitry Andric IdentifierInfo *II = ND->getIdentifier(); 67459d1ed5bSDimitry Andric assert(II && "Attempt to mangle unnamed decl."); 67559d1ed5bSDimitry Andric Str = II->getName(); 676ffd1746dSEd Schouten } 677ffd1746dSEd Schouten 67839d628a0SDimitry Andric // Keep the first result in the case of a mangling collision. 67939d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Str, GD)); 68039d628a0SDimitry Andric return FoundStr = Result.first->first(); 68159d1ed5bSDimitry Andric } 68259d1ed5bSDimitry Andric 68359d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 684ffd1746dSEd Schouten const BlockDecl *BD) { 6852754fe60SDimitry Andric MangleContext &MangleCtx = getCXXABI().getMangleContext(); 6862754fe60SDimitry Andric const Decl *D = GD.getDecl(); 68759d1ed5bSDimitry Andric 68859d1ed5bSDimitry Andric SmallString<256> Buffer; 68959d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(Buffer); 69059d1ed5bSDimitry Andric if (!D) 6917ae0e2c9SDimitry Andric MangleCtx.mangleGlobalBlock(BD, 6927ae0e2c9SDimitry Andric dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 69359d1ed5bSDimitry Andric else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 6942754fe60SDimitry Andric MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 69559d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 6962754fe60SDimitry Andric MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 6972754fe60SDimitry Andric else 6982754fe60SDimitry Andric MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 69959d1ed5bSDimitry Andric 70039d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 70139d628a0SDimitry Andric return Result.first->first(); 702f22ef01cSRoman Divacky } 703f22ef01cSRoman Divacky 7046122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 705f22ef01cSRoman Divacky return getModule().getNamedValue(Name); 706f22ef01cSRoman Divacky } 707f22ef01cSRoman Divacky 708f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before 709f22ef01cSRoman Divacky /// main() runs. 71059d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 71159d1ed5bSDimitry Andric llvm::Constant *AssociatedData) { 712f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 71359d1ed5bSDimitry Andric GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 714f22ef01cSRoman Divacky } 715f22ef01cSRoman Divacky 716f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called 717f22ef01cSRoman Divacky /// when the module is unloaded. 718f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) { 719f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 72059d1ed5bSDimitry Andric GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 721f22ef01cSRoman Divacky } 722f22ef01cSRoman Divacky 723f22ef01cSRoman Divacky void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 724f22ef01cSRoman Divacky // Ctor function type is void()*. 725bd5abe19SDimitry Andric llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 726f22ef01cSRoman Divacky llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 727f22ef01cSRoman Divacky 72859d1ed5bSDimitry Andric // Get the type of a ctor entry, { i32, void ()*, i8* }. 72959d1ed5bSDimitry Andric llvm::StructType *CtorStructTy = llvm::StructType::get( 73039d628a0SDimitry Andric Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr); 731f22ef01cSRoman Divacky 732f22ef01cSRoman Divacky // Construct the constructor and destructor arrays. 733dff0c46cSDimitry Andric SmallVector<llvm::Constant *, 8> Ctors; 7348f0fd8f6SDimitry Andric for (const auto &I : Fns) { 735dff0c46cSDimitry Andric llvm::Constant *S[] = { 7368f0fd8f6SDimitry Andric llvm::ConstantInt::get(Int32Ty, I.Priority, false), 7378f0fd8f6SDimitry Andric llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy), 7388f0fd8f6SDimitry Andric (I.AssociatedData 7398f0fd8f6SDimitry Andric ? llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy) 7408f0fd8f6SDimitry Andric : llvm::Constant::getNullValue(VoidPtrTy))}; 741f22ef01cSRoman Divacky Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 742f22ef01cSRoman Divacky } 743f22ef01cSRoman Divacky 744f22ef01cSRoman Divacky if (!Ctors.empty()) { 745f22ef01cSRoman Divacky llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 746f22ef01cSRoman Divacky new llvm::GlobalVariable(TheModule, AT, false, 747f22ef01cSRoman Divacky llvm::GlobalValue::AppendingLinkage, 748f22ef01cSRoman Divacky llvm::ConstantArray::get(AT, Ctors), 749f22ef01cSRoman Divacky GlobalName); 750f22ef01cSRoman Divacky } 751f22ef01cSRoman Divacky } 752f22ef01cSRoman Divacky 753f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes 754f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 75559d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 756f785676fSDimitry Andric 757e580952dSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 758f22ef01cSRoman Divacky 75959d1ed5bSDimitry Andric if (isa<CXXDestructorDecl>(D) && 76059d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 76159d1ed5bSDimitry Andric GD.getDtorType())) { 76259d1ed5bSDimitry Andric // Destructor variants in the Microsoft C++ ABI are always internal or 76359d1ed5bSDimitry Andric // linkonce_odr thunks emitted on an as-needed basis. 76459d1ed5bSDimitry Andric return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage 76559d1ed5bSDimitry Andric : llvm::GlobalValue::LinkOnceODRLinkage; 766f22ef01cSRoman Divacky } 767f22ef01cSRoman Divacky 768e7145dcbSDimitry Andric if (isa<CXXConstructorDecl>(D) && 769e7145dcbSDimitry Andric cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 770e7145dcbSDimitry Andric Context.getTargetInfo().getCXXABI().isMicrosoft()) { 771e7145dcbSDimitry Andric // Our approach to inheriting constructors is fundamentally different from 772e7145dcbSDimitry Andric // that used by the MS ABI, so keep our inheriting constructor thunks 773e7145dcbSDimitry Andric // internal rather than trying to pick an unambiguous mangling for them. 774e7145dcbSDimitry Andric return llvm::GlobalValue::InternalLinkage; 775e7145dcbSDimitry Andric } 776e7145dcbSDimitry Andric 77759d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false); 77859d1ed5bSDimitry Andric } 779f22ef01cSRoman Divacky 78097bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) { 78197bc6c73SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 78297bc6c73SDimitry Andric 78397bc6c73SDimitry Andric if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) { 78497bc6c73SDimitry Andric if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) { 78597bc6c73SDimitry Andric // Don't dllexport/import destructor thunks. 78697bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 78797bc6c73SDimitry Andric return; 78897bc6c73SDimitry Andric } 78997bc6c73SDimitry Andric } 79097bc6c73SDimitry Andric 79197bc6c73SDimitry Andric if (FD->hasAttr<DLLImportAttr>()) 79297bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 79397bc6c73SDimitry Andric else if (FD->hasAttr<DLLExportAttr>()) 79497bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 79597bc6c73SDimitry Andric else 79697bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 79797bc6c73SDimitry Andric } 79897bc6c73SDimitry Andric 799e7145dcbSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 8000623d748SDimitry Andric llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 8010623d748SDimitry Andric if (!MDS) return nullptr; 8020623d748SDimitry Andric 8030623d748SDimitry Andric llvm::MD5 md5; 8040623d748SDimitry Andric llvm::MD5::MD5Result result; 8050623d748SDimitry Andric md5.update(MDS->getString()); 8060623d748SDimitry Andric md5.final(result); 8070623d748SDimitry Andric uint64_t id = 0; 8080623d748SDimitry Andric for (int i = 0; i < 8; ++i) 8090623d748SDimitry Andric id |= static_cast<uint64_t>(result[i]) << (i * 8); 8100623d748SDimitry Andric return llvm::ConstantInt::get(Int64Ty, id); 8110623d748SDimitry Andric } 8120623d748SDimitry Andric 81359d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D, 81459d1ed5bSDimitry Andric llvm::Function *F) { 81559d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 816f22ef01cSRoman Divacky } 817f22ef01cSRoman Divacky 818f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 819f22ef01cSRoman Divacky const CGFunctionInfo &Info, 820f22ef01cSRoman Divacky llvm::Function *F) { 821f22ef01cSRoman Divacky unsigned CallingConv; 822f22ef01cSRoman Divacky AttributeListType AttributeList; 823ea942507SDimitry Andric ConstructAttributeList(F->getName(), Info, D, AttributeList, CallingConv, 824ea942507SDimitry Andric false); 825139f7f9bSDimitry Andric F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList)); 826f22ef01cSRoman Divacky F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 827f22ef01cSRoman Divacky } 828f22ef01cSRoman Divacky 8296122f3e6SDimitry Andric /// Determines whether the language options require us to model 8306122f3e6SDimitry Andric /// unwind exceptions. We treat -fexceptions as mandating this 8316122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions 8326122f3e6SDimitry Andric /// enabled. This means, for example, that C with -fexceptions 8336122f3e6SDimitry Andric /// enables this. 834dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) { 8356122f3e6SDimitry Andric // If exceptions are completely disabled, obviously this is false. 836dff0c46cSDimitry Andric if (!LangOpts.Exceptions) return false; 8376122f3e6SDimitry Andric 8386122f3e6SDimitry Andric // If C++ exceptions are enabled, this is true. 839dff0c46cSDimitry Andric if (LangOpts.CXXExceptions) return true; 8406122f3e6SDimitry Andric 8416122f3e6SDimitry Andric // If ObjC exceptions are enabled, this depends on the ABI. 842dff0c46cSDimitry Andric if (LangOpts.ObjCExceptions) { 8437ae0e2c9SDimitry Andric return LangOpts.ObjCRuntime.hasUnwindExceptions(); 8446122f3e6SDimitry Andric } 8456122f3e6SDimitry Andric 8466122f3e6SDimitry Andric return true; 8476122f3e6SDimitry Andric } 8486122f3e6SDimitry Andric 849f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 850f22ef01cSRoman Divacky llvm::Function *F) { 851f785676fSDimitry Andric llvm::AttrBuilder B; 852f785676fSDimitry Andric 853bd5abe19SDimitry Andric if (CodeGenOpts.UnwindTables) 854f785676fSDimitry Andric B.addAttribute(llvm::Attribute::UWTable); 855bd5abe19SDimitry Andric 856dff0c46cSDimitry Andric if (!hasUnwindExceptions(LangOpts)) 857f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoUnwind); 858f22ef01cSRoman Divacky 8590623d748SDimitry Andric if (LangOpts.getStackProtector() == LangOptions::SSPOn) 8600623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtect); 8610623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 8620623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 8630623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 8640623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectReq); 8650623d748SDimitry Andric 8660623d748SDimitry Andric if (!D) { 8670623d748SDimitry Andric F->addAttributes(llvm::AttributeSet::FunctionIndex, 8680623d748SDimitry Andric llvm::AttributeSet::get( 8690623d748SDimitry Andric F->getContext(), 8700623d748SDimitry Andric llvm::AttributeSet::FunctionIndex, B)); 8710623d748SDimitry Andric return; 8720623d748SDimitry Andric } 8730623d748SDimitry Andric 8746122f3e6SDimitry Andric if (D->hasAttr<NakedAttr>()) { 8756122f3e6SDimitry Andric // Naked implies noinline: we should not be inlining such functions. 876f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Naked); 877f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 87859d1ed5bSDimitry Andric } else if (D->hasAttr<NoDuplicateAttr>()) { 87959d1ed5bSDimitry Andric B.addAttribute(llvm::Attribute::NoDuplicate); 880f785676fSDimitry Andric } else if (D->hasAttr<NoInlineAttr>()) { 881f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 88259d1ed5bSDimitry Andric } else if (D->hasAttr<AlwaysInlineAttr>() && 883f785676fSDimitry Andric !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex, 884f785676fSDimitry Andric llvm::Attribute::NoInline)) { 885f785676fSDimitry Andric // (noinline wins over always_inline, and we can't specify both in IR) 886f785676fSDimitry Andric B.addAttribute(llvm::Attribute::AlwaysInline); 8876122f3e6SDimitry Andric } 8882754fe60SDimitry Andric 889f785676fSDimitry Andric if (D->hasAttr<ColdAttr>()) { 89039d628a0SDimitry Andric if (!D->hasAttr<OptimizeNoneAttr>()) 891f785676fSDimitry Andric B.addAttribute(llvm::Attribute::OptimizeForSize); 892f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Cold); 893f785676fSDimitry Andric } 8943861d79fSDimitry Andric 8953861d79fSDimitry Andric if (D->hasAttr<MinSizeAttr>()) 896f785676fSDimitry Andric B.addAttribute(llvm::Attribute::MinSize); 897f22ef01cSRoman Divacky 898f785676fSDimitry Andric F->addAttributes(llvm::AttributeSet::FunctionIndex, 899f785676fSDimitry Andric llvm::AttributeSet::get( 900f785676fSDimitry Andric F->getContext(), llvm::AttributeSet::FunctionIndex, B)); 901f785676fSDimitry Andric 90239d628a0SDimitry Andric if (D->hasAttr<OptimizeNoneAttr>()) { 90339d628a0SDimitry Andric // OptimizeNone implies noinline; we should not be inlining such functions. 90439d628a0SDimitry Andric F->addFnAttr(llvm::Attribute::OptimizeNone); 90539d628a0SDimitry Andric F->addFnAttr(llvm::Attribute::NoInline); 90639d628a0SDimitry Andric 90739d628a0SDimitry Andric // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline. 9080623d748SDimitry Andric F->removeFnAttr(llvm::Attribute::OptimizeForSize); 9090623d748SDimitry Andric F->removeFnAttr(llvm::Attribute::MinSize); 91039d628a0SDimitry Andric assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 91139d628a0SDimitry Andric "OptimizeNone and AlwaysInline on same function!"); 91239d628a0SDimitry Andric 91339d628a0SDimitry Andric // Attribute 'inlinehint' has no effect on 'optnone' functions. 91439d628a0SDimitry Andric // Explicitly remove it from the set of function attributes. 91539d628a0SDimitry Andric F->removeFnAttr(llvm::Attribute::InlineHint); 91639d628a0SDimitry Andric } 91739d628a0SDimitry Andric 918e580952dSDimitry Andric unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 919e580952dSDimitry Andric if (alignment) 920e580952dSDimitry Andric F->setAlignment(alignment); 921e580952dSDimitry Andric 9220623d748SDimitry Andric // Some C++ ABIs require 2-byte alignment for member functions, in order to 9230623d748SDimitry Andric // reserve a bit for differentiating between virtual and non-virtual member 9240623d748SDimitry Andric // functions. If the current target's C++ ABI requires this and this is a 9250623d748SDimitry Andric // member function, set its alignment accordingly. 9260623d748SDimitry Andric if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 927f22ef01cSRoman Divacky if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 928f22ef01cSRoman Divacky F->setAlignment(2); 929f22ef01cSRoman Divacky } 9300623d748SDimitry Andric } 931f22ef01cSRoman Divacky 932f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D, 933f22ef01cSRoman Divacky llvm::GlobalValue *GV) { 9340623d748SDimitry Andric if (const auto *ND = dyn_cast_or_null<NamedDecl>(D)) 9352754fe60SDimitry Andric setGlobalVisibility(GV, ND); 9362754fe60SDimitry Andric else 9372754fe60SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 938f22ef01cSRoman Divacky 9390623d748SDimitry Andric if (D && D->hasAttr<UsedAttr>()) 94059d1ed5bSDimitry Andric addUsedGlobal(GV); 94159d1ed5bSDimitry Andric } 94259d1ed5bSDimitry Andric 94339d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D, 94439d628a0SDimitry Andric llvm::GlobalValue *GV) { 94539d628a0SDimitry Andric SetCommonAttributes(D, GV); 94639d628a0SDimitry Andric 94739d628a0SDimitry Andric // Process the dllexport attribute based on whether the original definition 94839d628a0SDimitry Andric // (not necessarily the aliasee) was exported. 94939d628a0SDimitry Andric if (D->hasAttr<DLLExportAttr>()) 95039d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 95139d628a0SDimitry Andric } 95239d628a0SDimitry Andric 95359d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D, 95459d1ed5bSDimitry Andric llvm::GlobalObject *GO) { 95559d1ed5bSDimitry Andric SetCommonAttributes(D, GO); 956f22ef01cSRoman Divacky 9570623d748SDimitry Andric if (D) 958f22ef01cSRoman Divacky if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 95959d1ed5bSDimitry Andric GO->setSection(SA->getName()); 960f22ef01cSRoman Divacky 96197bc6c73SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 962f22ef01cSRoman Divacky } 963f22ef01cSRoman Divacky 964f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 965f22ef01cSRoman Divacky llvm::Function *F, 966f22ef01cSRoman Divacky const CGFunctionInfo &FI) { 967f22ef01cSRoman Divacky SetLLVMFunctionAttributes(D, FI, F); 968f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, F); 969f22ef01cSRoman Divacky 970f22ef01cSRoman Divacky F->setLinkage(llvm::Function::InternalLinkage); 971f22ef01cSRoman Divacky 97259d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 97359d1ed5bSDimitry Andric } 97459d1ed5bSDimitry Andric 97559d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, 97659d1ed5bSDimitry Andric const NamedDecl *ND) { 97759d1ed5bSDimitry Andric // Set linkage and visibility in case we never see a definition. 97859d1ed5bSDimitry Andric LinkageInfo LV = ND->getLinkageAndVisibility(); 97959d1ed5bSDimitry Andric if (LV.getLinkage() != ExternalLinkage) { 98059d1ed5bSDimitry Andric // Don't set internal linkage on declarations. 98159d1ed5bSDimitry Andric } else { 98259d1ed5bSDimitry Andric if (ND->hasAttr<DLLImportAttr>()) { 98359d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 98459d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 98559d1ed5bSDimitry Andric } else if (ND->hasAttr<DLLExportAttr>()) { 98659d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 98759d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 98859d1ed5bSDimitry Andric } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 98959d1ed5bSDimitry Andric // "extern_weak" is overloaded in LLVM; we probably should have 99059d1ed5bSDimitry Andric // separate linkage types for this. 99159d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 99259d1ed5bSDimitry Andric } 99359d1ed5bSDimitry Andric 99459d1ed5bSDimitry Andric // Set visibility on a declaration only if it's explicit. 99559d1ed5bSDimitry Andric if (LV.isVisibilityExplicit()) 99659d1ed5bSDimitry Andric GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility())); 99759d1ed5bSDimitry Andric } 998f22ef01cSRoman Divacky } 999f22ef01cSRoman Divacky 1000e7145dcbSDimitry Andric void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD, 10010623d748SDimitry Andric llvm::Function *F) { 10020623d748SDimitry Andric // Only if we are checking indirect calls. 10030623d748SDimitry Andric if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 10040623d748SDimitry Andric return; 10050623d748SDimitry Andric 10060623d748SDimitry Andric // Non-static class methods are handled via vtable pointer checks elsewhere. 10070623d748SDimitry Andric if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 10080623d748SDimitry Andric return; 10090623d748SDimitry Andric 10100623d748SDimitry Andric // Additionally, if building with cross-DSO support... 10110623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 10120623d748SDimitry Andric // Don't emit entries for function declarations. In cross-DSO mode these are 10130623d748SDimitry Andric // handled with better precision at run time. 10140623d748SDimitry Andric if (!FD->hasBody()) 10150623d748SDimitry Andric return; 10160623d748SDimitry Andric // Skip available_externally functions. They won't be codegen'ed in the 10170623d748SDimitry Andric // current module anyway. 10180623d748SDimitry Andric if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally) 10190623d748SDimitry Andric return; 10200623d748SDimitry Andric } 10210623d748SDimitry Andric 10220623d748SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 1023e7145dcbSDimitry Andric F->addTypeMetadata(0, MD); 10240623d748SDimitry Andric 10250623d748SDimitry Andric // Emit a hash-based bit set entry for cross-DSO calls. 1026e7145dcbSDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 1027e7145dcbSDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 1028e7145dcbSDimitry Andric F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 10290623d748SDimitry Andric } 10300623d748SDimitry Andric 103139d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 103239d628a0SDimitry Andric bool IsIncompleteFunction, 103339d628a0SDimitry Andric bool IsThunk) { 103433956c43SDimitry Andric if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 10353b0f4066SDimitry Andric // If this is an intrinsic function, set the function's attributes 10363b0f4066SDimitry Andric // to the intrinsic's attributes. 103733956c43SDimitry Andric F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 10383b0f4066SDimitry Andric return; 10393b0f4066SDimitry Andric } 10403b0f4066SDimitry Andric 104159d1ed5bSDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1042f22ef01cSRoman Divacky 1043f22ef01cSRoman Divacky if (!IsIncompleteFunction) 1044dff0c46cSDimitry Andric SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 1045f22ef01cSRoman Divacky 104659d1ed5bSDimitry Andric // Add the Returned attribute for "this", except for iOS 5 and earlier 104759d1ed5bSDimitry Andric // where substantial code, including the libstdc++ dylib, was compiled with 104859d1ed5bSDimitry Andric // GCC and does not actually return "this". 104939d628a0SDimitry Andric if (!IsThunk && getCXXABI().HasThisReturn(GD) && 105059d1ed5bSDimitry Andric !(getTarget().getTriple().isiOS() && 105159d1ed5bSDimitry Andric getTarget().getTriple().isOSVersionLT(6))) { 1052f785676fSDimitry Andric assert(!F->arg_empty() && 1053f785676fSDimitry Andric F->arg_begin()->getType() 1054f785676fSDimitry Andric ->canLosslesslyBitCastTo(F->getReturnType()) && 1055f785676fSDimitry Andric "unexpected this return"); 1056f785676fSDimitry Andric F->addAttribute(1, llvm::Attribute::Returned); 1057f785676fSDimitry Andric } 1058f785676fSDimitry Andric 1059f22ef01cSRoman Divacky // Only a few attributes are set on declarations; these may later be 1060f22ef01cSRoman Divacky // overridden by a definition. 1061f22ef01cSRoman Divacky 106259d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(F, FD); 10632754fe60SDimitry Andric 1064f22ef01cSRoman Divacky if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 1065f22ef01cSRoman Divacky F->setSection(SA->getName()); 1066f785676fSDimitry Andric 1067e7145dcbSDimitry Andric if (FD->isReplaceableGlobalAllocationFunction()) { 1068f785676fSDimitry Andric // A replaceable global allocation function does not act like a builtin by 1069f785676fSDimitry Andric // default, only if it is invoked by a new-expression or delete-expression. 1070f785676fSDimitry Andric F->addAttribute(llvm::AttributeSet::FunctionIndex, 1071f785676fSDimitry Andric llvm::Attribute::NoBuiltin); 10720623d748SDimitry Andric 1073e7145dcbSDimitry Andric // A sane operator new returns a non-aliasing pointer. 1074e7145dcbSDimitry Andric // FIXME: Also add NonNull attribute to the return value 1075e7145dcbSDimitry Andric // for the non-nothrow forms? 1076e7145dcbSDimitry Andric auto Kind = FD->getDeclName().getCXXOverloadedOperator(); 1077e7145dcbSDimitry Andric if (getCodeGenOpts().AssumeSaneOperatorNew && 1078e7145dcbSDimitry Andric (Kind == OO_New || Kind == OO_Array_New)) 1079e7145dcbSDimitry Andric F->addAttribute(llvm::AttributeSet::ReturnIndex, 1080e7145dcbSDimitry Andric llvm::Attribute::NoAlias); 1081e7145dcbSDimitry Andric } 1082e7145dcbSDimitry Andric 1083e7145dcbSDimitry Andric if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 1084e7145dcbSDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1085e7145dcbSDimitry Andric else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 1086e7145dcbSDimitry Andric if (MD->isVirtual()) 1087e7145dcbSDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1088e7145dcbSDimitry Andric 1089e7145dcbSDimitry Andric CreateFunctionTypeMetadata(FD, F); 1090f22ef01cSRoman Divacky } 1091f22ef01cSRoman Divacky 109259d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 1093f22ef01cSRoman Divacky assert(!GV->isDeclaration() && 1094f22ef01cSRoman Divacky "Only globals with definition can force usage."); 109597bc6c73SDimitry Andric LLVMUsed.emplace_back(GV); 1096f22ef01cSRoman Divacky } 1097f22ef01cSRoman Divacky 109859d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 109959d1ed5bSDimitry Andric assert(!GV->isDeclaration() && 110059d1ed5bSDimitry Andric "Only globals with definition can force usage."); 110197bc6c73SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 110259d1ed5bSDimitry Andric } 110359d1ed5bSDimitry Andric 110459d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name, 110559d1ed5bSDimitry Andric std::vector<llvm::WeakVH> &List) { 1106f22ef01cSRoman Divacky // Don't create llvm.used if there is no need. 110759d1ed5bSDimitry Andric if (List.empty()) 1108f22ef01cSRoman Divacky return; 1109f22ef01cSRoman Divacky 111059d1ed5bSDimitry Andric // Convert List to what ConstantArray needs. 1111dff0c46cSDimitry Andric SmallVector<llvm::Constant*, 8> UsedArray; 111259d1ed5bSDimitry Andric UsedArray.resize(List.size()); 111359d1ed5bSDimitry Andric for (unsigned i = 0, e = List.size(); i != e; ++i) { 1114f22ef01cSRoman Divacky UsedArray[i] = 111544f7b0dcSDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 111644f7b0dcSDimitry Andric cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 1117f22ef01cSRoman Divacky } 1118f22ef01cSRoman Divacky 1119f22ef01cSRoman Divacky if (UsedArray.empty()) 1120f22ef01cSRoman Divacky return; 112159d1ed5bSDimitry Andric llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 1122f22ef01cSRoman Divacky 112359d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 112459d1ed5bSDimitry Andric CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 112559d1ed5bSDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), Name); 1126f22ef01cSRoman Divacky 1127f22ef01cSRoman Divacky GV->setSection("llvm.metadata"); 1128f22ef01cSRoman Divacky } 1129f22ef01cSRoman Divacky 113059d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() { 113159d1ed5bSDimitry Andric emitUsed(*this, "llvm.used", LLVMUsed); 113259d1ed5bSDimitry Andric emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 113359d1ed5bSDimitry Andric } 113459d1ed5bSDimitry Andric 1135f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 113639d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 1137f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1138f785676fSDimitry Andric } 1139f785676fSDimitry Andric 1140f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 1141f785676fSDimitry Andric llvm::SmallString<32> Opt; 1142f785676fSDimitry Andric getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 114339d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1144f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1145f785676fSDimitry Andric } 1146f785676fSDimitry Andric 1147f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) { 1148f785676fSDimitry Andric llvm::SmallString<24> Opt; 1149f785676fSDimitry Andric getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 115039d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1151f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1152f785676fSDimitry Andric } 1153f785676fSDimitry Andric 1154139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules 1155139f7f9bSDimitry Andric /// it depends on, using a postorder walk. 115639d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 115739d628a0SDimitry Andric SmallVectorImpl<llvm::Metadata *> &Metadata, 1158139f7f9bSDimitry Andric llvm::SmallPtrSet<Module *, 16> &Visited) { 1159139f7f9bSDimitry Andric // Import this module's parent. 116039d628a0SDimitry Andric if (Mod->Parent && Visited.insert(Mod->Parent).second) { 1161f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 1162139f7f9bSDimitry Andric } 1163139f7f9bSDimitry Andric 1164139f7f9bSDimitry Andric // Import this module's dependencies. 1165139f7f9bSDimitry Andric for (unsigned I = Mod->Imports.size(); I > 0; --I) { 116639d628a0SDimitry Andric if (Visited.insert(Mod->Imports[I - 1]).second) 1167f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 1168139f7f9bSDimitry Andric } 1169139f7f9bSDimitry Andric 1170139f7f9bSDimitry Andric // Add linker options to link against the libraries/frameworks 1171139f7f9bSDimitry Andric // described by this module. 1172f785676fSDimitry Andric llvm::LLVMContext &Context = CGM.getLLVMContext(); 1173139f7f9bSDimitry Andric for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 1174f785676fSDimitry Andric // Link against a framework. Frameworks are currently Darwin only, so we 1175f785676fSDimitry Andric // don't to ask TargetCodeGenInfo for the spelling of the linker option. 1176139f7f9bSDimitry Andric if (Mod->LinkLibraries[I-1].IsFramework) { 117739d628a0SDimitry Andric llvm::Metadata *Args[2] = { 1178139f7f9bSDimitry Andric llvm::MDString::get(Context, "-framework"), 117939d628a0SDimitry Andric llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 1180139f7f9bSDimitry Andric 1181139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 1182139f7f9bSDimitry Andric continue; 1183139f7f9bSDimitry Andric } 1184139f7f9bSDimitry Andric 1185139f7f9bSDimitry Andric // Link against a library. 1186f785676fSDimitry Andric llvm::SmallString<24> Opt; 1187f785676fSDimitry Andric CGM.getTargetCodeGenInfo().getDependentLibraryOption( 1188f785676fSDimitry Andric Mod->LinkLibraries[I-1].Library, Opt); 118939d628a0SDimitry Andric auto *OptString = llvm::MDString::get(Context, Opt); 1190139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, OptString)); 1191139f7f9bSDimitry Andric } 1192139f7f9bSDimitry Andric } 1193139f7f9bSDimitry Andric 1194139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() { 1195139f7f9bSDimitry Andric // Collect the set of all of the modules we want to visit to emit link 1196139f7f9bSDimitry Andric // options, which is essentially the imported modules and all of their 1197139f7f9bSDimitry Andric // non-explicit child modules. 1198139f7f9bSDimitry Andric llvm::SetVector<clang::Module *> LinkModules; 1199139f7f9bSDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 1200139f7f9bSDimitry Andric SmallVector<clang::Module *, 16> Stack; 1201139f7f9bSDimitry Andric 1202139f7f9bSDimitry Andric // Seed the stack with imported modules. 12038f0fd8f6SDimitry Andric for (Module *M : ImportedModules) 12048f0fd8f6SDimitry Andric if (Visited.insert(M).second) 12058f0fd8f6SDimitry Andric Stack.push_back(M); 1206139f7f9bSDimitry Andric 1207139f7f9bSDimitry Andric // Find all of the modules to import, making a little effort to prune 1208139f7f9bSDimitry Andric // non-leaf modules. 1209139f7f9bSDimitry Andric while (!Stack.empty()) { 1210f785676fSDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 1211139f7f9bSDimitry Andric 1212139f7f9bSDimitry Andric bool AnyChildren = false; 1213139f7f9bSDimitry Andric 1214139f7f9bSDimitry Andric // Visit the submodules of this module. 1215139f7f9bSDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 1216139f7f9bSDimitry Andric SubEnd = Mod->submodule_end(); 1217139f7f9bSDimitry Andric Sub != SubEnd; ++Sub) { 1218139f7f9bSDimitry Andric // Skip explicit children; they need to be explicitly imported to be 1219139f7f9bSDimitry Andric // linked against. 1220139f7f9bSDimitry Andric if ((*Sub)->IsExplicit) 1221139f7f9bSDimitry Andric continue; 1222139f7f9bSDimitry Andric 122339d628a0SDimitry Andric if (Visited.insert(*Sub).second) { 1224139f7f9bSDimitry Andric Stack.push_back(*Sub); 1225139f7f9bSDimitry Andric AnyChildren = true; 1226139f7f9bSDimitry Andric } 1227139f7f9bSDimitry Andric } 1228139f7f9bSDimitry Andric 1229139f7f9bSDimitry Andric // We didn't find any children, so add this module to the list of 1230139f7f9bSDimitry Andric // modules to link against. 1231139f7f9bSDimitry Andric if (!AnyChildren) { 1232139f7f9bSDimitry Andric LinkModules.insert(Mod); 1233139f7f9bSDimitry Andric } 1234139f7f9bSDimitry Andric } 1235139f7f9bSDimitry Andric 1236139f7f9bSDimitry Andric // Add link options for all of the imported modules in reverse topological 1237f785676fSDimitry Andric // order. We don't do anything to try to order import link flags with respect 1238f785676fSDimitry Andric // to linker options inserted by things like #pragma comment(). 123939d628a0SDimitry Andric SmallVector<llvm::Metadata *, 16> MetadataArgs; 1240139f7f9bSDimitry Andric Visited.clear(); 12418f0fd8f6SDimitry Andric for (Module *M : LinkModules) 12428f0fd8f6SDimitry Andric if (Visited.insert(M).second) 12438f0fd8f6SDimitry Andric addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 1244139f7f9bSDimitry Andric std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 1245f785676fSDimitry Andric LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 1246139f7f9bSDimitry Andric 1247139f7f9bSDimitry Andric // Add the linker options metadata flag. 1248139f7f9bSDimitry Andric getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options", 1249f785676fSDimitry Andric llvm::MDNode::get(getLLVMContext(), 1250f785676fSDimitry Andric LinkerOptionsMetadata)); 1251139f7f9bSDimitry Andric } 1252139f7f9bSDimitry Andric 1253f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() { 1254f22ef01cSRoman Divacky // Emit code for any potentially referenced deferred decls. Since a 1255f22ef01cSRoman Divacky // previously unused static decl may become used during the generation of code 1256f22ef01cSRoman Divacky // for a static function, iterate until no changes are made. 1257f22ef01cSRoman Divacky 1258f22ef01cSRoman Divacky if (!DeferredVTables.empty()) { 1259139f7f9bSDimitry Andric EmitDeferredVTables(); 1260139f7f9bSDimitry Andric 1261e7145dcbSDimitry Andric // Emitting a vtable doesn't directly cause more vtables to 1262139f7f9bSDimitry Andric // become deferred, although it can cause functions to be 1263e7145dcbSDimitry Andric // emitted that then need those vtables. 1264139f7f9bSDimitry Andric assert(DeferredVTables.empty()); 1265f22ef01cSRoman Divacky } 1266f22ef01cSRoman Divacky 1267e7145dcbSDimitry Andric // Stop if we're out of both deferred vtables and deferred declarations. 126833956c43SDimitry Andric if (DeferredDeclsToEmit.empty()) 126933956c43SDimitry Andric return; 1270139f7f9bSDimitry Andric 127133956c43SDimitry Andric // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 127233956c43SDimitry Andric // work, it will not interfere with this. 127333956c43SDimitry Andric std::vector<DeferredGlobal> CurDeclsToEmit; 127433956c43SDimitry Andric CurDeclsToEmit.swap(DeferredDeclsToEmit); 127533956c43SDimitry Andric 127633956c43SDimitry Andric for (DeferredGlobal &G : CurDeclsToEmit) { 127759d1ed5bSDimitry Andric GlobalDecl D = G.GD; 127833956c43SDimitry Andric G.GV = nullptr; 1279f22ef01cSRoman Divacky 12800623d748SDimitry Andric // We should call GetAddrOfGlobal with IsForDefinition set to true in order 12810623d748SDimitry Andric // to get GlobalValue with exactly the type we need, not something that 12820623d748SDimitry Andric // might had been created for another decl with the same mangled name but 12830623d748SDimitry Andric // different type. 1284e7145dcbSDimitry Andric llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 1285e7145dcbSDimitry Andric GetAddrOfGlobal(D, /*IsForDefinition=*/true)); 1286e7145dcbSDimitry Andric 1287e7145dcbSDimitry Andric // In case of different address spaces, we may still get a cast, even with 1288e7145dcbSDimitry Andric // IsForDefinition equal to true. Query mangled names table to get 1289e7145dcbSDimitry Andric // GlobalValue. 129039d628a0SDimitry Andric if (!GV) 129139d628a0SDimitry Andric GV = GetGlobalValue(getMangledName(D)); 129239d628a0SDimitry Andric 1293e7145dcbSDimitry Andric // Make sure GetGlobalValue returned non-null. 1294e7145dcbSDimitry Andric assert(GV); 1295e7145dcbSDimitry Andric 1296f22ef01cSRoman Divacky // Check to see if we've already emitted this. This is necessary 1297f22ef01cSRoman Divacky // for a couple of reasons: first, decls can end up in the 1298f22ef01cSRoman Divacky // deferred-decls queue multiple times, and second, decls can end 1299f22ef01cSRoman Divacky // up with definitions in unusual ways (e.g. by an extern inline 1300f22ef01cSRoman Divacky // function acquiring a strong function redefinition). Just 1301f22ef01cSRoman Divacky // ignore these cases. 1302e7145dcbSDimitry Andric if (!GV->isDeclaration()) 1303f22ef01cSRoman Divacky continue; 1304f22ef01cSRoman Divacky 1305f22ef01cSRoman Divacky // Otherwise, emit the definition and move on to the next one. 130659d1ed5bSDimitry Andric EmitGlobalDefinition(D, GV); 130733956c43SDimitry Andric 130833956c43SDimitry Andric // If we found out that we need to emit more decls, do that recursively. 130933956c43SDimitry Andric // This has the advantage that the decls are emitted in a DFS and related 131033956c43SDimitry Andric // ones are close together, which is convenient for testing. 131133956c43SDimitry Andric if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 131233956c43SDimitry Andric EmitDeferred(); 131333956c43SDimitry Andric assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 131433956c43SDimitry Andric } 1315f22ef01cSRoman Divacky } 1316f22ef01cSRoman Divacky } 1317f22ef01cSRoman Divacky 13186122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() { 13196122f3e6SDimitry Andric if (Annotations.empty()) 13206122f3e6SDimitry Andric return; 13216122f3e6SDimitry Andric 13226122f3e6SDimitry Andric // Create a new global variable for the ConstantStruct in the Module. 13236122f3e6SDimitry Andric llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 13246122f3e6SDimitry Andric Annotations[0]->getType(), Annotations.size()), Annotations); 132559d1ed5bSDimitry Andric auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 132659d1ed5bSDimitry Andric llvm::GlobalValue::AppendingLinkage, 132759d1ed5bSDimitry Andric Array, "llvm.global.annotations"); 13286122f3e6SDimitry Andric gv->setSection(AnnotationSection); 13296122f3e6SDimitry Andric } 13306122f3e6SDimitry Andric 1331139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1332f785676fSDimitry Andric llvm::Constant *&AStr = AnnotationStrings[Str]; 1333f785676fSDimitry Andric if (AStr) 1334f785676fSDimitry Andric return AStr; 13356122f3e6SDimitry Andric 13366122f3e6SDimitry Andric // Not found yet, create a new global. 1337dff0c46cSDimitry Andric llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 133859d1ed5bSDimitry Andric auto *gv = 133959d1ed5bSDimitry Andric new llvm::GlobalVariable(getModule(), s->getType(), true, 134059d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, s, ".str"); 13416122f3e6SDimitry Andric gv->setSection(AnnotationSection); 1342e7145dcbSDimitry Andric gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1343f785676fSDimitry Andric AStr = gv; 13446122f3e6SDimitry Andric return gv; 13456122f3e6SDimitry Andric } 13466122f3e6SDimitry Andric 13476122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 13486122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 13496122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(Loc); 13506122f3e6SDimitry Andric if (PLoc.isValid()) 13516122f3e6SDimitry Andric return EmitAnnotationString(PLoc.getFilename()); 13526122f3e6SDimitry Andric return EmitAnnotationString(SM.getBufferName(Loc)); 13536122f3e6SDimitry Andric } 13546122f3e6SDimitry Andric 13556122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 13566122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 13576122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(L); 13586122f3e6SDimitry Andric unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 13596122f3e6SDimitry Andric SM.getExpansionLineNumber(L); 13606122f3e6SDimitry Andric return llvm::ConstantInt::get(Int32Ty, LineNo); 13616122f3e6SDimitry Andric } 13626122f3e6SDimitry Andric 1363f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1364f22ef01cSRoman Divacky const AnnotateAttr *AA, 13656122f3e6SDimitry Andric SourceLocation L) { 13666122f3e6SDimitry Andric // Get the globals for file name, annotation, and the line number. 13676122f3e6SDimitry Andric llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 13686122f3e6SDimitry Andric *UnitGV = EmitAnnotationUnit(L), 13696122f3e6SDimitry Andric *LineNoCst = EmitAnnotationLineNo(L); 1370f22ef01cSRoman Divacky 1371f22ef01cSRoman Divacky // Create the ConstantStruct for the global annotation. 1372f22ef01cSRoman Divacky llvm::Constant *Fields[4] = { 13736122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 13746122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 13756122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 13766122f3e6SDimitry Andric LineNoCst 1377f22ef01cSRoman Divacky }; 137817a519f9SDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 1379f22ef01cSRoman Divacky } 1380f22ef01cSRoman Divacky 13816122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 13826122f3e6SDimitry Andric llvm::GlobalValue *GV) { 13836122f3e6SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 13846122f3e6SDimitry Andric // Get the struct elements for these annotations. 138559d1ed5bSDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 138659d1ed5bSDimitry Andric Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 13876122f3e6SDimitry Andric } 13886122f3e6SDimitry Andric 138939d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn, 139039d628a0SDimitry Andric SourceLocation Loc) const { 139139d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 139239d628a0SDimitry Andric // Blacklist by function name. 139339d628a0SDimitry Andric if (SanitizerBL.isBlacklistedFunction(Fn->getName())) 139439d628a0SDimitry Andric return true; 139539d628a0SDimitry Andric // Blacklist by location. 13960623d748SDimitry Andric if (Loc.isValid()) 139739d628a0SDimitry Andric return SanitizerBL.isBlacklistedLocation(Loc); 139839d628a0SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 139939d628a0SDimitry Andric // it's located in the main file. 140039d628a0SDimitry Andric auto &SM = Context.getSourceManager(); 140139d628a0SDimitry Andric if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 140239d628a0SDimitry Andric return SanitizerBL.isBlacklistedFile(MainFile->getName()); 140339d628a0SDimitry Andric } 140439d628a0SDimitry Andric return false; 140539d628a0SDimitry Andric } 140639d628a0SDimitry Andric 140739d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 140839d628a0SDimitry Andric SourceLocation Loc, QualType Ty, 140939d628a0SDimitry Andric StringRef Category) const { 14108f0fd8f6SDimitry Andric // For now globals can be blacklisted only in ASan and KASan. 14118f0fd8f6SDimitry Andric if (!LangOpts.Sanitize.hasOneOf( 14128f0fd8f6SDimitry Andric SanitizerKind::Address | SanitizerKind::KernelAddress)) 141339d628a0SDimitry Andric return false; 141439d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 141539d628a0SDimitry Andric if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category)) 141639d628a0SDimitry Andric return true; 141739d628a0SDimitry Andric if (SanitizerBL.isBlacklistedLocation(Loc, Category)) 141839d628a0SDimitry Andric return true; 141939d628a0SDimitry Andric // Check global type. 142039d628a0SDimitry Andric if (!Ty.isNull()) { 142139d628a0SDimitry Andric // Drill down the array types: if global variable of a fixed type is 142239d628a0SDimitry Andric // blacklisted, we also don't instrument arrays of them. 142339d628a0SDimitry Andric while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 142439d628a0SDimitry Andric Ty = AT->getElementType(); 142539d628a0SDimitry Andric Ty = Ty.getCanonicalType().getUnqualifiedType(); 142639d628a0SDimitry Andric // We allow to blacklist only record types (classes, structs etc.) 142739d628a0SDimitry Andric if (Ty->isRecordType()) { 142839d628a0SDimitry Andric std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 142939d628a0SDimitry Andric if (SanitizerBL.isBlacklistedType(TypeStr, Category)) 143039d628a0SDimitry Andric return true; 143139d628a0SDimitry Andric } 143239d628a0SDimitry Andric } 143339d628a0SDimitry Andric return false; 143439d628a0SDimitry Andric } 143539d628a0SDimitry Andric 143639d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 1437e580952dSDimitry Andric // Never defer when EmitAllDecls is specified. 1438dff0c46cSDimitry Andric if (LangOpts.EmitAllDecls) 143939d628a0SDimitry Andric return true; 144039d628a0SDimitry Andric 144139d628a0SDimitry Andric return getContext().DeclMustBeEmitted(Global); 144239d628a0SDimitry Andric } 144339d628a0SDimitry Andric 144439d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 144539d628a0SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) 144639d628a0SDimitry Andric if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 144739d628a0SDimitry Andric // Implicit template instantiations may change linkage if they are later 144839d628a0SDimitry Andric // explicitly instantiated, so they should not be emitted eagerly. 1449f22ef01cSRoman Divacky return false; 1450e7145dcbSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(Global)) 1451e7145dcbSDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 1452e7145dcbSDimitry Andric ASTContext::InlineVariableDefinitionKind::WeakUnknown) 1453e7145dcbSDimitry Andric // A definition of an inline constexpr static data member may change 1454e7145dcbSDimitry Andric // linkage later if it's redeclared outside the class. 1455e7145dcbSDimitry Andric return false; 1456875ed548SDimitry Andric // If OpenMP is enabled and threadprivates must be generated like TLS, delay 1457875ed548SDimitry Andric // codegen for global variables, because they may be marked as threadprivate. 1458875ed548SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 1459875ed548SDimitry Andric getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global)) 1460875ed548SDimitry Andric return false; 1461f22ef01cSRoman Divacky 146239d628a0SDimitry Andric return true; 1463f22ef01cSRoman Divacky } 1464f22ef01cSRoman Divacky 14650623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor( 14663861d79fSDimitry Andric const CXXUuidofExpr* E) { 14673861d79fSDimitry Andric // Sema has verified that IIDSource has a __declspec(uuid()), and that its 14683861d79fSDimitry Andric // well-formed. 1469e7145dcbSDimitry Andric StringRef Uuid = E->getUuidStr(); 1470f785676fSDimitry Andric std::string Name = "_GUID_" + Uuid.lower(); 1471f785676fSDimitry Andric std::replace(Name.begin(), Name.end(), '-', '_'); 14723861d79fSDimitry Andric 1473e7145dcbSDimitry Andric // The UUID descriptor should be pointer aligned. 1474e7145dcbSDimitry Andric CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 14750623d748SDimitry Andric 14763861d79fSDimitry Andric // Look for an existing global. 14773861d79fSDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 14780623d748SDimitry Andric return ConstantAddress(GV, Alignment); 14793861d79fSDimitry Andric 148039d628a0SDimitry Andric llvm::Constant *Init = EmitUuidofInitializer(Uuid); 14813861d79fSDimitry Andric assert(Init && "failed to initialize as constant"); 14823861d79fSDimitry Andric 148359d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 1484f785676fSDimitry Andric getModule(), Init->getType(), 1485f785676fSDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 148633956c43SDimitry Andric if (supportsCOMDAT()) 148733956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 14880623d748SDimitry Andric return ConstantAddress(GV, Alignment); 14893861d79fSDimitry Andric } 14903861d79fSDimitry Andric 14910623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1492f22ef01cSRoman Divacky const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1493f22ef01cSRoman Divacky assert(AA && "No alias?"); 1494f22ef01cSRoman Divacky 14950623d748SDimitry Andric CharUnits Alignment = getContext().getDeclAlign(VD); 14966122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1497f22ef01cSRoman Divacky 1498f22ef01cSRoman Divacky // See if there is already something with the target's name in the module. 1499f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 15003861d79fSDimitry Andric if (Entry) { 15013861d79fSDimitry Andric unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 15020623d748SDimitry Andric auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 15030623d748SDimitry Andric return ConstantAddress(Ptr, Alignment); 15043861d79fSDimitry Andric } 1505f22ef01cSRoman Divacky 1506f22ef01cSRoman Divacky llvm::Constant *Aliasee; 1507f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 15083861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 15093861d79fSDimitry Andric GlobalDecl(cast<FunctionDecl>(VD)), 15102754fe60SDimitry Andric /*ForVTable=*/false); 1511f22ef01cSRoman Divacky else 1512f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 151359d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 151459d1ed5bSDimitry Andric nullptr); 15153861d79fSDimitry Andric 151659d1ed5bSDimitry Andric auto *F = cast<llvm::GlobalValue>(Aliasee); 1517f22ef01cSRoman Divacky F->setLinkage(llvm::Function::ExternalWeakLinkage); 1518f22ef01cSRoman Divacky WeakRefReferences.insert(F); 1519f22ef01cSRoman Divacky 15200623d748SDimitry Andric return ConstantAddress(Aliasee, Alignment); 1521f22ef01cSRoman Divacky } 1522f22ef01cSRoman Divacky 1523f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) { 152459d1ed5bSDimitry Andric const auto *Global = cast<ValueDecl>(GD.getDecl()); 1525f22ef01cSRoman Divacky 1526f22ef01cSRoman Divacky // Weak references don't produce any output by themselves. 1527f22ef01cSRoman Divacky if (Global->hasAttr<WeakRefAttr>()) 1528f22ef01cSRoman Divacky return; 1529f22ef01cSRoman Divacky 1530f22ef01cSRoman Divacky // If this is an alias definition (which otherwise looks like a declaration) 1531f22ef01cSRoman Divacky // emit it now. 1532f22ef01cSRoman Divacky if (Global->hasAttr<AliasAttr>()) 1533f22ef01cSRoman Divacky return EmitAliasDefinition(GD); 1534f22ef01cSRoman Divacky 1535e7145dcbSDimitry Andric // IFunc like an alias whose value is resolved at runtime by calling resolver. 1536e7145dcbSDimitry Andric if (Global->hasAttr<IFuncAttr>()) 1537e7145dcbSDimitry Andric return emitIFuncDefinition(GD); 1538e7145dcbSDimitry Andric 15396122f3e6SDimitry Andric // If this is CUDA, be selective about which declarations we emit. 1540dff0c46cSDimitry Andric if (LangOpts.CUDA) { 154133956c43SDimitry Andric if (LangOpts.CUDAIsDevice) { 15426122f3e6SDimitry Andric if (!Global->hasAttr<CUDADeviceAttr>() && 15436122f3e6SDimitry Andric !Global->hasAttr<CUDAGlobalAttr>() && 15446122f3e6SDimitry Andric !Global->hasAttr<CUDAConstantAttr>() && 15456122f3e6SDimitry Andric !Global->hasAttr<CUDASharedAttr>()) 15466122f3e6SDimitry Andric return; 15476122f3e6SDimitry Andric } else { 1548e7145dcbSDimitry Andric // We need to emit host-side 'shadows' for all global 1549e7145dcbSDimitry Andric // device-side variables because the CUDA runtime needs their 1550e7145dcbSDimitry Andric // size and host-side address in order to provide access to 1551e7145dcbSDimitry Andric // their device-side incarnations. 1552e7145dcbSDimitry Andric 1553e7145dcbSDimitry Andric // So device-only functions are the only things we skip. 1554e7145dcbSDimitry Andric if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 1555e7145dcbSDimitry Andric Global->hasAttr<CUDADeviceAttr>()) 15566122f3e6SDimitry Andric return; 1557e7145dcbSDimitry Andric 1558e7145dcbSDimitry Andric assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 1559e7145dcbSDimitry Andric "Expected Variable or Function"); 1560e580952dSDimitry Andric } 1561e580952dSDimitry Andric } 1562e580952dSDimitry Andric 1563e7145dcbSDimitry Andric if (LangOpts.OpenMP) { 1564ea942507SDimitry Andric // If this is OpenMP device, check if it is legal to emit this global 1565ea942507SDimitry Andric // normally. 1566ea942507SDimitry Andric if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 1567ea942507SDimitry Andric return; 1568e7145dcbSDimitry Andric if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 1569e7145dcbSDimitry Andric if (MustBeEmitted(Global)) 1570e7145dcbSDimitry Andric EmitOMPDeclareReduction(DRD); 1571e7145dcbSDimitry Andric return; 1572e7145dcbSDimitry Andric } 1573e7145dcbSDimitry Andric } 1574ea942507SDimitry Andric 15756122f3e6SDimitry Andric // Ignore declarations, they will be emitted on their first use. 157659d1ed5bSDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 1577f22ef01cSRoman Divacky // Forward declarations are emitted lazily on first use. 15786122f3e6SDimitry Andric if (!FD->doesThisDeclarationHaveABody()) { 15796122f3e6SDimitry Andric if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1580f22ef01cSRoman Divacky return; 15816122f3e6SDimitry Andric 15826122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 158359d1ed5bSDimitry Andric 158459d1ed5bSDimitry Andric // Compute the function info and LLVM type. 158559d1ed5bSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 158659d1ed5bSDimitry Andric llvm::Type *Ty = getTypes().GetFunctionType(FI); 158759d1ed5bSDimitry Andric 158859d1ed5bSDimitry Andric GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 158959d1ed5bSDimitry Andric /*DontDefer=*/false); 15906122f3e6SDimitry Andric return; 15916122f3e6SDimitry Andric } 1592f22ef01cSRoman Divacky } else { 159359d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(Global); 1594f22ef01cSRoman Divacky assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1595e7145dcbSDimitry Andric // We need to emit device-side global CUDA variables even if a 1596e7145dcbSDimitry Andric // variable does not have a definition -- we still need to define 1597e7145dcbSDimitry Andric // host-side shadow for it. 1598e7145dcbSDimitry Andric bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice && 1599e7145dcbSDimitry Andric !VD->hasDefinition() && 1600e7145dcbSDimitry Andric (VD->hasAttr<CUDAConstantAttr>() || 1601e7145dcbSDimitry Andric VD->hasAttr<CUDADeviceAttr>()); 1602e7145dcbSDimitry Andric if (!MustEmitForCuda && 1603e7145dcbSDimitry Andric VD->isThisDeclarationADefinition() != VarDecl::Definition && 1604e7145dcbSDimitry Andric !Context.isMSStaticDataMemberInlineDefinition(VD)) { 1605e7145dcbSDimitry Andric // If this declaration may have caused an inline variable definition to 1606e7145dcbSDimitry Andric // change linkage, make sure that it's emitted. 1607e7145dcbSDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 1608e7145dcbSDimitry Andric ASTContext::InlineVariableDefinitionKind::Strong) 1609e7145dcbSDimitry Andric GetAddrOfGlobalVar(VD); 1610f22ef01cSRoman Divacky return; 1611f22ef01cSRoman Divacky } 1612e7145dcbSDimitry Andric } 1613f22ef01cSRoman Divacky 161439d628a0SDimitry Andric // Defer code generation to first use when possible, e.g. if this is an inline 161539d628a0SDimitry Andric // function. If the global must always be emitted, do it eagerly if possible 161639d628a0SDimitry Andric // to benefit from cache locality. 161739d628a0SDimitry Andric if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 1618f22ef01cSRoman Divacky // Emit the definition if it can't be deferred. 1619f22ef01cSRoman Divacky EmitGlobalDefinition(GD); 1620f22ef01cSRoman Divacky return; 1621f22ef01cSRoman Divacky } 1622f22ef01cSRoman Divacky 1623e580952dSDimitry Andric // If we're deferring emission of a C++ variable with an 1624e580952dSDimitry Andric // initializer, remember the order in which it appeared in the file. 1625dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1626e580952dSDimitry Andric cast<VarDecl>(Global)->hasInit()) { 1627e580952dSDimitry Andric DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 162859d1ed5bSDimitry Andric CXXGlobalInits.push_back(nullptr); 1629e580952dSDimitry Andric } 1630e580952dSDimitry Andric 16316122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 163239d628a0SDimitry Andric if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) { 163339d628a0SDimitry Andric // The value has already been used and should therefore be emitted. 163459d1ed5bSDimitry Andric addDeferredDeclToEmit(GV, GD); 163539d628a0SDimitry Andric } else if (MustBeEmitted(Global)) { 163639d628a0SDimitry Andric // The value must be emitted, but cannot be emitted eagerly. 163739d628a0SDimitry Andric assert(!MayBeEmittedEagerly(Global)); 163839d628a0SDimitry Andric addDeferredDeclToEmit(/*GV=*/nullptr, GD); 163939d628a0SDimitry Andric } else { 1640f22ef01cSRoman Divacky // Otherwise, remember that we saw a deferred decl with this name. The 1641f22ef01cSRoman Divacky // first use of the mangled name will cause it to move into 1642f22ef01cSRoman Divacky // DeferredDeclsToEmit. 1643f22ef01cSRoman Divacky DeferredDecls[MangledName] = GD; 1644f22ef01cSRoman Divacky } 1645f22ef01cSRoman Divacky } 1646f22ef01cSRoman Divacky 1647f8254f43SDimitry Andric namespace { 1648f8254f43SDimitry Andric struct FunctionIsDirectlyRecursive : 1649f8254f43SDimitry Andric public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1650f8254f43SDimitry Andric const StringRef Name; 1651dff0c46cSDimitry Andric const Builtin::Context &BI; 1652f8254f43SDimitry Andric bool Result; 1653dff0c46cSDimitry Andric FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1654dff0c46cSDimitry Andric Name(N), BI(C), Result(false) { 1655f8254f43SDimitry Andric } 1656f8254f43SDimitry Andric typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1657f8254f43SDimitry Andric 1658f8254f43SDimitry Andric bool TraverseCallExpr(CallExpr *E) { 1659dff0c46cSDimitry Andric const FunctionDecl *FD = E->getDirectCallee(); 1660dff0c46cSDimitry Andric if (!FD) 1661f8254f43SDimitry Andric return true; 1662dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1663dff0c46cSDimitry Andric if (Attr && Name == Attr->getLabel()) { 1664dff0c46cSDimitry Andric Result = true; 1665dff0c46cSDimitry Andric return false; 1666dff0c46cSDimitry Andric } 1667dff0c46cSDimitry Andric unsigned BuiltinID = FD->getBuiltinID(); 16683dac3a9bSDimitry Andric if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 1669f8254f43SDimitry Andric return true; 16700623d748SDimitry Andric StringRef BuiltinName = BI.getName(BuiltinID); 1671dff0c46cSDimitry Andric if (BuiltinName.startswith("__builtin_") && 1672dff0c46cSDimitry Andric Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1673f8254f43SDimitry Andric Result = true; 1674f8254f43SDimitry Andric return false; 1675f8254f43SDimitry Andric } 1676f8254f43SDimitry Andric return true; 1677f8254f43SDimitry Andric } 1678f8254f43SDimitry Andric }; 16790623d748SDimitry Andric 16800623d748SDimitry Andric struct DLLImportFunctionVisitor 16810623d748SDimitry Andric : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 16820623d748SDimitry Andric bool SafeToInline = true; 16830623d748SDimitry Andric 16840623d748SDimitry Andric bool VisitVarDecl(VarDecl *VD) { 16850623d748SDimitry Andric // A thread-local variable cannot be imported. 16860623d748SDimitry Andric SafeToInline = !VD->getTLSKind(); 16870623d748SDimitry Andric return SafeToInline; 16880623d748SDimitry Andric } 16890623d748SDimitry Andric 16900623d748SDimitry Andric // Make sure we're not referencing non-imported vars or functions. 16910623d748SDimitry Andric bool VisitDeclRefExpr(DeclRefExpr *E) { 16920623d748SDimitry Andric ValueDecl *VD = E->getDecl(); 16930623d748SDimitry Andric if (isa<FunctionDecl>(VD)) 16940623d748SDimitry Andric SafeToInline = VD->hasAttr<DLLImportAttr>(); 16950623d748SDimitry Andric else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 16960623d748SDimitry Andric SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 16970623d748SDimitry Andric return SafeToInline; 16980623d748SDimitry Andric } 16990623d748SDimitry Andric bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 17000623d748SDimitry Andric SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 17010623d748SDimitry Andric return SafeToInline; 17020623d748SDimitry Andric } 17030623d748SDimitry Andric bool VisitCXXNewExpr(CXXNewExpr *E) { 17040623d748SDimitry Andric SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 17050623d748SDimitry Andric return SafeToInline; 17060623d748SDimitry Andric } 17070623d748SDimitry Andric }; 1708f8254f43SDimitry Andric } 1709f8254f43SDimitry Andric 1710dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another 1711dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin, 1712dff0c46cSDimitry Andric // ends up pointing to itself. 1713f8254f43SDimitry Andric bool 1714dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1715dff0c46cSDimitry Andric StringRef Name; 1716dff0c46cSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1717dff0c46cSDimitry Andric // asm labels are a special kind of mangling we have to support. 1718dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1719dff0c46cSDimitry Andric if (!Attr) 1720f8254f43SDimitry Andric return false; 1721dff0c46cSDimitry Andric Name = Attr->getLabel(); 1722dff0c46cSDimitry Andric } else { 1723dff0c46cSDimitry Andric Name = FD->getName(); 1724dff0c46cSDimitry Andric } 1725f8254f43SDimitry Andric 1726dff0c46cSDimitry Andric FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1727dff0c46cSDimitry Andric Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1728f8254f43SDimitry Andric return Walker.Result; 1729f8254f43SDimitry Andric } 1730f8254f43SDimitry Andric 1731f8254f43SDimitry Andric bool 1732f785676fSDimitry Andric CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1733f785676fSDimitry Andric if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1734f8254f43SDimitry Andric return true; 173559d1ed5bSDimitry Andric const auto *F = cast<FunctionDecl>(GD.getDecl()); 173659d1ed5bSDimitry Andric if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1737f8254f43SDimitry Andric return false; 17380623d748SDimitry Andric 17390623d748SDimitry Andric if (F->hasAttr<DLLImportAttr>()) { 17400623d748SDimitry Andric // Check whether it would be safe to inline this dllimport function. 17410623d748SDimitry Andric DLLImportFunctionVisitor Visitor; 17420623d748SDimitry Andric Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 17430623d748SDimitry Andric if (!Visitor.SafeToInline) 17440623d748SDimitry Andric return false; 17450623d748SDimitry Andric } 17460623d748SDimitry Andric 1747f8254f43SDimitry Andric // PR9614. Avoid cases where the source code is lying to us. An available 1748f8254f43SDimitry Andric // externally function should have an equivalent function somewhere else, 1749f8254f43SDimitry Andric // but a function that calls itself is clearly not equivalent to the real 1750f8254f43SDimitry Andric // implementation. 1751f8254f43SDimitry Andric // This happens in glibc's btowc and in some configure checks. 1752dff0c46cSDimitry Andric return !isTriviallyRecursive(F); 1753f8254f43SDimitry Andric } 1754f8254f43SDimitry Andric 1755f785676fSDimitry Andric /// If the type for the method's class was generated by 1756f785676fSDimitry Andric /// CGDebugInfo::createContextChain(), the cache contains only a 1757f785676fSDimitry Andric /// limited DIType without any declarations. Since EmitFunctionStart() 1758f785676fSDimitry Andric /// needs to find the canonical declaration for each method, we need 1759f785676fSDimitry Andric /// to construct the complete type prior to emitting the method. 1760f785676fSDimitry Andric void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) { 1761f785676fSDimitry Andric if (!D->isInstance()) 1762f785676fSDimitry Andric return; 1763f785676fSDimitry Andric 1764f785676fSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 1765e7145dcbSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) { 176659d1ed5bSDimitry Andric const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext())); 1767f785676fSDimitry Andric DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation()); 1768f785676fSDimitry Andric } 1769f785676fSDimitry Andric } 1770f785676fSDimitry Andric 177159d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 177259d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 1773f22ef01cSRoman Divacky 1774f22ef01cSRoman Divacky PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1775f22ef01cSRoman Divacky Context.getSourceManager(), 1776f22ef01cSRoman Divacky "Generating code for declaration"); 1777f22ef01cSRoman Divacky 1778f785676fSDimitry Andric if (isa<FunctionDecl>(D)) { 1779ffd1746dSEd Schouten // At -O0, don't generate IR for functions with available_externally 1780ffd1746dSEd Schouten // linkage. 1781f785676fSDimitry Andric if (!shouldEmitFunction(GD)) 1782ffd1746dSEd Schouten return; 1783ffd1746dSEd Schouten 178459d1ed5bSDimitry Andric if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 1785f785676fSDimitry Andric CompleteDIClassType(Method); 1786bd5abe19SDimitry Andric // Make sure to emit the definition(s) before we emit the thunks. 1787bd5abe19SDimitry Andric // This is necessary for the generation of certain thunks. 178859d1ed5bSDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 178939d628a0SDimitry Andric ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); 179059d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 179139d628a0SDimitry Andric ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); 1792bd5abe19SDimitry Andric else 179359d1ed5bSDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 1794bd5abe19SDimitry Andric 1795f22ef01cSRoman Divacky if (Method->isVirtual()) 1796f22ef01cSRoman Divacky getVTables().EmitThunks(GD); 1797f22ef01cSRoman Divacky 1798bd5abe19SDimitry Andric return; 1799ffd1746dSEd Schouten } 1800f22ef01cSRoman Divacky 180159d1ed5bSDimitry Andric return EmitGlobalFunctionDefinition(GD, GV); 1802ffd1746dSEd Schouten } 1803f22ef01cSRoman Divacky 180459d1ed5bSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 1805e7145dcbSDimitry Andric return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 1806f22ef01cSRoman Divacky 18076122f3e6SDimitry Andric llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1808f22ef01cSRoman Divacky } 1809f22ef01cSRoman Divacky 18100623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 18110623d748SDimitry Andric llvm::Function *NewFn); 18120623d748SDimitry Andric 1813f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1814f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there 1815f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 1816f22ef01cSRoman Divacky /// bitcasted to the right type. 1817f22ef01cSRoman Divacky /// 1818f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 1819f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created. 1820f22ef01cSRoman Divacky llvm::Constant * 18216122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 18226122f3e6SDimitry Andric llvm::Type *Ty, 1823f785676fSDimitry Andric GlobalDecl GD, bool ForVTable, 182439d628a0SDimitry Andric bool DontDefer, bool IsThunk, 18250623d748SDimitry Andric llvm::AttributeSet ExtraAttrs, 18260623d748SDimitry Andric bool IsForDefinition) { 1827f785676fSDimitry Andric const Decl *D = GD.getDecl(); 1828f785676fSDimitry Andric 1829f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 1830f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1831f22ef01cSRoman Divacky if (Entry) { 18323861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 1833f785676fSDimitry Andric const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 1834f22ef01cSRoman Divacky if (FD && !FD->hasAttr<WeakAttr>()) 1835f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 1836f22ef01cSRoman Divacky } 1837f22ef01cSRoman Divacky 183839d628a0SDimitry Andric // Handle dropped DLL attributes. 183939d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 184039d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 184139d628a0SDimitry Andric 18420623d748SDimitry Andric // If there are two attempts to define the same mangled name, issue an 18430623d748SDimitry Andric // error. 18440623d748SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 18450623d748SDimitry Andric GlobalDecl OtherGD; 1846e7145dcbSDimitry Andric // Check that GD is not yet in DiagnosedConflictingDefinitions is required 1847e7145dcbSDimitry Andric // to make sure that we issue an error only once. 18480623d748SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 18490623d748SDimitry Andric (GD.getCanonicalDecl().getDecl() != 18500623d748SDimitry Andric OtherGD.getCanonicalDecl().getDecl()) && 18510623d748SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 18520623d748SDimitry Andric getDiags().Report(D->getLocation(), 18530623d748SDimitry Andric diag::err_duplicate_mangled_name); 18540623d748SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 18550623d748SDimitry Andric diag::note_previous_definition); 18560623d748SDimitry Andric } 18570623d748SDimitry Andric } 18580623d748SDimitry Andric 18590623d748SDimitry Andric if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 18600623d748SDimitry Andric (Entry->getType()->getElementType() == Ty)) { 1861f22ef01cSRoman Divacky return Entry; 18620623d748SDimitry Andric } 1863f22ef01cSRoman Divacky 1864f22ef01cSRoman Divacky // Make sure the result is of the correct type. 18650623d748SDimitry Andric // (If function is requested for a definition, we always need to create a new 18660623d748SDimitry Andric // function, not just return a bitcast.) 18670623d748SDimitry Andric if (!IsForDefinition) 186817a519f9SDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1869f22ef01cSRoman Divacky } 1870f22ef01cSRoman Divacky 1871f22ef01cSRoman Divacky // This function doesn't have a complete type (for example, the return 1872f22ef01cSRoman Divacky // type is an incomplete struct). Use a fake type instead, and make 1873f22ef01cSRoman Divacky // sure not to try to set attributes. 1874f22ef01cSRoman Divacky bool IsIncompleteFunction = false; 1875f22ef01cSRoman Divacky 18766122f3e6SDimitry Andric llvm::FunctionType *FTy; 1877f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(Ty)) { 1878f22ef01cSRoman Divacky FTy = cast<llvm::FunctionType>(Ty); 1879f22ef01cSRoman Divacky } else { 1880bd5abe19SDimitry Andric FTy = llvm::FunctionType::get(VoidTy, false); 1881f22ef01cSRoman Divacky IsIncompleteFunction = true; 1882f22ef01cSRoman Divacky } 1883ffd1746dSEd Schouten 18840623d748SDimitry Andric llvm::Function *F = 18850623d748SDimitry Andric llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 18860623d748SDimitry Andric Entry ? StringRef() : MangledName, &getModule()); 18870623d748SDimitry Andric 18880623d748SDimitry Andric // If we already created a function with the same mangled name (but different 18890623d748SDimitry Andric // type) before, take its name and add it to the list of functions to be 18900623d748SDimitry Andric // replaced with F at the end of CodeGen. 18910623d748SDimitry Andric // 18920623d748SDimitry Andric // This happens if there is a prototype for a function (e.g. "int f()") and 18930623d748SDimitry Andric // then a definition of a different type (e.g. "int f(int x)"). 18940623d748SDimitry Andric if (Entry) { 18950623d748SDimitry Andric F->takeName(Entry); 18960623d748SDimitry Andric 18970623d748SDimitry Andric // This might be an implementation of a function without a prototype, in 18980623d748SDimitry Andric // which case, try to do special replacement of calls which match the new 18990623d748SDimitry Andric // prototype. The really key thing here is that we also potentially drop 19000623d748SDimitry Andric // arguments from the call site so as to make a direct call, which makes the 19010623d748SDimitry Andric // inliner happier and suppresses a number of optimizer warnings (!) about 19020623d748SDimitry Andric // dropping arguments. 19030623d748SDimitry Andric if (!Entry->use_empty()) { 19040623d748SDimitry Andric ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 19050623d748SDimitry Andric Entry->removeDeadConstantUsers(); 19060623d748SDimitry Andric } 19070623d748SDimitry Andric 19080623d748SDimitry Andric llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 19090623d748SDimitry Andric F, Entry->getType()->getElementType()->getPointerTo()); 19100623d748SDimitry Andric addGlobalValReplacement(Entry, BC); 19110623d748SDimitry Andric } 19120623d748SDimitry Andric 1913f22ef01cSRoman Divacky assert(F->getName() == MangledName && "name was uniqued!"); 1914f785676fSDimitry Andric if (D) 191539d628a0SDimitry Andric SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 1916139f7f9bSDimitry Andric if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) { 1917139f7f9bSDimitry Andric llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex); 1918139f7f9bSDimitry Andric F->addAttributes(llvm::AttributeSet::FunctionIndex, 1919139f7f9bSDimitry Andric llvm::AttributeSet::get(VMContext, 1920139f7f9bSDimitry Andric llvm::AttributeSet::FunctionIndex, 1921139f7f9bSDimitry Andric B)); 1922139f7f9bSDimitry Andric } 1923f22ef01cSRoman Divacky 192459d1ed5bSDimitry Andric if (!DontDefer) { 192559d1ed5bSDimitry Andric // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 192659d1ed5bSDimitry Andric // each other bottoming out with the base dtor. Therefore we emit non-base 192759d1ed5bSDimitry Andric // dtors on usage, even if there is no dtor definition in the TU. 192859d1ed5bSDimitry Andric if (D && isa<CXXDestructorDecl>(D) && 192959d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 193059d1ed5bSDimitry Andric GD.getDtorType())) 193159d1ed5bSDimitry Andric addDeferredDeclToEmit(F, GD); 193259d1ed5bSDimitry Andric 1933f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 1934f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 1935f22ef01cSRoman Divacky // of the file. 193659d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 1937f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 193859d1ed5bSDimitry Andric // Move the potentially referenced deferred decl to the 193959d1ed5bSDimitry Andric // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 194059d1ed5bSDimitry Andric // don't need it anymore). 194159d1ed5bSDimitry Andric addDeferredDeclToEmit(F, DDI->second); 1942f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 19432754fe60SDimitry Andric 19442754fe60SDimitry Andric // Otherwise, there are cases we have to worry about where we're 19452754fe60SDimitry Andric // using a declaration for which we must emit a definition but where 19462754fe60SDimitry Andric // we might not find a top-level definition: 19472754fe60SDimitry Andric // - member functions defined inline in their classes 19482754fe60SDimitry Andric // - friend functions defined inline in some class 19492754fe60SDimitry Andric // - special member functions with implicit definitions 19502754fe60SDimitry Andric // If we ever change our AST traversal to walk into class methods, 19512754fe60SDimitry Andric // this will be unnecessary. 19522754fe60SDimitry Andric // 195359d1ed5bSDimitry Andric // We also don't emit a definition for a function if it's going to be an 195439d628a0SDimitry Andric // entry in a vtable, unless it's already marked as used. 1955f785676fSDimitry Andric } else if (getLangOpts().CPlusPlus && D) { 19562754fe60SDimitry Andric // Look for a declaration that's lexically in a record. 195739d628a0SDimitry Andric for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 195839d628a0SDimitry Andric FD = FD->getPreviousDecl()) { 19592754fe60SDimitry Andric if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 196039d628a0SDimitry Andric if (FD->doesThisDeclarationHaveABody()) { 196159d1ed5bSDimitry Andric addDeferredDeclToEmit(F, GD.getWithDecl(FD)); 19622754fe60SDimitry Andric break; 1963f22ef01cSRoman Divacky } 1964f22ef01cSRoman Divacky } 196539d628a0SDimitry Andric } 1966f22ef01cSRoman Divacky } 196759d1ed5bSDimitry Andric } 1968f22ef01cSRoman Divacky 1969f22ef01cSRoman Divacky // Make sure the result is of the requested type. 1970f22ef01cSRoman Divacky if (!IsIncompleteFunction) { 1971f22ef01cSRoman Divacky assert(F->getType()->getElementType() == Ty); 1972f22ef01cSRoman Divacky return F; 1973f22ef01cSRoman Divacky } 1974f22ef01cSRoman Divacky 197517a519f9SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1976f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(F, PTy); 1977f22ef01cSRoman Divacky } 1978f22ef01cSRoman Divacky 1979f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function. If Ty is 1980f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to 1981f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function). 1982f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 19836122f3e6SDimitry Andric llvm::Type *Ty, 198459d1ed5bSDimitry Andric bool ForVTable, 19850623d748SDimitry Andric bool DontDefer, 19860623d748SDimitry Andric bool IsForDefinition) { 1987f22ef01cSRoman Divacky // If there was no specific requested type, just convert it now. 19880623d748SDimitry Andric if (!Ty) { 19890623d748SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 19900623d748SDimitry Andric auto CanonTy = Context.getCanonicalType(FD->getType()); 19910623d748SDimitry Andric Ty = getTypes().ConvertFunctionType(CanonTy, FD); 19920623d748SDimitry Andric } 1993ffd1746dSEd Schouten 19946122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 19950623d748SDimitry Andric return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 19960623d748SDimitry Andric /*IsThunk=*/false, llvm::AttributeSet(), 19970623d748SDimitry Andric IsForDefinition); 1998f22ef01cSRoman Divacky } 1999f22ef01cSRoman Divacky 2000f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified 2001f22ef01cSRoman Divacky /// type and name. 2002f22ef01cSRoman Divacky llvm::Constant * 20036122f3e6SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 20046122f3e6SDimitry Andric StringRef Name, 2005139f7f9bSDimitry Andric llvm::AttributeSet ExtraAttrs) { 200659d1ed5bSDimitry Andric llvm::Constant *C = 200759d1ed5bSDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 200839d628a0SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 200959d1ed5bSDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) 2010139f7f9bSDimitry Andric if (F->empty()) 2011139f7f9bSDimitry Andric F->setCallingConv(getRuntimeCC()); 2012139f7f9bSDimitry Andric return C; 2013f22ef01cSRoman Divacky } 2014f22ef01cSRoman Divacky 201539d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified 201639d628a0SDimitry Andric /// type and name. 201739d628a0SDimitry Andric llvm::Constant * 201839d628a0SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, 201939d628a0SDimitry Andric StringRef Name, 202039d628a0SDimitry Andric llvm::AttributeSet ExtraAttrs) { 202139d628a0SDimitry Andric llvm::Constant *C = 202239d628a0SDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 202339d628a0SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 202439d628a0SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) 202539d628a0SDimitry Andric if (F->empty()) 202639d628a0SDimitry Andric F->setCallingConv(getBuiltinCC()); 202739d628a0SDimitry Andric return C; 202839d628a0SDimitry Andric } 202939d628a0SDimitry Andric 2030dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted 2031dff0c46cSDimitry Andric /// as a constant. 2032dff0c46cSDimitry Andric /// 2033dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs 2034dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is 2035dff0c46cSDimitry Andric /// not written to during its construction. 2036dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 2037dff0c46cSDimitry Andric if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 2038f22ef01cSRoman Divacky return false; 2039bd5abe19SDimitry Andric 2040dff0c46cSDimitry Andric if (Context.getLangOpts().CPlusPlus) { 2041dff0c46cSDimitry Andric if (const CXXRecordDecl *Record 2042dff0c46cSDimitry Andric = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 2043dff0c46cSDimitry Andric return ExcludeCtor && !Record->hasMutableFields() && 2044dff0c46cSDimitry Andric Record->hasTrivialDestructor(); 2045f22ef01cSRoman Divacky } 2046bd5abe19SDimitry Andric 2047f22ef01cSRoman Divacky return true; 2048f22ef01cSRoman Divacky } 2049f22ef01cSRoman Divacky 2050f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 2051f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type. If there 2052f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 2053f22ef01cSRoman Divacky /// bitcasted to the right type. 2054f22ef01cSRoman Divacky /// 2055f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 2056f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created. 2057e7145dcbSDimitry Andric /// 2058e7145dcbSDimitry Andric /// If IsForDefinition is true, it is guranteed that an actual global with 2059e7145dcbSDimitry Andric /// type Ty will be returned, not conversion of a variable with the same 2060e7145dcbSDimitry Andric /// mangled name but some other type. 2061f22ef01cSRoman Divacky llvm::Constant * 20626122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 20636122f3e6SDimitry Andric llvm::PointerType *Ty, 2064e7145dcbSDimitry Andric const VarDecl *D, 2065e7145dcbSDimitry Andric bool IsForDefinition) { 2066f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 2067f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2068f22ef01cSRoman Divacky if (Entry) { 20693861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 2070f22ef01cSRoman Divacky if (D && !D->hasAttr<WeakAttr>()) 2071f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 2072f22ef01cSRoman Divacky } 2073f22ef01cSRoman Divacky 207439d628a0SDimitry Andric // Handle dropped DLL attributes. 207539d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 207639d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 207739d628a0SDimitry Andric 2078f22ef01cSRoman Divacky if (Entry->getType() == Ty) 2079f22ef01cSRoman Divacky return Entry; 2080f22ef01cSRoman Divacky 2081e7145dcbSDimitry Andric // If there are two attempts to define the same mangled name, issue an 2082e7145dcbSDimitry Andric // error. 2083e7145dcbSDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 2084e7145dcbSDimitry Andric GlobalDecl OtherGD; 2085e7145dcbSDimitry Andric const VarDecl *OtherD; 2086e7145dcbSDimitry Andric 2087e7145dcbSDimitry Andric // Check that D is not yet in DiagnosedConflictingDefinitions is required 2088e7145dcbSDimitry Andric // to make sure that we issue an error only once. 2089e7145dcbSDimitry Andric if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 2090e7145dcbSDimitry Andric (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 2091e7145dcbSDimitry Andric (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 2092e7145dcbSDimitry Andric OtherD->hasInit() && 2093e7145dcbSDimitry Andric DiagnosedConflictingDefinitions.insert(D).second) { 2094e7145dcbSDimitry Andric getDiags().Report(D->getLocation(), 2095e7145dcbSDimitry Andric diag::err_duplicate_mangled_name); 2096e7145dcbSDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 2097e7145dcbSDimitry Andric diag::note_previous_definition); 2098e7145dcbSDimitry Andric } 2099e7145dcbSDimitry Andric } 2100e7145dcbSDimitry Andric 2101f22ef01cSRoman Divacky // Make sure the result is of the correct type. 2102f785676fSDimitry Andric if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 2103f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 2104f785676fSDimitry Andric 2105e7145dcbSDimitry Andric // (If global is requested for a definition, we always need to create a new 2106e7145dcbSDimitry Andric // global, not just return a bitcast.) 2107e7145dcbSDimitry Andric if (!IsForDefinition) 2108f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(Entry, Ty); 2109f22ef01cSRoman Divacky } 2110f22ef01cSRoman Divacky 211159d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 211259d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 211359d1ed5bSDimitry Andric getModule(), Ty->getElementType(), false, 211459d1ed5bSDimitry Andric llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 211559d1ed5bSDimitry Andric llvm::GlobalVariable::NotThreadLocal, AddrSpace); 211659d1ed5bSDimitry Andric 2117e7145dcbSDimitry Andric // If we already created a global with the same mangled name (but different 2118e7145dcbSDimitry Andric // type) before, take its name and remove it from its parent. 2119e7145dcbSDimitry Andric if (Entry) { 2120e7145dcbSDimitry Andric GV->takeName(Entry); 2121e7145dcbSDimitry Andric 2122e7145dcbSDimitry Andric if (!Entry->use_empty()) { 2123e7145dcbSDimitry Andric llvm::Constant *NewPtrForOldDecl = 2124e7145dcbSDimitry Andric llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2125e7145dcbSDimitry Andric Entry->replaceAllUsesWith(NewPtrForOldDecl); 2126e7145dcbSDimitry Andric } 2127e7145dcbSDimitry Andric 2128e7145dcbSDimitry Andric Entry->eraseFromParent(); 2129e7145dcbSDimitry Andric } 2130e7145dcbSDimitry Andric 2131f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 2132f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 2133f22ef01cSRoman Divacky // of the file. 213459d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 2135f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 2136f22ef01cSRoman Divacky // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 2137f22ef01cSRoman Divacky // list, and remove it from DeferredDecls (since we don't need it anymore). 213859d1ed5bSDimitry Andric addDeferredDeclToEmit(GV, DDI->second); 2139f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 2140f22ef01cSRoman Divacky } 2141f22ef01cSRoman Divacky 2142f22ef01cSRoman Divacky // Handle things which are present even on external declarations. 2143f22ef01cSRoman Divacky if (D) { 2144f22ef01cSRoman Divacky // FIXME: This code is overly simple and should be merged with other global 2145f22ef01cSRoman Divacky // handling. 2146dff0c46cSDimitry Andric GV->setConstant(isTypeConstant(D->getType(), false)); 2147f22ef01cSRoman Divacky 214833956c43SDimitry Andric GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 214933956c43SDimitry Andric 215059d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(GV, D); 21512754fe60SDimitry Andric 2152284c1978SDimitry Andric if (D->getTLSKind()) { 2153284c1978SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 21540623d748SDimitry Andric CXXThreadLocals.push_back(D); 21557ae0e2c9SDimitry Andric setTLSMode(GV, *D); 2156f22ef01cSRoman Divacky } 2157f785676fSDimitry Andric 2158f785676fSDimitry Andric // If required by the ABI, treat declarations of static data members with 2159f785676fSDimitry Andric // inline initializers as definitions. 216059d1ed5bSDimitry Andric if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 2161f785676fSDimitry Andric EmitGlobalVarDefinition(D); 2162284c1978SDimitry Andric } 2163f22ef01cSRoman Divacky 216459d1ed5bSDimitry Andric // Handle XCore specific ABI requirements. 216559d1ed5bSDimitry Andric if (getTarget().getTriple().getArch() == llvm::Triple::xcore && 216659d1ed5bSDimitry Andric D->getLanguageLinkage() == CLanguageLinkage && 216759d1ed5bSDimitry Andric D->getType().isConstant(Context) && 216859d1ed5bSDimitry Andric isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 216959d1ed5bSDimitry Andric GV->setSection(".cp.rodata"); 217059d1ed5bSDimitry Andric } 217159d1ed5bSDimitry Andric 21727ae0e2c9SDimitry Andric if (AddrSpace != Ty->getAddressSpace()) 2173f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty); 2174f785676fSDimitry Andric 2175f22ef01cSRoman Divacky return GV; 2176f22ef01cSRoman Divacky } 2177f22ef01cSRoman Divacky 21780623d748SDimitry Andric llvm::Constant * 21790623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, 21800623d748SDimitry Andric bool IsForDefinition) { 21810623d748SDimitry Andric if (isa<CXXConstructorDecl>(GD.getDecl())) 21820623d748SDimitry Andric return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()), 21830623d748SDimitry Andric getFromCtorType(GD.getCtorType()), 21840623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 21850623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 21860623d748SDimitry Andric else if (isa<CXXDestructorDecl>(GD.getDecl())) 21870623d748SDimitry Andric return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()), 21880623d748SDimitry Andric getFromDtorType(GD.getDtorType()), 21890623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 21900623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 21910623d748SDimitry Andric else if (isa<CXXMethodDecl>(GD.getDecl())) { 21920623d748SDimitry Andric auto FInfo = &getTypes().arrangeCXXMethodDeclaration( 21930623d748SDimitry Andric cast<CXXMethodDecl>(GD.getDecl())); 21940623d748SDimitry Andric auto Ty = getTypes().GetFunctionType(*FInfo); 21950623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 21960623d748SDimitry Andric IsForDefinition); 21970623d748SDimitry Andric } else if (isa<FunctionDecl>(GD.getDecl())) { 21980623d748SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 21990623d748SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 22000623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 22010623d748SDimitry Andric IsForDefinition); 22020623d748SDimitry Andric } else 2203e7145dcbSDimitry Andric return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()), /*Ty=*/nullptr, 2204e7145dcbSDimitry Andric IsForDefinition); 22050623d748SDimitry Andric } 2206f22ef01cSRoman Divacky 22072754fe60SDimitry Andric llvm::GlobalVariable * 22086122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 22096122f3e6SDimitry Andric llvm::Type *Ty, 22102754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage) { 22112754fe60SDimitry Andric llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 221259d1ed5bSDimitry Andric llvm::GlobalVariable *OldGV = nullptr; 22132754fe60SDimitry Andric 22142754fe60SDimitry Andric if (GV) { 22152754fe60SDimitry Andric // Check if the variable has the right type. 22162754fe60SDimitry Andric if (GV->getType()->getElementType() == Ty) 22172754fe60SDimitry Andric return GV; 22182754fe60SDimitry Andric 22192754fe60SDimitry Andric // Because C++ name mangling, the only way we can end up with an already 22202754fe60SDimitry Andric // existing global with the same name is if it has been declared extern "C". 22212754fe60SDimitry Andric assert(GV->isDeclaration() && "Declaration has wrong type!"); 22222754fe60SDimitry Andric OldGV = GV; 22232754fe60SDimitry Andric } 22242754fe60SDimitry Andric 22252754fe60SDimitry Andric // Create a new variable. 22262754fe60SDimitry Andric GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 222759d1ed5bSDimitry Andric Linkage, nullptr, Name); 22282754fe60SDimitry Andric 22292754fe60SDimitry Andric if (OldGV) { 22302754fe60SDimitry Andric // Replace occurrences of the old variable if needed. 22312754fe60SDimitry Andric GV->takeName(OldGV); 22322754fe60SDimitry Andric 22332754fe60SDimitry Andric if (!OldGV->use_empty()) { 22342754fe60SDimitry Andric llvm::Constant *NewPtrForOldDecl = 22352754fe60SDimitry Andric llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 22362754fe60SDimitry Andric OldGV->replaceAllUsesWith(NewPtrForOldDecl); 22372754fe60SDimitry Andric } 22382754fe60SDimitry Andric 22392754fe60SDimitry Andric OldGV->eraseFromParent(); 22402754fe60SDimitry Andric } 22412754fe60SDimitry Andric 224233956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker() && 224333956c43SDimitry Andric !GV->hasAvailableExternallyLinkage()) 224433956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 224533956c43SDimitry Andric 22462754fe60SDimitry Andric return GV; 22472754fe60SDimitry Andric } 22482754fe60SDimitry Andric 2249f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 2250f22ef01cSRoman Divacky /// given global variable. If Ty is non-null and if the global doesn't exist, 2251cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the 2252e7145dcbSDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guranteed 2253e7145dcbSDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a 2254e7145dcbSDimitry Andric /// variable with the same mangled name but some other type. 2255f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 2256e7145dcbSDimitry Andric llvm::Type *Ty, 2257e7145dcbSDimitry Andric bool IsForDefinition) { 2258f22ef01cSRoman Divacky assert(D->hasGlobalStorage() && "Not a global variable"); 2259f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 226059d1ed5bSDimitry Andric if (!Ty) 2261f22ef01cSRoman Divacky Ty = getTypes().ConvertTypeForMem(ASTTy); 2262f22ef01cSRoman Divacky 22636122f3e6SDimitry Andric llvm::PointerType *PTy = 22643b0f4066SDimitry Andric llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 2265f22ef01cSRoman Divacky 22666122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2267e7145dcbSDimitry Andric return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition); 2268f22ef01cSRoman Divacky } 2269f22ef01cSRoman Divacky 2270f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the 2271f22ef01cSRoman Divacky /// specified type and name. 2272f22ef01cSRoman Divacky llvm::Constant * 22736122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 22746122f3e6SDimitry Andric StringRef Name) { 227559d1ed5bSDimitry Andric return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr); 2276f22ef01cSRoman Divacky } 2277f22ef01cSRoman Divacky 2278f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 2279f22ef01cSRoman Divacky assert(!D->getInit() && "Cannot emit definite definitions here!"); 2280f22ef01cSRoman Divacky 22816122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2282e7145dcbSDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(MangledName); 2283e7145dcbSDimitry Andric 2284e7145dcbSDimitry Andric // We already have a definition, not declaration, with the same mangled name. 2285e7145dcbSDimitry Andric // Emitting of declaration is not required (and actually overwrites emitted 2286e7145dcbSDimitry Andric // definition). 2287e7145dcbSDimitry Andric if (GV && !GV->isDeclaration()) 2288e7145dcbSDimitry Andric return; 2289e7145dcbSDimitry Andric 2290e7145dcbSDimitry Andric // If we have not seen a reference to this variable yet, place it into the 2291e7145dcbSDimitry Andric // deferred declarations table to be emitted if needed later. 2292e7145dcbSDimitry Andric if (!MustBeEmitted(D) && !GV) { 2293f22ef01cSRoman Divacky DeferredDecls[MangledName] = D; 2294f22ef01cSRoman Divacky return; 2295f22ef01cSRoman Divacky } 2296f22ef01cSRoman Divacky 2297f22ef01cSRoman Divacky // The tentative definition is the only definition. 2298f22ef01cSRoman Divacky EmitGlobalVarDefinition(D); 2299f22ef01cSRoman Divacky } 2300f22ef01cSRoman Divacky 23016122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 23022754fe60SDimitry Andric return Context.toCharUnitsFromBits( 23030623d748SDimitry Andric getDataLayout().getTypeStoreSizeInBits(Ty)); 2304f22ef01cSRoman Divacky } 2305f22ef01cSRoman Divacky 23067ae0e2c9SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 23077ae0e2c9SDimitry Andric unsigned AddrSpace) { 2308e7145dcbSDimitry Andric if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) { 23097ae0e2c9SDimitry Andric if (D->hasAttr<CUDAConstantAttr>()) 23107ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 23117ae0e2c9SDimitry Andric else if (D->hasAttr<CUDASharedAttr>()) 23127ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 23137ae0e2c9SDimitry Andric else 23147ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 23157ae0e2c9SDimitry Andric } 23167ae0e2c9SDimitry Andric 23177ae0e2c9SDimitry Andric return AddrSpace; 23187ae0e2c9SDimitry Andric } 23197ae0e2c9SDimitry Andric 2320284c1978SDimitry Andric template<typename SomeDecl> 2321284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 2322284c1978SDimitry Andric llvm::GlobalValue *GV) { 2323284c1978SDimitry Andric if (!getLangOpts().CPlusPlus) 2324284c1978SDimitry Andric return; 2325284c1978SDimitry Andric 2326284c1978SDimitry Andric // Must have 'used' attribute, or else inline assembly can't rely on 2327284c1978SDimitry Andric // the name existing. 2328284c1978SDimitry Andric if (!D->template hasAttr<UsedAttr>()) 2329284c1978SDimitry Andric return; 2330284c1978SDimitry Andric 2331284c1978SDimitry Andric // Must have internal linkage and an ordinary name. 2332f785676fSDimitry Andric if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 2333284c1978SDimitry Andric return; 2334284c1978SDimitry Andric 2335284c1978SDimitry Andric // Must be in an extern "C" context. Entities declared directly within 2336284c1978SDimitry Andric // a record are not extern "C" even if the record is in such a context. 2337f785676fSDimitry Andric const SomeDecl *First = D->getFirstDecl(); 2338284c1978SDimitry Andric if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 2339284c1978SDimitry Andric return; 2340284c1978SDimitry Andric 2341284c1978SDimitry Andric // OK, this is an internal linkage entity inside an extern "C" linkage 2342284c1978SDimitry Andric // specification. Make a note of that so we can give it the "expected" 2343284c1978SDimitry Andric // mangled name if nothing else is using that name. 2344284c1978SDimitry Andric std::pair<StaticExternCMap::iterator, bool> R = 2345284c1978SDimitry Andric StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 2346284c1978SDimitry Andric 2347284c1978SDimitry Andric // If we have multiple internal linkage entities with the same name 2348284c1978SDimitry Andric // in extern "C" regions, none of them gets that name. 2349284c1978SDimitry Andric if (!R.second) 235059d1ed5bSDimitry Andric R.first->second = nullptr; 2351284c1978SDimitry Andric } 2352284c1978SDimitry Andric 235333956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 235433956c43SDimitry Andric if (!CGM.supportsCOMDAT()) 235533956c43SDimitry Andric return false; 235633956c43SDimitry Andric 235733956c43SDimitry Andric if (D.hasAttr<SelectAnyAttr>()) 235833956c43SDimitry Andric return true; 235933956c43SDimitry Andric 236033956c43SDimitry Andric GVALinkage Linkage; 236133956c43SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(&D)) 236233956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 236333956c43SDimitry Andric else 236433956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 236533956c43SDimitry Andric 236633956c43SDimitry Andric switch (Linkage) { 236733956c43SDimitry Andric case GVA_Internal: 236833956c43SDimitry Andric case GVA_AvailableExternally: 236933956c43SDimitry Andric case GVA_StrongExternal: 237033956c43SDimitry Andric return false; 237133956c43SDimitry Andric case GVA_DiscardableODR: 237233956c43SDimitry Andric case GVA_StrongODR: 237333956c43SDimitry Andric return true; 237433956c43SDimitry Andric } 237533956c43SDimitry Andric llvm_unreachable("No such linkage"); 237633956c43SDimitry Andric } 237733956c43SDimitry Andric 237833956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 237933956c43SDimitry Andric llvm::GlobalObject &GO) { 238033956c43SDimitry Andric if (!shouldBeInCOMDAT(*this, D)) 238133956c43SDimitry Andric return; 238233956c43SDimitry Andric GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 238333956c43SDimitry Andric } 238433956c43SDimitry Andric 2385e7145dcbSDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition. 2386e7145dcbSDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 2387e7145dcbSDimitry Andric bool IsTentative) { 238859d1ed5bSDimitry Andric llvm::Constant *Init = nullptr; 2389f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 2390dff0c46cSDimitry Andric CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2391dff0c46cSDimitry Andric bool NeedsGlobalCtor = false; 2392dff0c46cSDimitry Andric bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 2393f22ef01cSRoman Divacky 2394dff0c46cSDimitry Andric const VarDecl *InitDecl; 2395dff0c46cSDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 2396f22ef01cSRoman Divacky 2397e7145dcbSDimitry Andric // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 2398e7145dcbSDimitry Andric // as part of their declaration." Sema has already checked for 2399e7145dcbSDimitry Andric // error cases, so we just need to set Init to UndefValue. 2400e7145dcbSDimitry Andric if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 2401e7145dcbSDimitry Andric D->hasAttr<CUDASharedAttr>()) 24020623d748SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 2403e7145dcbSDimitry Andric else if (!InitExpr) { 2404f22ef01cSRoman Divacky // This is a tentative definition; tentative definitions are 2405f22ef01cSRoman Divacky // implicitly initialized with { 0 }. 2406f22ef01cSRoman Divacky // 2407f22ef01cSRoman Divacky // Note that tentative definitions are only emitted at the end of 2408f22ef01cSRoman Divacky // a translation unit, so they should never have incomplete 2409f22ef01cSRoman Divacky // type. In addition, EmitTentativeDefinition makes sure that we 2410f22ef01cSRoman Divacky // never attempt to emit a tentative definition if a real one 2411f22ef01cSRoman Divacky // exists. A use may still exists, however, so we still may need 2412f22ef01cSRoman Divacky // to do a RAUW. 2413f22ef01cSRoman Divacky assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 2414f22ef01cSRoman Divacky Init = EmitNullConstant(D->getType()); 2415f22ef01cSRoman Divacky } else { 24167ae0e2c9SDimitry Andric initializedGlobalDecl = GlobalDecl(D); 2417dff0c46cSDimitry Andric Init = EmitConstantInit(*InitDecl); 2418f785676fSDimitry Andric 2419f22ef01cSRoman Divacky if (!Init) { 2420f22ef01cSRoman Divacky QualType T = InitExpr->getType(); 2421f22ef01cSRoman Divacky if (D->getType()->isReferenceType()) 2422f22ef01cSRoman Divacky T = D->getType(); 2423f22ef01cSRoman Divacky 2424dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus) { 2425f22ef01cSRoman Divacky Init = EmitNullConstant(T); 2426dff0c46cSDimitry Andric NeedsGlobalCtor = true; 2427f22ef01cSRoman Divacky } else { 2428f22ef01cSRoman Divacky ErrorUnsupported(D, "static initializer"); 2429f22ef01cSRoman Divacky Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 2430f22ef01cSRoman Divacky } 2431e580952dSDimitry Andric } else { 2432e580952dSDimitry Andric // We don't need an initializer, so remove the entry for the delayed 2433dff0c46cSDimitry Andric // initializer position (just in case this entry was delayed) if we 2434dff0c46cSDimitry Andric // also don't need to register a destructor. 2435dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 2436e580952dSDimitry Andric DelayedCXXInitPosition.erase(D); 2437f22ef01cSRoman Divacky } 2438f22ef01cSRoman Divacky } 2439f22ef01cSRoman Divacky 24406122f3e6SDimitry Andric llvm::Type* InitType = Init->getType(); 2441e7145dcbSDimitry Andric llvm::Constant *Entry = 2442e7145dcbSDimitry Andric GetAddrOfGlobalVar(D, InitType, /*IsForDefinition=*/!IsTentative); 2443f22ef01cSRoman Divacky 2444f22ef01cSRoman Divacky // Strip off a bitcast if we got one back. 244559d1ed5bSDimitry Andric if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2446f22ef01cSRoman Divacky assert(CE->getOpcode() == llvm::Instruction::BitCast || 2447f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 2448f785676fSDimitry Andric // All zero index gep. 2449f22ef01cSRoman Divacky CE->getOpcode() == llvm::Instruction::GetElementPtr); 2450f22ef01cSRoman Divacky Entry = CE->getOperand(0); 2451f22ef01cSRoman Divacky } 2452f22ef01cSRoman Divacky 2453f22ef01cSRoman Divacky // Entry is now either a Function or GlobalVariable. 245459d1ed5bSDimitry Andric auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 2455f22ef01cSRoman Divacky 2456f22ef01cSRoman Divacky // We have a definition after a declaration with the wrong type. 2457f22ef01cSRoman Divacky // We must make a new GlobalVariable* and update everything that used OldGV 2458f22ef01cSRoman Divacky // (a declaration or tentative definition) with the new GlobalVariable* 2459f22ef01cSRoman Divacky // (which will be a definition). 2460f22ef01cSRoman Divacky // 2461f22ef01cSRoman Divacky // This happens if there is a prototype for a global (e.g. 2462f22ef01cSRoman Divacky // "extern int x[];") and then a definition of a different type (e.g. 2463f22ef01cSRoman Divacky // "int x[10];"). This also happens when an initializer has a different type 2464f22ef01cSRoman Divacky // from the type of the global (this happens with unions). 246559d1ed5bSDimitry Andric if (!GV || 2466f22ef01cSRoman Divacky GV->getType()->getElementType() != InitType || 24673b0f4066SDimitry Andric GV->getType()->getAddressSpace() != 24687ae0e2c9SDimitry Andric GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 2469f22ef01cSRoman Divacky 2470f22ef01cSRoman Divacky // Move the old entry aside so that we'll create a new one. 24716122f3e6SDimitry Andric Entry->setName(StringRef()); 2472f22ef01cSRoman Divacky 2473f22ef01cSRoman Divacky // Make a new global with the correct type, this is now guaranteed to work. 2474e7145dcbSDimitry Andric GV = cast<llvm::GlobalVariable>( 2475e7145dcbSDimitry Andric GetAddrOfGlobalVar(D, InitType, /*IsForDefinition=*/!IsTentative)); 2476f22ef01cSRoman Divacky 2477f22ef01cSRoman Divacky // Replace all uses of the old global with the new global 2478f22ef01cSRoman Divacky llvm::Constant *NewPtrForOldDecl = 2479f22ef01cSRoman Divacky llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2480f22ef01cSRoman Divacky Entry->replaceAllUsesWith(NewPtrForOldDecl); 2481f22ef01cSRoman Divacky 2482f22ef01cSRoman Divacky // Erase the old global, since it is no longer used. 2483f22ef01cSRoman Divacky cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 2484f22ef01cSRoman Divacky } 2485f22ef01cSRoman Divacky 2486284c1978SDimitry Andric MaybeHandleStaticInExternC(D, GV); 2487284c1978SDimitry Andric 24886122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 24896122f3e6SDimitry Andric AddGlobalAnnotations(D, GV); 2490f22ef01cSRoman Divacky 2491e7145dcbSDimitry Andric // Set the llvm linkage type as appropriate. 2492e7145dcbSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 2493e7145dcbSDimitry Andric getLLVMLinkageVarDefinition(D, GV->isConstant()); 2494e7145dcbSDimitry Andric 24950623d748SDimitry Andric // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 24960623d748SDimitry Andric // the device. [...]" 24970623d748SDimitry Andric // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 24980623d748SDimitry Andric // __device__, declares a variable that: [...] 24990623d748SDimitry Andric // Is accessible from all the threads within the grid and from the host 25000623d748SDimitry Andric // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 25010623d748SDimitry Andric // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 2502e7145dcbSDimitry Andric if (GV && LangOpts.CUDA) { 2503e7145dcbSDimitry Andric if (LangOpts.CUDAIsDevice) { 2504e7145dcbSDimitry Andric if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) 25050623d748SDimitry Andric GV->setExternallyInitialized(true); 2506e7145dcbSDimitry Andric } else { 2507e7145dcbSDimitry Andric // Host-side shadows of external declarations of device-side 2508e7145dcbSDimitry Andric // global variables become internal definitions. These have to 2509e7145dcbSDimitry Andric // be internal in order to prevent name conflicts with global 2510e7145dcbSDimitry Andric // host variables with the same name in a different TUs. 2511e7145dcbSDimitry Andric if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) { 2512e7145dcbSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 2513e7145dcbSDimitry Andric 2514e7145dcbSDimitry Andric // Shadow variables and their properties must be registered 2515e7145dcbSDimitry Andric // with CUDA runtime. 2516e7145dcbSDimitry Andric unsigned Flags = 0; 2517e7145dcbSDimitry Andric if (!D->hasDefinition()) 2518e7145dcbSDimitry Andric Flags |= CGCUDARuntime::ExternDeviceVar; 2519e7145dcbSDimitry Andric if (D->hasAttr<CUDAConstantAttr>()) 2520e7145dcbSDimitry Andric Flags |= CGCUDARuntime::ConstantDeviceVar; 2521e7145dcbSDimitry Andric getCUDARuntime().registerDeviceVar(*GV, Flags); 2522e7145dcbSDimitry Andric } else if (D->hasAttr<CUDASharedAttr>()) 2523e7145dcbSDimitry Andric // __shared__ variables are odd. Shadows do get created, but 2524e7145dcbSDimitry Andric // they are not registered with the CUDA runtime, so they 2525e7145dcbSDimitry Andric // can't really be used to access their device-side 2526e7145dcbSDimitry Andric // counterparts. It's not clear yet whether it's nvcc's bug or 2527e7145dcbSDimitry Andric // a feature, but we've got to do the same for compatibility. 2528e7145dcbSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 2529e7145dcbSDimitry Andric } 25300623d748SDimitry Andric } 2531f22ef01cSRoman Divacky GV->setInitializer(Init); 2532f22ef01cSRoman Divacky 2533f22ef01cSRoman Divacky // If it is safe to mark the global 'constant', do so now. 2534dff0c46cSDimitry Andric GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 2535dff0c46cSDimitry Andric isTypeConstant(D->getType(), true)); 2536f22ef01cSRoman Divacky 253739d628a0SDimitry Andric // If it is in a read-only section, mark it 'constant'. 253839d628a0SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 253939d628a0SDimitry Andric const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 254039d628a0SDimitry Andric if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 254139d628a0SDimitry Andric GV->setConstant(true); 254239d628a0SDimitry Andric } 254339d628a0SDimitry Andric 2544f22ef01cSRoman Divacky GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 2545f22ef01cSRoman Divacky 2546f785676fSDimitry Andric 25470623d748SDimitry Andric // On Darwin, if the normal linkage of a C++ thread_local variable is 25480623d748SDimitry Andric // LinkOnce or Weak, we keep the normal linkage to prevent multiple 25490623d748SDimitry Andric // copies within a linkage unit; otherwise, the backing variable has 25500623d748SDimitry Andric // internal linkage and all accesses should just be calls to the 255159d1ed5bSDimitry Andric // Itanium-specified entry point, which has the normal linkage of the 25520623d748SDimitry Andric // variable. This is to preserve the ability to change the implementation 25530623d748SDimitry Andric // behind the scenes. 255439d628a0SDimitry Andric if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic && 25550623d748SDimitry Andric Context.getTargetInfo().getTriple().isOSDarwin() && 25560623d748SDimitry Andric !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) && 25570623d748SDimitry Andric !llvm::GlobalVariable::isWeakLinkage(Linkage)) 255859d1ed5bSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 255959d1ed5bSDimitry Andric 256059d1ed5bSDimitry Andric GV->setLinkage(Linkage); 256159d1ed5bSDimitry Andric if (D->hasAttr<DLLImportAttr>()) 256259d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 256359d1ed5bSDimitry Andric else if (D->hasAttr<DLLExportAttr>()) 256459d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 256539d628a0SDimitry Andric else 256639d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 2567f785676fSDimitry Andric 25682754fe60SDimitry Andric if (Linkage == llvm::GlobalVariable::CommonLinkage) 2569f22ef01cSRoman Divacky // common vars aren't constant even if declared const. 2570f22ef01cSRoman Divacky GV->setConstant(false); 2571f22ef01cSRoman Divacky 257259d1ed5bSDimitry Andric setNonAliasAttributes(D, GV); 2573f22ef01cSRoman Divacky 257439d628a0SDimitry Andric if (D->getTLSKind() && !GV->isThreadLocal()) { 257539d628a0SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 25760623d748SDimitry Andric CXXThreadLocals.push_back(D); 257739d628a0SDimitry Andric setTLSMode(GV, *D); 257839d628a0SDimitry Andric } 257939d628a0SDimitry Andric 258033956c43SDimitry Andric maybeSetTrivialComdat(*D, *GV); 258133956c43SDimitry Andric 25822754fe60SDimitry Andric // Emit the initializer function if necessary. 2583dff0c46cSDimitry Andric if (NeedsGlobalCtor || NeedsGlobalDtor) 2584dff0c46cSDimitry Andric EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 25852754fe60SDimitry Andric 258639d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 25873861d79fSDimitry Andric 2588f22ef01cSRoman Divacky // Emit global variable debug information. 25896122f3e6SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 2590e7145dcbSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 2591f22ef01cSRoman Divacky DI->EmitGlobalVariable(GV, D); 2592f22ef01cSRoman Divacky } 2593f22ef01cSRoman Divacky 259439d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context, 259533956c43SDimitry Andric CodeGenModule &CGM, const VarDecl *D, 259633956c43SDimitry Andric bool NoCommon) { 259759d1ed5bSDimitry Andric // Don't give variables common linkage if -fno-common was specified unless it 259859d1ed5bSDimitry Andric // was overridden by a NoCommon attribute. 259959d1ed5bSDimitry Andric if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 260059d1ed5bSDimitry Andric return true; 260159d1ed5bSDimitry Andric 260259d1ed5bSDimitry Andric // C11 6.9.2/2: 260359d1ed5bSDimitry Andric // A declaration of an identifier for an object that has file scope without 260459d1ed5bSDimitry Andric // an initializer, and without a storage-class specifier or with the 260559d1ed5bSDimitry Andric // storage-class specifier static, constitutes a tentative definition. 260659d1ed5bSDimitry Andric if (D->getInit() || D->hasExternalStorage()) 260759d1ed5bSDimitry Andric return true; 260859d1ed5bSDimitry Andric 260959d1ed5bSDimitry Andric // A variable cannot be both common and exist in a section. 261059d1ed5bSDimitry Andric if (D->hasAttr<SectionAttr>()) 261159d1ed5bSDimitry Andric return true; 261259d1ed5bSDimitry Andric 261359d1ed5bSDimitry Andric // Thread local vars aren't considered common linkage. 261459d1ed5bSDimitry Andric if (D->getTLSKind()) 261559d1ed5bSDimitry Andric return true; 261659d1ed5bSDimitry Andric 261759d1ed5bSDimitry Andric // Tentative definitions marked with WeakImportAttr are true definitions. 261859d1ed5bSDimitry Andric if (D->hasAttr<WeakImportAttr>()) 261959d1ed5bSDimitry Andric return true; 262059d1ed5bSDimitry Andric 262133956c43SDimitry Andric // A variable cannot be both common and exist in a comdat. 262233956c43SDimitry Andric if (shouldBeInCOMDAT(CGM, *D)) 262333956c43SDimitry Andric return true; 262433956c43SDimitry Andric 2625e7145dcbSDimitry Andric // Declarations with a required alignment do not have common linkage in MSVC 262639d628a0SDimitry Andric // mode. 26270623d748SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 262833956c43SDimitry Andric if (D->hasAttr<AlignedAttr>()) 262939d628a0SDimitry Andric return true; 263033956c43SDimitry Andric QualType VarType = D->getType(); 263133956c43SDimitry Andric if (Context.isAlignmentRequired(VarType)) 263233956c43SDimitry Andric return true; 263333956c43SDimitry Andric 263433956c43SDimitry Andric if (const auto *RT = VarType->getAs<RecordType>()) { 263533956c43SDimitry Andric const RecordDecl *RD = RT->getDecl(); 263633956c43SDimitry Andric for (const FieldDecl *FD : RD->fields()) { 263733956c43SDimitry Andric if (FD->isBitField()) 263833956c43SDimitry Andric continue; 263933956c43SDimitry Andric if (FD->hasAttr<AlignedAttr>()) 264033956c43SDimitry Andric return true; 264133956c43SDimitry Andric if (Context.isAlignmentRequired(FD->getType())) 264233956c43SDimitry Andric return true; 264333956c43SDimitry Andric } 264433956c43SDimitry Andric } 264533956c43SDimitry Andric } 264639d628a0SDimitry Andric 264759d1ed5bSDimitry Andric return false; 264859d1ed5bSDimitry Andric } 264959d1ed5bSDimitry Andric 265059d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 265159d1ed5bSDimitry Andric const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 26522754fe60SDimitry Andric if (Linkage == GVA_Internal) 26532754fe60SDimitry Andric return llvm::Function::InternalLinkage; 265459d1ed5bSDimitry Andric 265559d1ed5bSDimitry Andric if (D->hasAttr<WeakAttr>()) { 265659d1ed5bSDimitry Andric if (IsConstantVariable) 265759d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 265859d1ed5bSDimitry Andric else 265959d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakAnyLinkage; 266059d1ed5bSDimitry Andric } 266159d1ed5bSDimitry Andric 266259d1ed5bSDimitry Andric // We are guaranteed to have a strong definition somewhere else, 266359d1ed5bSDimitry Andric // so we can use available_externally linkage. 266459d1ed5bSDimitry Andric if (Linkage == GVA_AvailableExternally) 266559d1ed5bSDimitry Andric return llvm::Function::AvailableExternallyLinkage; 266659d1ed5bSDimitry Andric 266759d1ed5bSDimitry Andric // Note that Apple's kernel linker doesn't support symbol 266859d1ed5bSDimitry Andric // coalescing, so we need to avoid linkonce and weak linkages there. 266959d1ed5bSDimitry Andric // Normally, this means we just map to internal, but for explicit 267059d1ed5bSDimitry Andric // instantiations we'll map to external. 267159d1ed5bSDimitry Andric 267259d1ed5bSDimitry Andric // In C++, the compiler has to emit a definition in every translation unit 267359d1ed5bSDimitry Andric // that references the function. We should use linkonce_odr because 267459d1ed5bSDimitry Andric // a) if all references in this translation unit are optimized away, we 267559d1ed5bSDimitry Andric // don't need to codegen it. b) if the function persists, it needs to be 267659d1ed5bSDimitry Andric // merged with other definitions. c) C++ has the ODR, so we know the 267759d1ed5bSDimitry Andric // definition is dependable. 267859d1ed5bSDimitry Andric if (Linkage == GVA_DiscardableODR) 267959d1ed5bSDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 268059d1ed5bSDimitry Andric : llvm::Function::InternalLinkage; 268159d1ed5bSDimitry Andric 268259d1ed5bSDimitry Andric // An explicit instantiation of a template has weak linkage, since 268359d1ed5bSDimitry Andric // explicit instantiations can occur in multiple translation units 268459d1ed5bSDimitry Andric // and must all be equivalent. However, we are not allowed to 268559d1ed5bSDimitry Andric // throw away these explicit instantiations. 2686e7145dcbSDimitry Andric // 2687e7145dcbSDimitry Andric // We don't currently support CUDA device code spread out across multiple TUs, 2688e7145dcbSDimitry Andric // so say that CUDA templates are either external (for kernels) or internal. 2689e7145dcbSDimitry Andric // This lets llvm perform aggressive inter-procedural optimizations. 2690e7145dcbSDimitry Andric if (Linkage == GVA_StrongODR) { 2691e7145dcbSDimitry Andric if (Context.getLangOpts().AppleKext) 2692e7145dcbSDimitry Andric return llvm::Function::ExternalLinkage; 2693e7145dcbSDimitry Andric if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) 2694e7145dcbSDimitry Andric return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 2695e7145dcbSDimitry Andric : llvm::Function::InternalLinkage; 2696e7145dcbSDimitry Andric return llvm::Function::WeakODRLinkage; 2697e7145dcbSDimitry Andric } 269859d1ed5bSDimitry Andric 269959d1ed5bSDimitry Andric // C++ doesn't have tentative definitions and thus cannot have common 270059d1ed5bSDimitry Andric // linkage. 270159d1ed5bSDimitry Andric if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 270233956c43SDimitry Andric !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 270339d628a0SDimitry Andric CodeGenOpts.NoCommon)) 270459d1ed5bSDimitry Andric return llvm::GlobalVariable::CommonLinkage; 270559d1ed5bSDimitry Andric 2706f785676fSDimitry Andric // selectany symbols are externally visible, so use weak instead of 2707f785676fSDimitry Andric // linkonce. MSVC optimizes away references to const selectany globals, so 2708f785676fSDimitry Andric // all definitions should be the same and ODR linkage should be used. 2709f785676fSDimitry Andric // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 271059d1ed5bSDimitry Andric if (D->hasAttr<SelectAnyAttr>()) 2711f785676fSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 271259d1ed5bSDimitry Andric 271359d1ed5bSDimitry Andric // Otherwise, we have strong external linkage. 271459d1ed5bSDimitry Andric assert(Linkage == GVA_StrongExternal); 27152754fe60SDimitry Andric return llvm::GlobalVariable::ExternalLinkage; 27162754fe60SDimitry Andric } 27172754fe60SDimitry Andric 271859d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 271959d1ed5bSDimitry Andric const VarDecl *VD, bool IsConstant) { 272059d1ed5bSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 272159d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 272259d1ed5bSDimitry Andric } 272359d1ed5bSDimitry Andric 2724139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type. 2725139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites 2726139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 2727139f7f9bSDimitry Andric llvm::Function *newFn) { 2728139f7f9bSDimitry Andric // Fast path. 2729139f7f9bSDimitry Andric if (old->use_empty()) return; 2730139f7f9bSDimitry Andric 2731139f7f9bSDimitry Andric llvm::Type *newRetTy = newFn->getReturnType(); 2732139f7f9bSDimitry Andric SmallVector<llvm::Value*, 4> newArgs; 27330623d748SDimitry Andric SmallVector<llvm::OperandBundleDef, 1> newBundles; 2734139f7f9bSDimitry Andric 2735139f7f9bSDimitry Andric for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 2736139f7f9bSDimitry Andric ui != ue; ) { 2737139f7f9bSDimitry Andric llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 273859d1ed5bSDimitry Andric llvm::User *user = use->getUser(); 2739139f7f9bSDimitry Andric 2740139f7f9bSDimitry Andric // Recognize and replace uses of bitcasts. Most calls to 2741139f7f9bSDimitry Andric // unprototyped functions will use bitcasts. 274259d1ed5bSDimitry Andric if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 2743139f7f9bSDimitry Andric if (bitcast->getOpcode() == llvm::Instruction::BitCast) 2744139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(bitcast, newFn); 2745139f7f9bSDimitry Andric continue; 2746139f7f9bSDimitry Andric } 2747139f7f9bSDimitry Andric 2748139f7f9bSDimitry Andric // Recognize calls to the function. 2749139f7f9bSDimitry Andric llvm::CallSite callSite(user); 2750139f7f9bSDimitry Andric if (!callSite) continue; 275159d1ed5bSDimitry Andric if (!callSite.isCallee(&*use)) continue; 2752139f7f9bSDimitry Andric 2753139f7f9bSDimitry Andric // If the return types don't match exactly, then we can't 2754139f7f9bSDimitry Andric // transform this call unless it's dead. 2755139f7f9bSDimitry Andric if (callSite->getType() != newRetTy && !callSite->use_empty()) 2756139f7f9bSDimitry Andric continue; 2757139f7f9bSDimitry Andric 2758139f7f9bSDimitry Andric // Get the call site's attribute list. 2759139f7f9bSDimitry Andric SmallVector<llvm::AttributeSet, 8> newAttrs; 2760139f7f9bSDimitry Andric llvm::AttributeSet oldAttrs = callSite.getAttributes(); 2761139f7f9bSDimitry Andric 2762139f7f9bSDimitry Andric // Collect any return attributes from the call. 2763139f7f9bSDimitry Andric if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex)) 2764139f7f9bSDimitry Andric newAttrs.push_back( 2765139f7f9bSDimitry Andric llvm::AttributeSet::get(newFn->getContext(), 2766139f7f9bSDimitry Andric oldAttrs.getRetAttributes())); 2767139f7f9bSDimitry Andric 2768139f7f9bSDimitry Andric // If the function was passed too few arguments, don't transform. 2769139f7f9bSDimitry Andric unsigned newNumArgs = newFn->arg_size(); 2770139f7f9bSDimitry Andric if (callSite.arg_size() < newNumArgs) continue; 2771139f7f9bSDimitry Andric 2772139f7f9bSDimitry Andric // If extra arguments were passed, we silently drop them. 2773139f7f9bSDimitry Andric // If any of the types mismatch, we don't transform. 2774139f7f9bSDimitry Andric unsigned argNo = 0; 2775139f7f9bSDimitry Andric bool dontTransform = false; 2776139f7f9bSDimitry Andric for (llvm::Function::arg_iterator ai = newFn->arg_begin(), 2777139f7f9bSDimitry Andric ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) { 2778139f7f9bSDimitry Andric if (callSite.getArgument(argNo)->getType() != ai->getType()) { 2779139f7f9bSDimitry Andric dontTransform = true; 2780139f7f9bSDimitry Andric break; 2781139f7f9bSDimitry Andric } 2782139f7f9bSDimitry Andric 2783139f7f9bSDimitry Andric // Add any parameter attributes. 2784139f7f9bSDimitry Andric if (oldAttrs.hasAttributes(argNo + 1)) 2785139f7f9bSDimitry Andric newAttrs. 2786139f7f9bSDimitry Andric push_back(llvm:: 2787139f7f9bSDimitry Andric AttributeSet::get(newFn->getContext(), 2788139f7f9bSDimitry Andric oldAttrs.getParamAttributes(argNo + 1))); 2789139f7f9bSDimitry Andric } 2790139f7f9bSDimitry Andric if (dontTransform) 2791139f7f9bSDimitry Andric continue; 2792139f7f9bSDimitry Andric 2793139f7f9bSDimitry Andric if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) 2794139f7f9bSDimitry Andric newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(), 2795139f7f9bSDimitry Andric oldAttrs.getFnAttributes())); 2796139f7f9bSDimitry Andric 2797139f7f9bSDimitry Andric // Okay, we can transform this. Create the new call instruction and copy 2798139f7f9bSDimitry Andric // over the required information. 2799139f7f9bSDimitry Andric newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 2800139f7f9bSDimitry Andric 28010623d748SDimitry Andric // Copy over any operand bundles. 28020623d748SDimitry Andric callSite.getOperandBundlesAsDefs(newBundles); 28030623d748SDimitry Andric 2804139f7f9bSDimitry Andric llvm::CallSite newCall; 2805139f7f9bSDimitry Andric if (callSite.isCall()) { 28060623d748SDimitry Andric newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "", 2807139f7f9bSDimitry Andric callSite.getInstruction()); 2808139f7f9bSDimitry Andric } else { 280959d1ed5bSDimitry Andric auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction()); 2810139f7f9bSDimitry Andric newCall = llvm::InvokeInst::Create(newFn, 2811139f7f9bSDimitry Andric oldInvoke->getNormalDest(), 2812139f7f9bSDimitry Andric oldInvoke->getUnwindDest(), 28130623d748SDimitry Andric newArgs, newBundles, "", 2814139f7f9bSDimitry Andric callSite.getInstruction()); 2815139f7f9bSDimitry Andric } 2816139f7f9bSDimitry Andric newArgs.clear(); // for the next iteration 2817139f7f9bSDimitry Andric 2818139f7f9bSDimitry Andric if (!newCall->getType()->isVoidTy()) 2819139f7f9bSDimitry Andric newCall->takeName(callSite.getInstruction()); 2820139f7f9bSDimitry Andric newCall.setAttributes( 2821139f7f9bSDimitry Andric llvm::AttributeSet::get(newFn->getContext(), newAttrs)); 2822139f7f9bSDimitry Andric newCall.setCallingConv(callSite.getCallingConv()); 2823139f7f9bSDimitry Andric 2824139f7f9bSDimitry Andric // Finally, remove the old call, replacing any uses with the new one. 2825139f7f9bSDimitry Andric if (!callSite->use_empty()) 2826139f7f9bSDimitry Andric callSite->replaceAllUsesWith(newCall.getInstruction()); 2827139f7f9bSDimitry Andric 2828139f7f9bSDimitry Andric // Copy debug location attached to CI. 282933956c43SDimitry Andric if (callSite->getDebugLoc()) 2830139f7f9bSDimitry Andric newCall->setDebugLoc(callSite->getDebugLoc()); 28310623d748SDimitry Andric 2832139f7f9bSDimitry Andric callSite->eraseFromParent(); 2833139f7f9bSDimitry Andric } 2834139f7f9bSDimitry Andric } 2835139f7f9bSDimitry Andric 2836f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 2837f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}". If there are 2838f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to 2839f22ef01cSRoman Divacky /// call the new function directly. 2840f22ef01cSRoman Divacky /// 2841f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to 2842f22ef01cSRoman Divacky /// functions to be able to inline them. If there is a bitcast in the way, it 2843f22ef01cSRoman Divacky /// won't inline them. Instcombine normally deletes these calls, but it isn't 2844f22ef01cSRoman Divacky /// run at -O0. 2845f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2846f22ef01cSRoman Divacky llvm::Function *NewFn) { 2847f22ef01cSRoman Divacky // If we're redefining a global as a function, don't transform it. 2848139f7f9bSDimitry Andric if (!isa<llvm::Function>(Old)) return; 2849f22ef01cSRoman Divacky 2850139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(Old, NewFn); 2851f22ef01cSRoman Divacky } 2852f22ef01cSRoman Divacky 2853dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 2854e7145dcbSDimitry Andric auto DK = VD->isThisDeclarationADefinition(); 2855e7145dcbSDimitry Andric if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 2856e7145dcbSDimitry Andric return; 2857e7145dcbSDimitry Andric 2858dff0c46cSDimitry Andric TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 2859dff0c46cSDimitry Andric // If we have a definition, this might be a deferred decl. If the 2860dff0c46cSDimitry Andric // instantiation is explicit, make sure we emit it at the end. 2861dff0c46cSDimitry Andric if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 2862dff0c46cSDimitry Andric GetAddrOfGlobalVar(VD); 2863139f7f9bSDimitry Andric 2864139f7f9bSDimitry Andric EmitTopLevelDecl(VD); 2865dff0c46cSDimitry Andric } 2866f22ef01cSRoman Divacky 286759d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 286859d1ed5bSDimitry Andric llvm::GlobalValue *GV) { 286959d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 28703b0f4066SDimitry Andric 28713b0f4066SDimitry Andric // Compute the function info and LLVM type. 2872dff0c46cSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2873dff0c46cSDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 28743b0f4066SDimitry Andric 2875f22ef01cSRoman Divacky // Get or create the prototype for the function. 28760623d748SDimitry Andric if (!GV || (GV->getType()->getElementType() != Ty)) 28770623d748SDimitry Andric GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 28780623d748SDimitry Andric /*DontDefer=*/true, 28790623d748SDimitry Andric /*IsForDefinition=*/true)); 2880f22ef01cSRoman Divacky 28810623d748SDimitry Andric // Already emitted. 28820623d748SDimitry Andric if (!GV->isDeclaration()) 2883f785676fSDimitry Andric return; 2884f22ef01cSRoman Divacky 28852754fe60SDimitry Andric // We need to set linkage and visibility on the function before 28862754fe60SDimitry Andric // generating code for it because various parts of IR generation 28872754fe60SDimitry Andric // want to propagate this information down (e.g. to local static 28882754fe60SDimitry Andric // declarations). 288959d1ed5bSDimitry Andric auto *Fn = cast<llvm::Function>(GV); 2890f785676fSDimitry Andric setFunctionLinkage(GD, Fn); 289197bc6c73SDimitry Andric setFunctionDLLStorageClass(GD, Fn); 2892f22ef01cSRoman Divacky 289359d1ed5bSDimitry Andric // FIXME: this is redundant with part of setFunctionDefinitionAttributes 28942754fe60SDimitry Andric setGlobalVisibility(Fn, D); 28952754fe60SDimitry Andric 2896284c1978SDimitry Andric MaybeHandleStaticInExternC(D, Fn); 2897284c1978SDimitry Andric 289833956c43SDimitry Andric maybeSetTrivialComdat(*D, *Fn); 289933956c43SDimitry Andric 29003b0f4066SDimitry Andric CodeGenFunction(*this).GenerateCode(D, Fn, FI); 2901f22ef01cSRoman Divacky 290259d1ed5bSDimitry Andric setFunctionDefinitionAttributes(D, Fn); 2903f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, Fn); 2904f22ef01cSRoman Divacky 2905f22ef01cSRoman Divacky if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 2906f22ef01cSRoman Divacky AddGlobalCtor(Fn, CA->getPriority()); 2907f22ef01cSRoman Divacky if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 2908f22ef01cSRoman Divacky AddGlobalDtor(Fn, DA->getPriority()); 29096122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 29106122f3e6SDimitry Andric AddGlobalAnnotations(D, Fn); 2911f22ef01cSRoman Divacky } 2912f22ef01cSRoman Divacky 2913f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 291459d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 2915f22ef01cSRoman Divacky const AliasAttr *AA = D->getAttr<AliasAttr>(); 2916f22ef01cSRoman Divacky assert(AA && "Not an alias?"); 2917f22ef01cSRoman Divacky 29186122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 2919f22ef01cSRoman Divacky 29209a4b3118SDimitry Andric if (AA->getAliasee() == MangledName) { 2921e7145dcbSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 29229a4b3118SDimitry Andric return; 29239a4b3118SDimitry Andric } 29249a4b3118SDimitry Andric 2925f22ef01cSRoman Divacky // If there is a definition in the module, then it wins over the alias. 2926f22ef01cSRoman Divacky // This is dubious, but allow it to be safe. Just ignore the alias. 2927f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2928f22ef01cSRoman Divacky if (Entry && !Entry->isDeclaration()) 2929f22ef01cSRoman Divacky return; 2930f22ef01cSRoman Divacky 2931f785676fSDimitry Andric Aliases.push_back(GD); 2932f785676fSDimitry Andric 29336122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 2934f22ef01cSRoman Divacky 2935f22ef01cSRoman Divacky // Create a reference to the named value. This ensures that it is emitted 2936f22ef01cSRoman Divacky // if a deferred decl. 2937f22ef01cSRoman Divacky llvm::Constant *Aliasee; 2938f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 29393861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 29402754fe60SDimitry Andric /*ForVTable=*/false); 2941f22ef01cSRoman Divacky else 2942f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 294359d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 294439d628a0SDimitry Andric /*D=*/nullptr); 2945f22ef01cSRoman Divacky 2946f22ef01cSRoman Divacky // Create the new alias itself, but don't set a name yet. 294759d1ed5bSDimitry Andric auto *GA = llvm::GlobalAlias::create( 29480623d748SDimitry Andric DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule()); 2949f22ef01cSRoman Divacky 2950f22ef01cSRoman Divacky if (Entry) { 295159d1ed5bSDimitry Andric if (GA->getAliasee() == Entry) { 2952e7145dcbSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 295359d1ed5bSDimitry Andric return; 295459d1ed5bSDimitry Andric } 295559d1ed5bSDimitry Andric 2956f22ef01cSRoman Divacky assert(Entry->isDeclaration()); 2957f22ef01cSRoman Divacky 2958f22ef01cSRoman Divacky // If there is a declaration in the module, then we had an extern followed 2959f22ef01cSRoman Divacky // by the alias, as in: 2960f22ef01cSRoman Divacky // extern int test6(); 2961f22ef01cSRoman Divacky // ... 2962f22ef01cSRoman Divacky // int test6() __attribute__((alias("test7"))); 2963f22ef01cSRoman Divacky // 2964f22ef01cSRoman Divacky // Remove it and replace uses of it with the alias. 2965f22ef01cSRoman Divacky GA->takeName(Entry); 2966f22ef01cSRoman Divacky 2967f22ef01cSRoman Divacky Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 2968f22ef01cSRoman Divacky Entry->getType())); 2969f22ef01cSRoman Divacky Entry->eraseFromParent(); 2970f22ef01cSRoman Divacky } else { 2971ffd1746dSEd Schouten GA->setName(MangledName); 2972f22ef01cSRoman Divacky } 2973f22ef01cSRoman Divacky 2974f22ef01cSRoman Divacky // Set attributes which are particular to an alias; this is a 2975f22ef01cSRoman Divacky // specialization of the attributes which may be set on a global 2976f22ef01cSRoman Divacky // variable/function. 297739d628a0SDimitry Andric if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 29783b0f4066SDimitry Andric D->isWeakImported()) { 2979f22ef01cSRoman Divacky GA->setLinkage(llvm::Function::WeakAnyLinkage); 2980f22ef01cSRoman Divacky } 2981f22ef01cSRoman Divacky 298239d628a0SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 298339d628a0SDimitry Andric if (VD->getTLSKind()) 298439d628a0SDimitry Andric setTLSMode(GA, *VD); 298539d628a0SDimitry Andric 298639d628a0SDimitry Andric setAliasAttributes(D, GA); 2987f22ef01cSRoman Divacky } 2988f22ef01cSRoman Divacky 2989e7145dcbSDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 2990e7145dcbSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 2991e7145dcbSDimitry Andric const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 2992e7145dcbSDimitry Andric assert(IFA && "Not an ifunc?"); 2993e7145dcbSDimitry Andric 2994e7145dcbSDimitry Andric StringRef MangledName = getMangledName(GD); 2995e7145dcbSDimitry Andric 2996e7145dcbSDimitry Andric if (IFA->getResolver() == MangledName) { 2997e7145dcbSDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 2998e7145dcbSDimitry Andric return; 2999e7145dcbSDimitry Andric } 3000e7145dcbSDimitry Andric 3001e7145dcbSDimitry Andric // Report an error if some definition overrides ifunc. 3002e7145dcbSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3003e7145dcbSDimitry Andric if (Entry && !Entry->isDeclaration()) { 3004e7145dcbSDimitry Andric GlobalDecl OtherGD; 3005e7145dcbSDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 3006e7145dcbSDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 3007e7145dcbSDimitry Andric Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name); 3008e7145dcbSDimitry Andric Diags.Report(OtherGD.getDecl()->getLocation(), 3009e7145dcbSDimitry Andric diag::note_previous_definition); 3010e7145dcbSDimitry Andric } 3011e7145dcbSDimitry Andric return; 3012e7145dcbSDimitry Andric } 3013e7145dcbSDimitry Andric 3014e7145dcbSDimitry Andric Aliases.push_back(GD); 3015e7145dcbSDimitry Andric 3016e7145dcbSDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 3017e7145dcbSDimitry Andric llvm::Constant *Resolver = 3018e7145dcbSDimitry Andric GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD, 3019e7145dcbSDimitry Andric /*ForVTable=*/false); 3020e7145dcbSDimitry Andric llvm::GlobalIFunc *GIF = 3021e7145dcbSDimitry Andric llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 3022e7145dcbSDimitry Andric "", Resolver, &getModule()); 3023e7145dcbSDimitry Andric if (Entry) { 3024e7145dcbSDimitry Andric if (GIF->getResolver() == Entry) { 3025e7145dcbSDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 3026e7145dcbSDimitry Andric return; 3027e7145dcbSDimitry Andric } 3028e7145dcbSDimitry Andric assert(Entry->isDeclaration()); 3029e7145dcbSDimitry Andric 3030e7145dcbSDimitry Andric // If there is a declaration in the module, then we had an extern followed 3031e7145dcbSDimitry Andric // by the ifunc, as in: 3032e7145dcbSDimitry Andric // extern int test(); 3033e7145dcbSDimitry Andric // ... 3034e7145dcbSDimitry Andric // int test() __attribute__((ifunc("resolver"))); 3035e7145dcbSDimitry Andric // 3036e7145dcbSDimitry Andric // Remove it and replace uses of it with the ifunc. 3037e7145dcbSDimitry Andric GIF->takeName(Entry); 3038e7145dcbSDimitry Andric 3039e7145dcbSDimitry Andric Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 3040e7145dcbSDimitry Andric Entry->getType())); 3041e7145dcbSDimitry Andric Entry->eraseFromParent(); 3042e7145dcbSDimitry Andric } else 3043e7145dcbSDimitry Andric GIF->setName(MangledName); 3044e7145dcbSDimitry Andric 3045e7145dcbSDimitry Andric SetCommonAttributes(D, GIF); 3046e7145dcbSDimitry Andric } 3047e7145dcbSDimitry Andric 304817a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 30496122f3e6SDimitry Andric ArrayRef<llvm::Type*> Tys) { 305017a519f9SDimitry Andric return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 305117a519f9SDimitry Andric Tys); 3052f22ef01cSRoman Divacky } 3053f22ef01cSRoman Divacky 305433956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 305533956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 305633956c43SDimitry Andric const StringLiteral *Literal, bool TargetIsLSB, 305733956c43SDimitry Andric bool &IsUTF16, unsigned &StringLength) { 30586122f3e6SDimitry Andric StringRef String = Literal->getString(); 3059e580952dSDimitry Andric unsigned NumBytes = String.size(); 3060f22ef01cSRoman Divacky 3061f22ef01cSRoman Divacky // Check for simple case. 3062f22ef01cSRoman Divacky if (!Literal->containsNonAsciiOrNull()) { 3063f22ef01cSRoman Divacky StringLength = NumBytes; 306439d628a0SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 3065f22ef01cSRoman Divacky } 3066f22ef01cSRoman Divacky 3067dff0c46cSDimitry Andric // Otherwise, convert the UTF8 literals into a string of shorts. 3068dff0c46cSDimitry Andric IsUTF16 = true; 3069dff0c46cSDimitry Andric 3070dff0c46cSDimitry Andric SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 30713861d79fSDimitry Andric const UTF8 *FromPtr = (const UTF8 *)String.data(); 3072f22ef01cSRoman Divacky UTF16 *ToPtr = &ToBuf[0]; 3073f22ef01cSRoman Divacky 30742754fe60SDimitry Andric (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 3075f22ef01cSRoman Divacky &ToPtr, ToPtr + NumBytes, 3076f22ef01cSRoman Divacky strictConversion); 3077f22ef01cSRoman Divacky 3078f22ef01cSRoman Divacky // ConvertUTF8toUTF16 returns the length in ToPtr. 3079f22ef01cSRoman Divacky StringLength = ToPtr - &ToBuf[0]; 3080f22ef01cSRoman Divacky 3081dff0c46cSDimitry Andric // Add an explicit null. 3082dff0c46cSDimitry Andric *ToPtr = 0; 308339d628a0SDimitry Andric return *Map.insert(std::make_pair( 308439d628a0SDimitry Andric StringRef(reinterpret_cast<const char *>(ToBuf.data()), 308539d628a0SDimitry Andric (StringLength + 1) * 2), 308639d628a0SDimitry Andric nullptr)).first; 3087f22ef01cSRoman Divacky } 3088f22ef01cSRoman Divacky 308933956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 309033956c43SDimitry Andric GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 309133956c43SDimitry Andric const StringLiteral *Literal, unsigned &StringLength) { 30926122f3e6SDimitry Andric StringRef String = Literal->getString(); 3093bd5abe19SDimitry Andric StringLength = String.size(); 309439d628a0SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 3095bd5abe19SDimitry Andric } 3096bd5abe19SDimitry Andric 30970623d748SDimitry Andric ConstantAddress 3098f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 3099f22ef01cSRoman Divacky unsigned StringLength = 0; 3100f22ef01cSRoman Divacky bool isUTF16 = false; 310133956c43SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 3102f22ef01cSRoman Divacky GetConstantCFStringEntry(CFConstantStringMap, Literal, 310333956c43SDimitry Andric getDataLayout().isLittleEndian(), isUTF16, 310433956c43SDimitry Andric StringLength); 3105f22ef01cSRoman Divacky 310639d628a0SDimitry Andric if (auto *C = Entry.second) 31070623d748SDimitry Andric return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 3108f22ef01cSRoman Divacky 3109dff0c46cSDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 3110f22ef01cSRoman Divacky llvm::Constant *Zeros[] = { Zero, Zero }; 3111284c1978SDimitry Andric llvm::Value *V; 3112f22ef01cSRoman Divacky 3113f22ef01cSRoman Divacky // If we don't already have it, get __CFConstantStringClassReference. 3114f22ef01cSRoman Divacky if (!CFConstantStringClassRef) { 31156122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 3116f22ef01cSRoman Divacky Ty = llvm::ArrayType::get(Ty, 0); 3117e7145dcbSDimitry Andric llvm::Constant *GV = 3118e7145dcbSDimitry Andric CreateRuntimeVariable(Ty, "__CFConstantStringClassReference"); 3119e7145dcbSDimitry Andric 3120e7145dcbSDimitry Andric if (getTarget().getTriple().isOSBinFormatCOFF()) { 3121e7145dcbSDimitry Andric IdentifierInfo &II = getContext().Idents.get(GV->getName()); 3122e7145dcbSDimitry Andric TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl(); 3123e7145dcbSDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 3124e7145dcbSDimitry Andric llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV); 3125e7145dcbSDimitry Andric 3126e7145dcbSDimitry Andric const VarDecl *VD = nullptr; 3127e7145dcbSDimitry Andric for (const auto &Result : DC->lookup(&II)) 3128e7145dcbSDimitry Andric if ((VD = dyn_cast<VarDecl>(Result))) 3129e7145dcbSDimitry Andric break; 3130e7145dcbSDimitry Andric 3131e7145dcbSDimitry Andric if (!VD || !VD->hasAttr<DLLExportAttr>()) { 3132e7145dcbSDimitry Andric CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3133e7145dcbSDimitry Andric CGV->setLinkage(llvm::GlobalValue::ExternalLinkage); 3134e7145dcbSDimitry Andric } else { 3135e7145dcbSDimitry Andric CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 3136e7145dcbSDimitry Andric CGV->setLinkage(llvm::GlobalValue::ExternalLinkage); 3137e7145dcbSDimitry Andric } 3138e7145dcbSDimitry Andric } 3139e7145dcbSDimitry Andric 3140f22ef01cSRoman Divacky // Decay array -> ptr 314133956c43SDimitry Andric V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros); 3142284c1978SDimitry Andric CFConstantStringClassRef = V; 3143e7145dcbSDimitry Andric } else { 3144284c1978SDimitry Andric V = CFConstantStringClassRef; 3145e7145dcbSDimitry Andric } 3146f22ef01cSRoman Divacky 3147f22ef01cSRoman Divacky QualType CFTy = getContext().getCFConstantStringType(); 3148f22ef01cSRoman Divacky 314959d1ed5bSDimitry Andric auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 3150f22ef01cSRoman Divacky 3151dff0c46cSDimitry Andric llvm::Constant *Fields[4]; 3152f22ef01cSRoman Divacky 3153f22ef01cSRoman Divacky // Class pointer. 3154284c1978SDimitry Andric Fields[0] = cast<llvm::ConstantExpr>(V); 3155f22ef01cSRoman Divacky 3156f22ef01cSRoman Divacky // Flags. 31576122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 3158e7145dcbSDimitry Andric Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) 3159e7145dcbSDimitry Andric : llvm::ConstantInt::get(Ty, 0x07C8); 3160f22ef01cSRoman Divacky 3161f22ef01cSRoman Divacky // String pointer. 316259d1ed5bSDimitry Andric llvm::Constant *C = nullptr; 3163dff0c46cSDimitry Andric if (isUTF16) { 31640623d748SDimitry Andric auto Arr = llvm::makeArrayRef( 316539d628a0SDimitry Andric reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 316639d628a0SDimitry Andric Entry.first().size() / 2); 3167dff0c46cSDimitry Andric C = llvm::ConstantDataArray::get(VMContext, Arr); 3168dff0c46cSDimitry Andric } else { 316939d628a0SDimitry Andric C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 3170dff0c46cSDimitry Andric } 3171f22ef01cSRoman Divacky 3172dff0c46cSDimitry Andric // Note: -fwritable-strings doesn't make the backing store strings of 3173dff0c46cSDimitry Andric // CFStrings writable. (See <rdar://problem/10657500>) 317459d1ed5bSDimitry Andric auto *GV = 3175dff0c46cSDimitry Andric new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 317659d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, C, ".str"); 3177e7145dcbSDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3178284c1978SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 3179284c1978SDimitry Andric // of the string is via this class initializer. 3180e7145dcbSDimitry Andric CharUnits Align = isUTF16 3181e7145dcbSDimitry Andric ? getContext().getTypeAlignInChars(getContext().ShortTy) 3182e7145dcbSDimitry Andric : getContext().getTypeAlignInChars(getContext().CharTy); 3183f22ef01cSRoman Divacky GV->setAlignment(Align.getQuantity()); 3184e7145dcbSDimitry Andric 3185e7145dcbSDimitry Andric // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 3186e7145dcbSDimitry Andric // Without it LLVM can merge the string with a non unnamed_addr one during 3187e7145dcbSDimitry Andric // LTO. Doing that changes the section it ends in, which surprises ld64. 3188e7145dcbSDimitry Andric if (getTarget().getTriple().isOSBinFormatMachO()) 3189e7145dcbSDimitry Andric GV->setSection(isUTF16 ? "__TEXT,__ustring" 3190e7145dcbSDimitry Andric : "__TEXT,__cstring,cstring_literals"); 3191dff0c46cSDimitry Andric 3192dff0c46cSDimitry Andric // String. 319333956c43SDimitry Andric Fields[2] = 319433956c43SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 3195f22ef01cSRoman Divacky 3196dff0c46cSDimitry Andric if (isUTF16) 3197dff0c46cSDimitry Andric // Cast the UTF16 string to the correct type. 3198dff0c46cSDimitry Andric Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 3199dff0c46cSDimitry Andric 3200f22ef01cSRoman Divacky // String length. 3201f22ef01cSRoman Divacky Ty = getTypes().ConvertType(getContext().LongTy); 3202f22ef01cSRoman Divacky Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 3203f22ef01cSRoman Divacky 32040623d748SDimitry Andric CharUnits Alignment = getPointerAlign(); 32050623d748SDimitry Andric 3206f22ef01cSRoman Divacky // The struct. 3207f22ef01cSRoman Divacky C = llvm::ConstantStruct::get(STy, Fields); 3208f22ef01cSRoman Divacky GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 3209f22ef01cSRoman Divacky llvm::GlobalVariable::PrivateLinkage, C, 3210f22ef01cSRoman Divacky "_unnamed_cfstring_"); 32110623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 3212e7145dcbSDimitry Andric switch (getTarget().getTriple().getObjectFormat()) { 3213e7145dcbSDimitry Andric case llvm::Triple::UnknownObjectFormat: 3214e7145dcbSDimitry Andric llvm_unreachable("unknown file format"); 3215e7145dcbSDimitry Andric case llvm::Triple::COFF: 3216e7145dcbSDimitry Andric case llvm::Triple::ELF: 3217e7145dcbSDimitry Andric GV->setSection("cfstring"); 3218e7145dcbSDimitry Andric break; 3219e7145dcbSDimitry Andric case llvm::Triple::MachO: 3220e7145dcbSDimitry Andric GV->setSection("__DATA,__cfstring"); 3221e7145dcbSDimitry Andric break; 3222e7145dcbSDimitry Andric } 322339d628a0SDimitry Andric Entry.second = GV; 3224f22ef01cSRoman Divacky 32250623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3226f22ef01cSRoman Divacky } 3227f22ef01cSRoman Divacky 32280623d748SDimitry Andric ConstantAddress 32292754fe60SDimitry Andric CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 3230f22ef01cSRoman Divacky unsigned StringLength = 0; 323133956c43SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 3232bd5abe19SDimitry Andric GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 3233f22ef01cSRoman Divacky 323439d628a0SDimitry Andric if (auto *C = Entry.second) 32350623d748SDimitry Andric return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 3236f22ef01cSRoman Divacky 3237dff0c46cSDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 3238f22ef01cSRoman Divacky llvm::Constant *Zeros[] = { Zero, Zero }; 3239284c1978SDimitry Andric llvm::Value *V; 3240f22ef01cSRoman Divacky // If we don't already have it, get _NSConstantStringClassReference. 32412754fe60SDimitry Andric if (!ConstantStringClassRef) { 3242dff0c46cSDimitry Andric std::string StringClass(getLangOpts().ObjCConstantStringClass); 32436122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 32442754fe60SDimitry Andric llvm::Constant *GV; 32457ae0e2c9SDimitry Andric if (LangOpts.ObjCRuntime.isNonFragile()) { 3246bd5abe19SDimitry Andric std::string str = 3247bd5abe19SDimitry Andric StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 3248bd5abe19SDimitry Andric : "OBJC_CLASS_$_" + StringClass; 3249bd5abe19SDimitry Andric GV = getObjCRuntime().GetClassGlobal(str); 3250bd5abe19SDimitry Andric // Make sure the result is of the correct type. 32516122f3e6SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 3252284c1978SDimitry Andric V = llvm::ConstantExpr::getBitCast(GV, PTy); 3253284c1978SDimitry Andric ConstantStringClassRef = V; 3254bd5abe19SDimitry Andric } else { 3255bd5abe19SDimitry Andric std::string str = 3256bd5abe19SDimitry Andric StringClass.empty() ? "_NSConstantStringClassReference" 3257bd5abe19SDimitry Andric : "_" + StringClass + "ClassReference"; 32586122f3e6SDimitry Andric llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 3259bd5abe19SDimitry Andric GV = CreateRuntimeVariable(PTy, str); 3260f22ef01cSRoman Divacky // Decay array -> ptr 326133956c43SDimitry Andric V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros); 3262284c1978SDimitry Andric ConstantStringClassRef = V; 3263f22ef01cSRoman Divacky } 326433956c43SDimitry Andric } else 3265284c1978SDimitry Andric V = ConstantStringClassRef; 3266f22ef01cSRoman Divacky 32676122f3e6SDimitry Andric if (!NSConstantStringType) { 32686122f3e6SDimitry Andric // Construct the type for a constant NSString. 326959d1ed5bSDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString"); 32706122f3e6SDimitry Andric D->startDefinition(); 3271f22ef01cSRoman Divacky 32726122f3e6SDimitry Andric QualType FieldTypes[3]; 32736122f3e6SDimitry Andric 32746122f3e6SDimitry Andric // const int *isa; 32756122f3e6SDimitry Andric FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 32766122f3e6SDimitry Andric // const char *str; 32776122f3e6SDimitry Andric FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 32786122f3e6SDimitry Andric // unsigned int length; 32796122f3e6SDimitry Andric FieldTypes[2] = Context.UnsignedIntTy; 32806122f3e6SDimitry Andric 32816122f3e6SDimitry Andric // Create fields 32826122f3e6SDimitry Andric for (unsigned i = 0; i < 3; ++i) { 32836122f3e6SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, D, 32846122f3e6SDimitry Andric SourceLocation(), 328559d1ed5bSDimitry Andric SourceLocation(), nullptr, 328659d1ed5bSDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 328759d1ed5bSDimitry Andric /*BitWidth=*/nullptr, 32886122f3e6SDimitry Andric /*Mutable=*/false, 32897ae0e2c9SDimitry Andric ICIS_NoInit); 32906122f3e6SDimitry Andric Field->setAccess(AS_public); 32916122f3e6SDimitry Andric D->addDecl(Field); 32926122f3e6SDimitry Andric } 32936122f3e6SDimitry Andric 32946122f3e6SDimitry Andric D->completeDefinition(); 32956122f3e6SDimitry Andric QualType NSTy = Context.getTagDeclType(D); 32966122f3e6SDimitry Andric NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 32976122f3e6SDimitry Andric } 3298f22ef01cSRoman Divacky 3299dff0c46cSDimitry Andric llvm::Constant *Fields[3]; 3300f22ef01cSRoman Divacky 3301f22ef01cSRoman Divacky // Class pointer. 3302284c1978SDimitry Andric Fields[0] = cast<llvm::ConstantExpr>(V); 3303f22ef01cSRoman Divacky 3304f22ef01cSRoman Divacky // String pointer. 3305dff0c46cSDimitry Andric llvm::Constant *C = 330639d628a0SDimitry Andric llvm::ConstantDataArray::getString(VMContext, Entry.first()); 3307f22ef01cSRoman Divacky 3308f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes Linkage; 3309f22ef01cSRoman Divacky bool isConstant; 3310f22ef01cSRoman Divacky Linkage = llvm::GlobalValue::PrivateLinkage; 3311dff0c46cSDimitry Andric isConstant = !LangOpts.WritableStrings; 3312f22ef01cSRoman Divacky 331359d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant, 331459d1ed5bSDimitry Andric Linkage, C, ".str"); 3315e7145dcbSDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3316284c1978SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 3317284c1978SDimitry Andric // of the string is via this class initializer. 33183b0f4066SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 33193b0f4066SDimitry Andric GV->setAlignment(Align.getQuantity()); 332033956c43SDimitry Andric Fields[1] = 332133956c43SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 3322f22ef01cSRoman Divacky 3323f22ef01cSRoman Divacky // String length. 33246122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 3325f22ef01cSRoman Divacky Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 3326f22ef01cSRoman Divacky 3327f22ef01cSRoman Divacky // The struct. 33280623d748SDimitry Andric CharUnits Alignment = getPointerAlign(); 33296122f3e6SDimitry Andric C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 3330f22ef01cSRoman Divacky GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 3331f22ef01cSRoman Divacky llvm::GlobalVariable::PrivateLinkage, C, 3332f22ef01cSRoman Divacky "_unnamed_nsstring_"); 33330623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 333459d1ed5bSDimitry Andric const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip"; 333559d1ed5bSDimitry Andric const char *NSStringNonFragileABISection = 333659d1ed5bSDimitry Andric "__DATA,__objc_stringobj,regular,no_dead_strip"; 3337f22ef01cSRoman Divacky // FIXME. Fix section. 333859d1ed5bSDimitry Andric GV->setSection(LangOpts.ObjCRuntime.isNonFragile() 333959d1ed5bSDimitry Andric ? NSStringNonFragileABISection 334059d1ed5bSDimitry Andric : NSStringSection); 334139d628a0SDimitry Andric Entry.second = GV; 3342f22ef01cSRoman Divacky 33430623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3344f22ef01cSRoman Divacky } 3345f22ef01cSRoman Divacky 33466122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() { 33476122f3e6SDimitry Andric if (ObjCFastEnumerationStateType.isNull()) { 334859d1ed5bSDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 33496122f3e6SDimitry Andric D->startDefinition(); 33506122f3e6SDimitry Andric 33516122f3e6SDimitry Andric QualType FieldTypes[] = { 33526122f3e6SDimitry Andric Context.UnsignedLongTy, 33536122f3e6SDimitry Andric Context.getPointerType(Context.getObjCIdType()), 33546122f3e6SDimitry Andric Context.getPointerType(Context.UnsignedLongTy), 33556122f3e6SDimitry Andric Context.getConstantArrayType(Context.UnsignedLongTy, 33566122f3e6SDimitry Andric llvm::APInt(32, 5), ArrayType::Normal, 0) 33576122f3e6SDimitry Andric }; 33586122f3e6SDimitry Andric 33596122f3e6SDimitry Andric for (size_t i = 0; i < 4; ++i) { 33606122f3e6SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, 33616122f3e6SDimitry Andric D, 33626122f3e6SDimitry Andric SourceLocation(), 336359d1ed5bSDimitry Andric SourceLocation(), nullptr, 336459d1ed5bSDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 336559d1ed5bSDimitry Andric /*BitWidth=*/nullptr, 33666122f3e6SDimitry Andric /*Mutable=*/false, 33677ae0e2c9SDimitry Andric ICIS_NoInit); 33686122f3e6SDimitry Andric Field->setAccess(AS_public); 33696122f3e6SDimitry Andric D->addDecl(Field); 33706122f3e6SDimitry Andric } 33716122f3e6SDimitry Andric 33726122f3e6SDimitry Andric D->completeDefinition(); 33736122f3e6SDimitry Andric ObjCFastEnumerationStateType = Context.getTagDeclType(D); 33746122f3e6SDimitry Andric } 33756122f3e6SDimitry Andric 33766122f3e6SDimitry Andric return ObjCFastEnumerationStateType; 33776122f3e6SDimitry Andric } 33786122f3e6SDimitry Andric 3379dff0c46cSDimitry Andric llvm::Constant * 3380dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 3381dff0c46cSDimitry Andric assert(!E->getType()->isPointerType() && "Strings are always arrays"); 3382f22ef01cSRoman Divacky 3383dff0c46cSDimitry Andric // Don't emit it as the address of the string, emit the string data itself 3384dff0c46cSDimitry Andric // as an inline array. 3385dff0c46cSDimitry Andric if (E->getCharByteWidth() == 1) { 3386dff0c46cSDimitry Andric SmallString<64> Str(E->getString()); 3387f22ef01cSRoman Divacky 3388dff0c46cSDimitry Andric // Resize the string to the right size, which is indicated by its type. 3389dff0c46cSDimitry Andric const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 3390dff0c46cSDimitry Andric Str.resize(CAT->getSize().getZExtValue()); 3391dff0c46cSDimitry Andric return llvm::ConstantDataArray::getString(VMContext, Str, false); 33926122f3e6SDimitry Andric } 3393f22ef01cSRoman Divacky 339459d1ed5bSDimitry Andric auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 3395dff0c46cSDimitry Andric llvm::Type *ElemTy = AType->getElementType(); 3396dff0c46cSDimitry Andric unsigned NumElements = AType->getNumElements(); 3397f22ef01cSRoman Divacky 3398dff0c46cSDimitry Andric // Wide strings have either 2-byte or 4-byte elements. 3399dff0c46cSDimitry Andric if (ElemTy->getPrimitiveSizeInBits() == 16) { 3400dff0c46cSDimitry Andric SmallVector<uint16_t, 32> Elements; 3401dff0c46cSDimitry Andric Elements.reserve(NumElements); 3402dff0c46cSDimitry Andric 3403dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3404dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 3405dff0c46cSDimitry Andric Elements.resize(NumElements); 3406dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 3407dff0c46cSDimitry Andric } 3408dff0c46cSDimitry Andric 3409dff0c46cSDimitry Andric assert(ElemTy->getPrimitiveSizeInBits() == 32); 3410dff0c46cSDimitry Andric SmallVector<uint32_t, 32> Elements; 3411dff0c46cSDimitry Andric Elements.reserve(NumElements); 3412dff0c46cSDimitry Andric 3413dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3414dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 3415dff0c46cSDimitry Andric Elements.resize(NumElements); 3416dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 3417f22ef01cSRoman Divacky } 3418f22ef01cSRoman Divacky 341959d1ed5bSDimitry Andric static llvm::GlobalVariable * 342059d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 342159d1ed5bSDimitry Andric CodeGenModule &CGM, StringRef GlobalName, 34220623d748SDimitry Andric CharUnits Alignment) { 342359d1ed5bSDimitry Andric // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 342459d1ed5bSDimitry Andric unsigned AddrSpace = 0; 342559d1ed5bSDimitry Andric if (CGM.getLangOpts().OpenCL) 342659d1ed5bSDimitry Andric AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 3427dff0c46cSDimitry Andric 342833956c43SDimitry Andric llvm::Module &M = CGM.getModule(); 342959d1ed5bSDimitry Andric // Create a global variable for this string 343059d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 343133956c43SDimitry Andric M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 343233956c43SDimitry Andric nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 34330623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 3434e7145dcbSDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 343533956c43SDimitry Andric if (GV->isWeakForLinker()) { 343633956c43SDimitry Andric assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 343733956c43SDimitry Andric GV->setComdat(M.getOrInsertComdat(GV->getName())); 343833956c43SDimitry Andric } 343933956c43SDimitry Andric 344059d1ed5bSDimitry Andric return GV; 3441f22ef01cSRoman Divacky } 3442dff0c46cSDimitry Andric 344359d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 344459d1ed5bSDimitry Andric /// constant array for the given string literal. 34450623d748SDimitry Andric ConstantAddress 344639d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 344739d628a0SDimitry Andric StringRef Name) { 34480623d748SDimitry Andric CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 3449dff0c46cSDimitry Andric 345059d1ed5bSDimitry Andric llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 345159d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 345259d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 345359d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 345459d1ed5bSDimitry Andric if (auto GV = *Entry) { 34550623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 34560623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 34570623d748SDimitry Andric return ConstantAddress(GV, Alignment); 345859d1ed5bSDimitry Andric } 345959d1ed5bSDimitry Andric } 346059d1ed5bSDimitry Andric 346159d1ed5bSDimitry Andric SmallString<256> MangledNameBuffer; 346259d1ed5bSDimitry Andric StringRef GlobalVariableName; 346359d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes LT; 346459d1ed5bSDimitry Andric 346559d1ed5bSDimitry Andric // Mangle the string literal if the ABI allows for it. However, we cannot 346659d1ed5bSDimitry Andric // do this if we are compiling with ASan or -fwritable-strings because they 346759d1ed5bSDimitry Andric // rely on strings having normal linkage. 346839d628a0SDimitry Andric if (!LangOpts.WritableStrings && 346939d628a0SDimitry Andric !LangOpts.Sanitize.has(SanitizerKind::Address) && 347059d1ed5bSDimitry Andric getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { 347159d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(MangledNameBuffer); 347259d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 347359d1ed5bSDimitry Andric 347459d1ed5bSDimitry Andric LT = llvm::GlobalValue::LinkOnceODRLinkage; 347559d1ed5bSDimitry Andric GlobalVariableName = MangledNameBuffer; 347659d1ed5bSDimitry Andric } else { 347759d1ed5bSDimitry Andric LT = llvm::GlobalValue::PrivateLinkage; 347839d628a0SDimitry Andric GlobalVariableName = Name; 347959d1ed5bSDimitry Andric } 348059d1ed5bSDimitry Andric 348159d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 348259d1ed5bSDimitry Andric if (Entry) 348359d1ed5bSDimitry Andric *Entry = GV; 348459d1ed5bSDimitry Andric 348539d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 348639d628a0SDimitry Andric QualType()); 34870623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3488f22ef01cSRoman Divacky } 3489f22ef01cSRoman Divacky 3490f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 3491f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node. 34920623d748SDimitry Andric ConstantAddress 3493f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 3494f22ef01cSRoman Divacky std::string Str; 3495f22ef01cSRoman Divacky getContext().getObjCEncodingForType(E->getEncodedType(), Str); 3496f22ef01cSRoman Divacky 3497f22ef01cSRoman Divacky return GetAddrOfConstantCString(Str); 3498f22ef01cSRoman Divacky } 3499f22ef01cSRoman Divacky 350059d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing 350159d1ed5bSDimitry Andric /// the literal and a terminating '\0' character. 350259d1ed5bSDimitry Andric /// The result has pointer to array type. 35030623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString( 35040623d748SDimitry Andric const std::string &Str, const char *GlobalName) { 350559d1ed5bSDimitry Andric StringRef StrWithNull(Str.c_str(), Str.size() + 1); 35060623d748SDimitry Andric CharUnits Alignment = 35070623d748SDimitry Andric getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 3508f22ef01cSRoman Divacky 350959d1ed5bSDimitry Andric llvm::Constant *C = 351059d1ed5bSDimitry Andric llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 351159d1ed5bSDimitry Andric 351259d1ed5bSDimitry Andric // Don't share any string literals if strings aren't constant. 351359d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 351459d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 351559d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 351659d1ed5bSDimitry Andric if (auto GV = *Entry) { 35170623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 35180623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 35190623d748SDimitry Andric return ConstantAddress(GV, Alignment); 352059d1ed5bSDimitry Andric } 352159d1ed5bSDimitry Andric } 352259d1ed5bSDimitry Andric 3523f22ef01cSRoman Divacky // Get the default prefix if a name wasn't specified. 3524f22ef01cSRoman Divacky if (!GlobalName) 3525f22ef01cSRoman Divacky GlobalName = ".str"; 3526f22ef01cSRoman Divacky // Create a global variable for this. 352759d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 352859d1ed5bSDimitry Andric GlobalName, Alignment); 352959d1ed5bSDimitry Andric if (Entry) 353059d1ed5bSDimitry Andric *Entry = GV; 35310623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3532f22ef01cSRoman Divacky } 3533f22ef01cSRoman Divacky 35340623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 3535f785676fSDimitry Andric const MaterializeTemporaryExpr *E, const Expr *Init) { 3536f785676fSDimitry Andric assert((E->getStorageDuration() == SD_Static || 3537f785676fSDimitry Andric E->getStorageDuration() == SD_Thread) && "not a global temporary"); 353859d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 3539f785676fSDimitry Andric 3540f785676fSDimitry Andric // If we're not materializing a subobject of the temporary, keep the 3541f785676fSDimitry Andric // cv-qualifiers from the type of the MaterializeTemporaryExpr. 3542f785676fSDimitry Andric QualType MaterializedType = Init->getType(); 3543f785676fSDimitry Andric if (Init == E->GetTemporaryExpr()) 3544f785676fSDimitry Andric MaterializedType = E->getType(); 3545f785676fSDimitry Andric 35460623d748SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 35470623d748SDimitry Andric 35480623d748SDimitry Andric if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E]) 35490623d748SDimitry Andric return ConstantAddress(Slot, Align); 3550f785676fSDimitry Andric 3551f785676fSDimitry Andric // FIXME: If an externally-visible declaration extends multiple temporaries, 3552f785676fSDimitry Andric // we need to give each temporary the same name in every translation unit (and 3553f785676fSDimitry Andric // we also need to make the temporaries externally-visible). 3554f785676fSDimitry Andric SmallString<256> Name; 3555f785676fSDimitry Andric llvm::raw_svector_ostream Out(Name); 355659d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleReferenceTemporary( 355759d1ed5bSDimitry Andric VD, E->getManglingNumber(), Out); 3558f785676fSDimitry Andric 355959d1ed5bSDimitry Andric APValue *Value = nullptr; 3560f785676fSDimitry Andric if (E->getStorageDuration() == SD_Static) { 3561f785676fSDimitry Andric // We might have a cached constant initializer for this temporary. Note 3562f785676fSDimitry Andric // that this might have a different value from the value computed by 3563f785676fSDimitry Andric // evaluating the initializer if the surrounding constant expression 3564f785676fSDimitry Andric // modifies the temporary. 3565f785676fSDimitry Andric Value = getContext().getMaterializedTemporaryValue(E, false); 3566f785676fSDimitry Andric if (Value && Value->isUninit()) 356759d1ed5bSDimitry Andric Value = nullptr; 3568f785676fSDimitry Andric } 3569f785676fSDimitry Andric 3570f785676fSDimitry Andric // Try evaluating it now, it might have a constant initializer. 3571f785676fSDimitry Andric Expr::EvalResult EvalResult; 3572f785676fSDimitry Andric if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 3573f785676fSDimitry Andric !EvalResult.hasSideEffects()) 3574f785676fSDimitry Andric Value = &EvalResult.Val; 3575f785676fSDimitry Andric 357659d1ed5bSDimitry Andric llvm::Constant *InitialValue = nullptr; 3577f785676fSDimitry Andric bool Constant = false; 3578f785676fSDimitry Andric llvm::Type *Type; 3579f785676fSDimitry Andric if (Value) { 3580f785676fSDimitry Andric // The temporary has a constant initializer, use it. 358159d1ed5bSDimitry Andric InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr); 3582f785676fSDimitry Andric Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 3583f785676fSDimitry Andric Type = InitialValue->getType(); 3584f785676fSDimitry Andric } else { 3585f785676fSDimitry Andric // No initializer, the initialization will be provided when we 3586f785676fSDimitry Andric // initialize the declaration which performed lifetime extension. 3587f785676fSDimitry Andric Type = getTypes().ConvertTypeForMem(MaterializedType); 3588f785676fSDimitry Andric } 3589f785676fSDimitry Andric 3590f785676fSDimitry Andric // Create a global variable for this lifetime-extended temporary. 359159d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 359259d1ed5bSDimitry Andric getLLVMLinkageVarDefinition(VD, Constant); 359333956c43SDimitry Andric if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 359433956c43SDimitry Andric const VarDecl *InitVD; 359533956c43SDimitry Andric if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 359633956c43SDimitry Andric isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 359733956c43SDimitry Andric // Temporaries defined inside a class get linkonce_odr linkage because the 359833956c43SDimitry Andric // class can be defined in multipe translation units. 359933956c43SDimitry Andric Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 360033956c43SDimitry Andric } else { 360133956c43SDimitry Andric // There is no need for this temporary to have external linkage if the 360233956c43SDimitry Andric // VarDecl has external linkage. 360333956c43SDimitry Andric Linkage = llvm::GlobalVariable::InternalLinkage; 360433956c43SDimitry Andric } 360533956c43SDimitry Andric } 360659d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace( 360759d1ed5bSDimitry Andric VD, getContext().getTargetAddressSpace(MaterializedType)); 360859d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 360959d1ed5bSDimitry Andric getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 361059d1ed5bSDimitry Andric /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, 361159d1ed5bSDimitry Andric AddrSpace); 361259d1ed5bSDimitry Andric setGlobalVisibility(GV, VD); 36130623d748SDimitry Andric GV->setAlignment(Align.getQuantity()); 361433956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker()) 361533956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3616f785676fSDimitry Andric if (VD->getTLSKind()) 3617f785676fSDimitry Andric setTLSMode(GV, *VD); 36180623d748SDimitry Andric MaterializedGlobalTemporaryMap[E] = GV; 36190623d748SDimitry Andric return ConstantAddress(GV, Align); 3620f785676fSDimitry Andric } 3621f785676fSDimitry Andric 3622f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized 3623f22ef01cSRoman Divacky /// properties for an implementation. 3624f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const 3625f22ef01cSRoman Divacky ObjCImplementationDecl *D) { 362659d1ed5bSDimitry Andric for (const auto *PID : D->property_impls()) { 3627f22ef01cSRoman Divacky // Dynamic is just for type-checking. 3628f22ef01cSRoman Divacky if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 3629f22ef01cSRoman Divacky ObjCPropertyDecl *PD = PID->getPropertyDecl(); 3630f22ef01cSRoman Divacky 3631f22ef01cSRoman Divacky // Determine which methods need to be implemented, some may have 36323861d79fSDimitry Andric // been overridden. Note that ::isPropertyAccessor is not the method 3633f22ef01cSRoman Divacky // we want, that just indicates if the decl came from a 3634f22ef01cSRoman Divacky // property. What we want to know is if the method is defined in 3635f22ef01cSRoman Divacky // this implementation. 3636f22ef01cSRoman Divacky if (!D->getInstanceMethod(PD->getGetterName())) 3637f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCGetter( 3638f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3639f22ef01cSRoman Divacky if (!PD->isReadOnly() && 3640f22ef01cSRoman Divacky !D->getInstanceMethod(PD->getSetterName())) 3641f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCSetter( 3642f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3643f22ef01cSRoman Divacky } 3644f22ef01cSRoman Divacky } 3645f22ef01cSRoman Divacky } 3646f22ef01cSRoman Divacky 36473b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) { 36486122f3e6SDimitry Andric const ObjCInterfaceDecl *iface = impl->getClassInterface(); 36496122f3e6SDimitry Andric for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 36503b0f4066SDimitry Andric ivar; ivar = ivar->getNextIvar()) 36513b0f4066SDimitry Andric if (ivar->getType().isDestructedType()) 36523b0f4066SDimitry Andric return true; 36533b0f4066SDimitry Andric 36543b0f4066SDimitry Andric return false; 36553b0f4066SDimitry Andric } 36563b0f4066SDimitry Andric 365739d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM, 365839d628a0SDimitry Andric ObjCImplementationDecl *D) { 365939d628a0SDimitry Andric CodeGenFunction CGF(CGM); 366039d628a0SDimitry Andric for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 366139d628a0SDimitry Andric E = D->init_end(); B != E; ++B) { 366239d628a0SDimitry Andric CXXCtorInitializer *CtorInitExp = *B; 366339d628a0SDimitry Andric Expr *Init = CtorInitExp->getInit(); 366439d628a0SDimitry Andric if (!CGF.isTrivialInitializer(Init)) 366539d628a0SDimitry Andric return false; 366639d628a0SDimitry Andric } 366739d628a0SDimitry Andric return true; 366839d628a0SDimitry Andric } 366939d628a0SDimitry Andric 3670f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization 3671f22ef01cSRoman Divacky /// for an implementation. 3672f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 36733b0f4066SDimitry Andric // We might need a .cxx_destruct even if we don't have any ivar initializers. 36743b0f4066SDimitry Andric if (needsDestructMethod(D)) { 3675f22ef01cSRoman Divacky IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 3676f22ef01cSRoman Divacky Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 36773b0f4066SDimitry Andric ObjCMethodDecl *DTORMethod = 36783b0f4066SDimitry Andric ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 367959d1ed5bSDimitry Andric cxxSelector, getContext().VoidTy, nullptr, D, 36806122f3e6SDimitry Andric /*isInstance=*/true, /*isVariadic=*/false, 36813861d79fSDimitry Andric /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 36826122f3e6SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 3683f22ef01cSRoman Divacky D->addInstanceMethod(DTORMethod); 3684f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 36853861d79fSDimitry Andric D->setHasDestructors(true); 36863b0f4066SDimitry Andric } 3687f22ef01cSRoman Divacky 36883b0f4066SDimitry Andric // If the implementation doesn't have any ivar initializers, we don't need 36893b0f4066SDimitry Andric // a .cxx_construct. 369039d628a0SDimitry Andric if (D->getNumIvarInitializers() == 0 || 369139d628a0SDimitry Andric AllTrivialInitializers(*this, D)) 36923b0f4066SDimitry Andric return; 36933b0f4066SDimitry Andric 36943b0f4066SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 36953b0f4066SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 3696f22ef01cSRoman Divacky // The constructor returns 'self'. 3697f22ef01cSRoman Divacky ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 3698f22ef01cSRoman Divacky D->getLocation(), 36996122f3e6SDimitry Andric D->getLocation(), 37006122f3e6SDimitry Andric cxxSelector, 370159d1ed5bSDimitry Andric getContext().getObjCIdType(), 370259d1ed5bSDimitry Andric nullptr, D, /*isInstance=*/true, 37036122f3e6SDimitry Andric /*isVariadic=*/false, 37043861d79fSDimitry Andric /*isPropertyAccessor=*/true, 37056122f3e6SDimitry Andric /*isImplicitlyDeclared=*/true, 37066122f3e6SDimitry Andric /*isDefined=*/false, 3707f22ef01cSRoman Divacky ObjCMethodDecl::Required); 3708f22ef01cSRoman Divacky D->addInstanceMethod(CTORMethod); 3709f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 37103861d79fSDimitry Andric D->setHasNonZeroConstructors(true); 3711f22ef01cSRoman Divacky } 3712f22ef01cSRoman Divacky 3713f22ef01cSRoman Divacky /// EmitNamespace - Emit all declarations in a namespace. 3714f22ef01cSRoman Divacky void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 371559d1ed5bSDimitry Andric for (auto *I : ND->decls()) { 371659d1ed5bSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(I)) 3717f785676fSDimitry Andric if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 3718f785676fSDimitry Andric VD->getTemplateSpecializationKind() != TSK_Undeclared) 3719f785676fSDimitry Andric continue; 372059d1ed5bSDimitry Andric EmitTopLevelDecl(I); 3721f22ef01cSRoman Divacky } 3722f785676fSDimitry Andric } 3723f22ef01cSRoman Divacky 3724f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec. 3725f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 3726f22ef01cSRoman Divacky if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 3727f22ef01cSRoman Divacky LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 3728f22ef01cSRoman Divacky ErrorUnsupported(LSD, "linkage spec"); 3729f22ef01cSRoman Divacky return; 3730f22ef01cSRoman Divacky } 3731f22ef01cSRoman Divacky 373259d1ed5bSDimitry Andric for (auto *I : LSD->decls()) { 37333861d79fSDimitry Andric // Meta-data for ObjC class includes references to implemented methods. 37343861d79fSDimitry Andric // Generate class's method definitions first. 373559d1ed5bSDimitry Andric if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 373659d1ed5bSDimitry Andric for (auto *M : OID->methods()) 373759d1ed5bSDimitry Andric EmitTopLevelDecl(M); 37383861d79fSDimitry Andric } 373959d1ed5bSDimitry Andric EmitTopLevelDecl(I); 3740f22ef01cSRoman Divacky } 37413861d79fSDimitry Andric } 3742f22ef01cSRoman Divacky 3743f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration. 3744f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) { 3745f22ef01cSRoman Divacky // Ignore dependent declarations. 3746f22ef01cSRoman Divacky if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 3747f22ef01cSRoman Divacky return; 3748f22ef01cSRoman Divacky 3749f22ef01cSRoman Divacky switch (D->getKind()) { 3750f22ef01cSRoman Divacky case Decl::CXXConversion: 3751f22ef01cSRoman Divacky case Decl::CXXMethod: 3752f22ef01cSRoman Divacky case Decl::Function: 3753f22ef01cSRoman Divacky // Skip function templates 37543b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 37553b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3756f22ef01cSRoman Divacky return; 3757f22ef01cSRoman Divacky 3758f22ef01cSRoman Divacky EmitGlobal(cast<FunctionDecl>(D)); 375939d628a0SDimitry Andric // Always provide some coverage mapping 376039d628a0SDimitry Andric // even for the functions that aren't emitted. 376139d628a0SDimitry Andric AddDeferredUnusedCoverageMapping(D); 3762f22ef01cSRoman Divacky break; 3763f22ef01cSRoman Divacky 3764f22ef01cSRoman Divacky case Decl::Var: 3765f785676fSDimitry Andric // Skip variable templates 3766f785676fSDimitry Andric if (cast<VarDecl>(D)->getDescribedVarTemplate()) 3767f785676fSDimitry Andric return; 3768f785676fSDimitry Andric case Decl::VarTemplateSpecialization: 3769f22ef01cSRoman Divacky EmitGlobal(cast<VarDecl>(D)); 3770f22ef01cSRoman Divacky break; 3771f22ef01cSRoman Divacky 37723b0f4066SDimitry Andric // Indirect fields from global anonymous structs and unions can be 37733b0f4066SDimitry Andric // ignored; only the actual variable requires IR gen support. 37743b0f4066SDimitry Andric case Decl::IndirectField: 37753b0f4066SDimitry Andric break; 37763b0f4066SDimitry Andric 3777f22ef01cSRoman Divacky // C++ Decls 3778f22ef01cSRoman Divacky case Decl::Namespace: 3779f22ef01cSRoman Divacky EmitNamespace(cast<NamespaceDecl>(D)); 3780f22ef01cSRoman Divacky break; 3781e7145dcbSDimitry Andric case Decl::CXXRecord: 3782e7145dcbSDimitry Andric // Emit any static data members, they may be definitions. 3783e7145dcbSDimitry Andric for (auto *I : cast<CXXRecordDecl>(D)->decls()) 3784e7145dcbSDimitry Andric if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 3785e7145dcbSDimitry Andric EmitTopLevelDecl(I); 3786e7145dcbSDimitry Andric break; 3787f22ef01cSRoman Divacky // No code generation needed. 3788f22ef01cSRoman Divacky case Decl::UsingShadow: 3789f22ef01cSRoman Divacky case Decl::ClassTemplate: 3790f785676fSDimitry Andric case Decl::VarTemplate: 3791f785676fSDimitry Andric case Decl::VarTemplatePartialSpecialization: 3792f22ef01cSRoman Divacky case Decl::FunctionTemplate: 3793bd5abe19SDimitry Andric case Decl::TypeAliasTemplate: 3794bd5abe19SDimitry Andric case Decl::Block: 3795139f7f9bSDimitry Andric case Decl::Empty: 3796f22ef01cSRoman Divacky break; 379759d1ed5bSDimitry Andric case Decl::Using: // using X; [C++] 379859d1ed5bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 379959d1ed5bSDimitry Andric DI->EmitUsingDecl(cast<UsingDecl>(*D)); 380059d1ed5bSDimitry Andric return; 3801f785676fSDimitry Andric case Decl::NamespaceAlias: 3802f785676fSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3803f785676fSDimitry Andric DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 3804f785676fSDimitry Andric return; 3805284c1978SDimitry Andric case Decl::UsingDirective: // using namespace X; [C++] 3806284c1978SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3807284c1978SDimitry Andric DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 3808284c1978SDimitry Andric return; 3809f22ef01cSRoman Divacky case Decl::CXXConstructor: 3810f22ef01cSRoman Divacky // Skip function templates 38113b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 38123b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3813f22ef01cSRoman Divacky return; 3814f22ef01cSRoman Divacky 3815f785676fSDimitry Andric getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 3816f22ef01cSRoman Divacky break; 3817f22ef01cSRoman Divacky case Decl::CXXDestructor: 38183b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 38193b0f4066SDimitry Andric return; 3820f785676fSDimitry Andric getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 3821f22ef01cSRoman Divacky break; 3822f22ef01cSRoman Divacky 3823f22ef01cSRoman Divacky case Decl::StaticAssert: 3824f22ef01cSRoman Divacky // Nothing to do. 3825f22ef01cSRoman Divacky break; 3826f22ef01cSRoman Divacky 3827f22ef01cSRoman Divacky // Objective-C Decls 3828f22ef01cSRoman Divacky 3829f22ef01cSRoman Divacky // Forward declarations, no (immediate) code generation. 3830f22ef01cSRoman Divacky case Decl::ObjCInterface: 38317ae0e2c9SDimitry Andric case Decl::ObjCCategory: 3832f22ef01cSRoman Divacky break; 3833f22ef01cSRoman Divacky 3834dff0c46cSDimitry Andric case Decl::ObjCProtocol: { 383559d1ed5bSDimitry Andric auto *Proto = cast<ObjCProtocolDecl>(D); 3836dff0c46cSDimitry Andric if (Proto->isThisDeclarationADefinition()) 3837dff0c46cSDimitry Andric ObjCRuntime->GenerateProtocol(Proto); 3838f22ef01cSRoman Divacky break; 3839dff0c46cSDimitry Andric } 3840f22ef01cSRoman Divacky 3841f22ef01cSRoman Divacky case Decl::ObjCCategoryImpl: 3842f22ef01cSRoman Divacky // Categories have properties but don't support synthesize so we 3843f22ef01cSRoman Divacky // can ignore them here. 38446122f3e6SDimitry Andric ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 3845f22ef01cSRoman Divacky break; 3846f22ef01cSRoman Divacky 3847f22ef01cSRoman Divacky case Decl::ObjCImplementation: { 384859d1ed5bSDimitry Andric auto *OMD = cast<ObjCImplementationDecl>(D); 3849f22ef01cSRoman Divacky EmitObjCPropertyImplementations(OMD); 3850f22ef01cSRoman Divacky EmitObjCIvarInitializations(OMD); 38516122f3e6SDimitry Andric ObjCRuntime->GenerateClass(OMD); 3852dff0c46cSDimitry Andric // Emit global variable debug information. 3853dff0c46cSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3854e7145dcbSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 3855139f7f9bSDimitry Andric DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 3856139f7f9bSDimitry Andric OMD->getClassInterface()), OMD->getLocation()); 3857f22ef01cSRoman Divacky break; 3858f22ef01cSRoman Divacky } 3859f22ef01cSRoman Divacky case Decl::ObjCMethod: { 386059d1ed5bSDimitry Andric auto *OMD = cast<ObjCMethodDecl>(D); 3861f22ef01cSRoman Divacky // If this is not a prototype, emit the body. 3862f22ef01cSRoman Divacky if (OMD->getBody()) 3863f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCMethod(OMD); 3864f22ef01cSRoman Divacky break; 3865f22ef01cSRoman Divacky } 3866f22ef01cSRoman Divacky case Decl::ObjCCompatibleAlias: 3867dff0c46cSDimitry Andric ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 3868f22ef01cSRoman Divacky break; 3869f22ef01cSRoman Divacky 3870e7145dcbSDimitry Andric case Decl::PragmaComment: { 3871e7145dcbSDimitry Andric const auto *PCD = cast<PragmaCommentDecl>(D); 3872e7145dcbSDimitry Andric switch (PCD->getCommentKind()) { 3873e7145dcbSDimitry Andric case PCK_Unknown: 3874e7145dcbSDimitry Andric llvm_unreachable("unexpected pragma comment kind"); 3875e7145dcbSDimitry Andric case PCK_Linker: 3876e7145dcbSDimitry Andric AppendLinkerOptions(PCD->getArg()); 3877e7145dcbSDimitry Andric break; 3878e7145dcbSDimitry Andric case PCK_Lib: 3879e7145dcbSDimitry Andric AddDependentLib(PCD->getArg()); 3880e7145dcbSDimitry Andric break; 3881e7145dcbSDimitry Andric case PCK_Compiler: 3882e7145dcbSDimitry Andric case PCK_ExeStr: 3883e7145dcbSDimitry Andric case PCK_User: 3884e7145dcbSDimitry Andric break; // We ignore all of these. 3885e7145dcbSDimitry Andric } 3886e7145dcbSDimitry Andric break; 3887e7145dcbSDimitry Andric } 3888e7145dcbSDimitry Andric 3889e7145dcbSDimitry Andric case Decl::PragmaDetectMismatch: { 3890e7145dcbSDimitry Andric const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 3891e7145dcbSDimitry Andric AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 3892e7145dcbSDimitry Andric break; 3893e7145dcbSDimitry Andric } 3894e7145dcbSDimitry Andric 3895f22ef01cSRoman Divacky case Decl::LinkageSpec: 3896f22ef01cSRoman Divacky EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 3897f22ef01cSRoman Divacky break; 3898f22ef01cSRoman Divacky 3899f22ef01cSRoman Divacky case Decl::FileScopeAsm: { 390033956c43SDimitry Andric // File-scope asm is ignored during device-side CUDA compilation. 390133956c43SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 390233956c43SDimitry Andric break; 3903ea942507SDimitry Andric // File-scope asm is ignored during device-side OpenMP compilation. 3904ea942507SDimitry Andric if (LangOpts.OpenMPIsDevice) 3905ea942507SDimitry Andric break; 390659d1ed5bSDimitry Andric auto *AD = cast<FileScopeAsmDecl>(D); 390733956c43SDimitry Andric getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 3908f22ef01cSRoman Divacky break; 3909f22ef01cSRoman Divacky } 3910f22ef01cSRoman Divacky 3911139f7f9bSDimitry Andric case Decl::Import: { 391259d1ed5bSDimitry Andric auto *Import = cast<ImportDecl>(D); 3913139f7f9bSDimitry Andric 3914139f7f9bSDimitry Andric // Ignore import declarations that come from imported modules. 39150623d748SDimitry Andric if (Import->getImportedOwningModule()) 3916139f7f9bSDimitry Andric break; 39173dac3a9bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 39183dac3a9bSDimitry Andric DI->EmitImportDecl(*Import); 3919139f7f9bSDimitry Andric 3920139f7f9bSDimitry Andric ImportedModules.insert(Import->getImportedModule()); 3921139f7f9bSDimitry Andric break; 3922139f7f9bSDimitry Andric } 3923139f7f9bSDimitry Andric 392439d628a0SDimitry Andric case Decl::OMPThreadPrivate: 392539d628a0SDimitry Andric EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 392639d628a0SDimitry Andric break; 392739d628a0SDimitry Andric 392859d1ed5bSDimitry Andric case Decl::ClassTemplateSpecialization: { 392959d1ed5bSDimitry Andric const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 393059d1ed5bSDimitry Andric if (DebugInfo && 393139d628a0SDimitry Andric Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition && 393239d628a0SDimitry Andric Spec->hasDefinition()) 393359d1ed5bSDimitry Andric DebugInfo->completeTemplateDefinition(*Spec); 393439d628a0SDimitry Andric break; 393559d1ed5bSDimitry Andric } 393659d1ed5bSDimitry Andric 3937e7145dcbSDimitry Andric case Decl::OMPDeclareReduction: 3938e7145dcbSDimitry Andric EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 3939e7145dcbSDimitry Andric break; 3940e7145dcbSDimitry Andric 3941f22ef01cSRoman Divacky default: 3942f22ef01cSRoman Divacky // Make sure we handled everything we should, every other kind is a 3943f22ef01cSRoman Divacky // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 3944f22ef01cSRoman Divacky // function. Need to recode Decl::Kind to do that easily. 3945f22ef01cSRoman Divacky assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 394639d628a0SDimitry Andric break; 394739d628a0SDimitry Andric } 394839d628a0SDimitry Andric } 394939d628a0SDimitry Andric 395039d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 395139d628a0SDimitry Andric // Do we need to generate coverage mapping? 395239d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 395339d628a0SDimitry Andric return; 395439d628a0SDimitry Andric switch (D->getKind()) { 395539d628a0SDimitry Andric case Decl::CXXConversion: 395639d628a0SDimitry Andric case Decl::CXXMethod: 395739d628a0SDimitry Andric case Decl::Function: 395839d628a0SDimitry Andric case Decl::ObjCMethod: 395939d628a0SDimitry Andric case Decl::CXXConstructor: 396039d628a0SDimitry Andric case Decl::CXXDestructor: { 39610623d748SDimitry Andric if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 396239d628a0SDimitry Andric return; 396339d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 396439d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 396539d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = true; 396639d628a0SDimitry Andric break; 396739d628a0SDimitry Andric } 396839d628a0SDimitry Andric default: 396939d628a0SDimitry Andric break; 397039d628a0SDimitry Andric }; 397139d628a0SDimitry Andric } 397239d628a0SDimitry Andric 397339d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 397439d628a0SDimitry Andric // Do we need to generate coverage mapping? 397539d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 397639d628a0SDimitry Andric return; 397739d628a0SDimitry Andric if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 397839d628a0SDimitry Andric if (Fn->isTemplateInstantiation()) 397939d628a0SDimitry Andric ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 398039d628a0SDimitry Andric } 398139d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 398239d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 398339d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = false; 398439d628a0SDimitry Andric else 398539d628a0SDimitry Andric I->second = false; 398639d628a0SDimitry Andric } 398739d628a0SDimitry Andric 398839d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 398939d628a0SDimitry Andric std::vector<const Decl *> DeferredDecls; 399033956c43SDimitry Andric for (const auto &I : DeferredEmptyCoverageMappingDecls) { 399139d628a0SDimitry Andric if (!I.second) 399239d628a0SDimitry Andric continue; 399339d628a0SDimitry Andric DeferredDecls.push_back(I.first); 399439d628a0SDimitry Andric } 399539d628a0SDimitry Andric // Sort the declarations by their location to make sure that the tests get a 399639d628a0SDimitry Andric // predictable order for the coverage mapping for the unused declarations. 399739d628a0SDimitry Andric if (CodeGenOpts.DumpCoverageMapping) 399839d628a0SDimitry Andric std::sort(DeferredDecls.begin(), DeferredDecls.end(), 399939d628a0SDimitry Andric [] (const Decl *LHS, const Decl *RHS) { 400039d628a0SDimitry Andric return LHS->getLocStart() < RHS->getLocStart(); 400139d628a0SDimitry Andric }); 400239d628a0SDimitry Andric for (const auto *D : DeferredDecls) { 400339d628a0SDimitry Andric switch (D->getKind()) { 400439d628a0SDimitry Andric case Decl::CXXConversion: 400539d628a0SDimitry Andric case Decl::CXXMethod: 400639d628a0SDimitry Andric case Decl::Function: 400739d628a0SDimitry Andric case Decl::ObjCMethod: { 400839d628a0SDimitry Andric CodeGenPGO PGO(*this); 400939d628a0SDimitry Andric GlobalDecl GD(cast<FunctionDecl>(D)); 401039d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 401139d628a0SDimitry Andric getFunctionLinkage(GD)); 401239d628a0SDimitry Andric break; 401339d628a0SDimitry Andric } 401439d628a0SDimitry Andric case Decl::CXXConstructor: { 401539d628a0SDimitry Andric CodeGenPGO PGO(*this); 401639d628a0SDimitry Andric GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 401739d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 401839d628a0SDimitry Andric getFunctionLinkage(GD)); 401939d628a0SDimitry Andric break; 402039d628a0SDimitry Andric } 402139d628a0SDimitry Andric case Decl::CXXDestructor: { 402239d628a0SDimitry Andric CodeGenPGO PGO(*this); 402339d628a0SDimitry Andric GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 402439d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 402539d628a0SDimitry Andric getFunctionLinkage(GD)); 402639d628a0SDimitry Andric break; 402739d628a0SDimitry Andric } 402839d628a0SDimitry Andric default: 402939d628a0SDimitry Andric break; 403039d628a0SDimitry Andric }; 4031f22ef01cSRoman Divacky } 4032f22ef01cSRoman Divacky } 4033ffd1746dSEd Schouten 4034ffd1746dSEd Schouten /// Turns the given pointer into a constant. 4035ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 4036ffd1746dSEd Schouten const void *Ptr) { 4037ffd1746dSEd Schouten uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 40386122f3e6SDimitry Andric llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 4039ffd1746dSEd Schouten return llvm::ConstantInt::get(i64, PtrInt); 4040ffd1746dSEd Schouten } 4041ffd1746dSEd Schouten 4042ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 4043ffd1746dSEd Schouten llvm::NamedMDNode *&GlobalMetadata, 4044ffd1746dSEd Schouten GlobalDecl D, 4045ffd1746dSEd Schouten llvm::GlobalValue *Addr) { 4046ffd1746dSEd Schouten if (!GlobalMetadata) 4047ffd1746dSEd Schouten GlobalMetadata = 4048ffd1746dSEd Schouten CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 4049ffd1746dSEd Schouten 4050ffd1746dSEd Schouten // TODO: should we report variant information for ctors/dtors? 405139d628a0SDimitry Andric llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 405239d628a0SDimitry Andric llvm::ConstantAsMetadata::get(GetPointerConstant( 405339d628a0SDimitry Andric CGM.getLLVMContext(), D.getDecl()))}; 40543b0f4066SDimitry Andric GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 4055ffd1746dSEd Schouten } 4056ffd1746dSEd Schouten 4057284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked 4058284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled 4059284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer 4060284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the 4061284c1978SDimitry Andric /// same translation unit. 4062284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() { 4063e7145dcbSDimitry Andric // Don't do anything if we're generating CUDA device code -- the NVPTX 4064e7145dcbSDimitry Andric // assembly target doesn't support aliases. 4065e7145dcbSDimitry Andric if (Context.getTargetInfo().getTriple().isNVPTX()) 4066e7145dcbSDimitry Andric return; 40678f0fd8f6SDimitry Andric for (auto &I : StaticExternCValues) { 40688f0fd8f6SDimitry Andric IdentifierInfo *Name = I.first; 40698f0fd8f6SDimitry Andric llvm::GlobalValue *Val = I.second; 4070284c1978SDimitry Andric if (Val && !getModule().getNamedValue(Name->getName())) 407159d1ed5bSDimitry Andric addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 4072284c1978SDimitry Andric } 4073284c1978SDimitry Andric } 4074284c1978SDimitry Andric 407559d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 407659d1ed5bSDimitry Andric GlobalDecl &Result) const { 407759d1ed5bSDimitry Andric auto Res = Manglings.find(MangledName); 407859d1ed5bSDimitry Andric if (Res == Manglings.end()) 407959d1ed5bSDimitry Andric return false; 408059d1ed5bSDimitry Andric Result = Res->getValue(); 408159d1ed5bSDimitry Andric return true; 408259d1ed5bSDimitry Andric } 408359d1ed5bSDimitry Andric 4084ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the 4085ffd1746dSEd Schouten /// current module with the Decls they came from. This is useful for 4086ffd1746dSEd Schouten /// projects using IR gen as a subroutine. 4087ffd1746dSEd Schouten /// 4088ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly 4089ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata 4090ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'. 4091ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() { 409259d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 4093ffd1746dSEd Schouten 409459d1ed5bSDimitry Andric for (auto &I : MangledDeclNames) { 409559d1ed5bSDimitry Andric llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 40960623d748SDimitry Andric // Some mangled names don't necessarily have an associated GlobalValue 40970623d748SDimitry Andric // in this module, e.g. if we mangled it for DebugInfo. 40980623d748SDimitry Andric if (Addr) 409959d1ed5bSDimitry Andric EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 4100ffd1746dSEd Schouten } 4101ffd1746dSEd Schouten } 4102ffd1746dSEd Schouten 4103ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current 4104ffd1746dSEd Schouten /// function. 4105ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() { 4106ffd1746dSEd Schouten if (LocalDeclMap.empty()) return; 4107ffd1746dSEd Schouten 4108ffd1746dSEd Schouten llvm::LLVMContext &Context = getLLVMContext(); 4109ffd1746dSEd Schouten 4110ffd1746dSEd Schouten // Find the unique metadata ID for this name. 4111ffd1746dSEd Schouten unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 4112ffd1746dSEd Schouten 411359d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 4114ffd1746dSEd Schouten 411559d1ed5bSDimitry Andric for (auto &I : LocalDeclMap) { 411659d1ed5bSDimitry Andric const Decl *D = I.first; 41170623d748SDimitry Andric llvm::Value *Addr = I.second.getPointer(); 411859d1ed5bSDimitry Andric if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 4119ffd1746dSEd Schouten llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 412039d628a0SDimitry Andric Alloca->setMetadata( 412139d628a0SDimitry Andric DeclPtrKind, llvm::MDNode::get( 412239d628a0SDimitry Andric Context, llvm::ValueAsMetadata::getConstant(DAddr))); 412359d1ed5bSDimitry Andric } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 4124ffd1746dSEd Schouten GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 4125ffd1746dSEd Schouten EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 4126ffd1746dSEd Schouten } 4127ffd1746dSEd Schouten } 4128ffd1746dSEd Schouten } 4129e580952dSDimitry Andric 4130f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() { 4131f785676fSDimitry Andric llvm::NamedMDNode *IdentMetadata = 4132f785676fSDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.ident"); 4133f785676fSDimitry Andric std::string Version = getClangFullVersion(); 4134f785676fSDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 4135f785676fSDimitry Andric 413639d628a0SDimitry Andric llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 4137f785676fSDimitry Andric IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 4138f785676fSDimitry Andric } 4139f785676fSDimitry Andric 414059d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() { 414139d628a0SDimitry Andric // Warning, new MangledDeclNames may be appended within this loop. 414239d628a0SDimitry Andric // We rely on MapVector insertions adding new elements to the end 414339d628a0SDimitry Andric // of the container. 414439d628a0SDimitry Andric // FIXME: Move this loop into the one target that needs it, and only 414539d628a0SDimitry Andric // loop over those declarations for which we couldn't emit the target 414639d628a0SDimitry Andric // metadata when we emitted the declaration. 414739d628a0SDimitry Andric for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 414839d628a0SDimitry Andric auto Val = *(MangledDeclNames.begin() + I); 414939d628a0SDimitry Andric const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 415039d628a0SDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(Val.second); 415159d1ed5bSDimitry Andric getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 415259d1ed5bSDimitry Andric } 415359d1ed5bSDimitry Andric } 415459d1ed5bSDimitry Andric 4155bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() { 4156bd5abe19SDimitry Andric if (!getCodeGenOpts().CoverageFile.empty()) { 4157bd5abe19SDimitry Andric if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 4158bd5abe19SDimitry Andric llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 4159bd5abe19SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 4160bd5abe19SDimitry Andric llvm::MDString *CoverageFile = 4161bd5abe19SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 4162bd5abe19SDimitry Andric for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 4163bd5abe19SDimitry Andric llvm::MDNode *CU = CUNode->getOperand(i); 416439d628a0SDimitry Andric llvm::Metadata *Elts[] = {CoverageFile, CU}; 416539d628a0SDimitry Andric GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 4166bd5abe19SDimitry Andric } 4167bd5abe19SDimitry Andric } 4168bd5abe19SDimitry Andric } 4169bd5abe19SDimitry Andric } 41703861d79fSDimitry Andric 417139d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { 41723861d79fSDimitry Andric // Sema has checked that all uuid strings are of the form 41733861d79fSDimitry Andric // "12345678-1234-1234-1234-1234567890ab". 41743861d79fSDimitry Andric assert(Uuid.size() == 36); 4175f785676fSDimitry Andric for (unsigned i = 0; i < 36; ++i) { 4176f785676fSDimitry Andric if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 4177f785676fSDimitry Andric else assert(isHexDigit(Uuid[i])); 41783861d79fSDimitry Andric } 41793861d79fSDimitry Andric 418039d628a0SDimitry Andric // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". 4181f785676fSDimitry Andric const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 41823861d79fSDimitry Andric 4183f785676fSDimitry Andric llvm::Constant *Field3[8]; 4184f785676fSDimitry Andric for (unsigned Idx = 0; Idx < 8; ++Idx) 4185f785676fSDimitry Andric Field3[Idx] = llvm::ConstantInt::get( 4186f785676fSDimitry Andric Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 41873861d79fSDimitry Andric 4188f785676fSDimitry Andric llvm::Constant *Fields[4] = { 4189f785676fSDimitry Andric llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 4190f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 4191f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 4192f785676fSDimitry Andric llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 4193f785676fSDimitry Andric }; 4194f785676fSDimitry Andric 4195f785676fSDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 41963861d79fSDimitry Andric } 419759d1ed5bSDimitry Andric 419859d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 419959d1ed5bSDimitry Andric bool ForEH) { 420059d1ed5bSDimitry Andric // Return a bogus pointer if RTTI is disabled, unless it's for EH. 420159d1ed5bSDimitry Andric // FIXME: should we even be calling this method if RTTI is disabled 420259d1ed5bSDimitry Andric // and it's not for EH? 420359d1ed5bSDimitry Andric if (!ForEH && !getLangOpts().RTTI) 420459d1ed5bSDimitry Andric return llvm::Constant::getNullValue(Int8PtrTy); 420559d1ed5bSDimitry Andric 420659d1ed5bSDimitry Andric if (ForEH && Ty->isObjCObjectPointerType() && 420759d1ed5bSDimitry Andric LangOpts.ObjCRuntime.isGNUFamily()) 420859d1ed5bSDimitry Andric return ObjCRuntime->GetEHType(Ty); 420959d1ed5bSDimitry Andric 421059d1ed5bSDimitry Andric return getCXXABI().getAddrOfRTTIDescriptor(Ty); 421159d1ed5bSDimitry Andric } 421259d1ed5bSDimitry Andric 421339d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 421439d628a0SDimitry Andric for (auto RefExpr : D->varlists()) { 421539d628a0SDimitry Andric auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 421639d628a0SDimitry Andric bool PerformInit = 421739d628a0SDimitry Andric VD->getAnyInitializer() && 421839d628a0SDimitry Andric !VD->getAnyInitializer()->isConstantInitializer(getContext(), 421939d628a0SDimitry Andric /*ForRef=*/false); 42200623d748SDimitry Andric 42210623d748SDimitry Andric Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 422233956c43SDimitry Andric if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 42230623d748SDimitry Andric VD, Addr, RefExpr->getLocStart(), PerformInit)) 422439d628a0SDimitry Andric CXXGlobalInits.push_back(InitFunction); 422539d628a0SDimitry Andric } 422639d628a0SDimitry Andric } 42278f0fd8f6SDimitry Andric 42280623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 42290623d748SDimitry Andric llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()]; 42300623d748SDimitry Andric if (InternalId) 42310623d748SDimitry Andric return InternalId; 42320623d748SDimitry Andric 42330623d748SDimitry Andric if (isExternallyVisible(T->getLinkage())) { 42348f0fd8f6SDimitry Andric std::string OutName; 42358f0fd8f6SDimitry Andric llvm::raw_string_ostream Out(OutName); 42360623d748SDimitry Andric getCXXABI().getMangleContext().mangleTypeName(T, Out); 42378f0fd8f6SDimitry Andric 42380623d748SDimitry Andric InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 42390623d748SDimitry Andric } else { 42400623d748SDimitry Andric InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 42410623d748SDimitry Andric llvm::ArrayRef<llvm::Metadata *>()); 42420623d748SDimitry Andric } 42430623d748SDimitry Andric 42440623d748SDimitry Andric return InternalId; 42450623d748SDimitry Andric } 42460623d748SDimitry Andric 4247e7145dcbSDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier. 4248e7145dcbSDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const { 4249e7145dcbSDimitry Andric // Returns true if at least one of vtable-based CFI checkers is enabled and 4250e7145dcbSDimitry Andric // is not in the trapping mode. 4251e7145dcbSDimitry Andric return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 4252e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 4253e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 4254e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 4255e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 4256e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 4257e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 4258e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 4259e7145dcbSDimitry Andric } 4260e7145dcbSDimitry Andric 4261e7145dcbSDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 42620623d748SDimitry Andric CharUnits Offset, 42630623d748SDimitry Andric const CXXRecordDecl *RD) { 42640623d748SDimitry Andric llvm::Metadata *MD = 42650623d748SDimitry Andric CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 4266e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 42670623d748SDimitry Andric 4268e7145dcbSDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 4269e7145dcbSDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 4270e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), 4271e7145dcbSDimitry Andric llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 4272e7145dcbSDimitry Andric 4273e7145dcbSDimitry Andric if (NeedAllVtablesTypeId()) { 4274e7145dcbSDimitry Andric llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 4275e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 42760623d748SDimitry Andric } 42770623d748SDimitry Andric } 42780623d748SDimitry Andric 42790623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the 42800623d748SDimitry Andric // passed in function. 42810623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 42820623d748SDimitry Andric const FunctionDecl *FD) { 42830623d748SDimitry Andric StringRef TargetCPU = Target.getTargetOpts().CPU; 42840623d748SDimitry Andric if (const auto *TD = FD->getAttr<TargetAttr>()) { 42850623d748SDimitry Andric // If we have a TargetAttr build up the feature map based on that. 42860623d748SDimitry Andric TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); 42870623d748SDimitry Andric 42880623d748SDimitry Andric // Make a copy of the features as passed on the command line into the 42890623d748SDimitry Andric // beginning of the additional features from the function to override. 42900623d748SDimitry Andric ParsedAttr.first.insert(ParsedAttr.first.begin(), 42910623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.begin(), 42920623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.end()); 42930623d748SDimitry Andric 42940623d748SDimitry Andric if (ParsedAttr.second != "") 42950623d748SDimitry Andric TargetCPU = ParsedAttr.second; 42960623d748SDimitry Andric 42970623d748SDimitry Andric // Now populate the feature map, first with the TargetCPU which is either 42980623d748SDimitry Andric // the default or a new one from the target attribute string. Then we'll use 42990623d748SDimitry Andric // the passed in features (FeaturesAsWritten) along with the new ones from 43000623d748SDimitry Andric // the attribute. 43010623d748SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first); 43020623d748SDimitry Andric } else { 43030623d748SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 43040623d748SDimitry Andric Target.getTargetOpts().Features); 43050623d748SDimitry Andric } 43068f0fd8f6SDimitry Andric } 4307e7145dcbSDimitry Andric 4308e7145dcbSDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 4309e7145dcbSDimitry Andric if (!SanStats) 4310e7145dcbSDimitry Andric SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule()); 4311e7145dcbSDimitry Andric 4312e7145dcbSDimitry Andric return *SanStats; 4313e7145dcbSDimitry Andric } 4314