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" 4420e90f04SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h" 45139f7f9bSDimitry Andric #include "clang/Frontend/CodeGenOptions.h" 46f785676fSDimitry Andric #include "clang/Sema/SemaDiagnostic.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(); 10544290647SDimitry Andric SizeSizeInBytes = 10644290647SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); 1070623d748SDimitry Andric IntAlignInBytes = 1080623d748SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 109dff0c46cSDimitry Andric IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 11044290647SDimitry Andric IntPtrTy = llvm::IntegerType::get(LLVMContext, 11144290647SDimitry Andric C.getTargetInfo().getMaxPointerWidth()); 112dff0c46cSDimitry Andric Int8PtrTy = Int8Ty->getPointerTo(0); 113dff0c46cSDimitry Andric Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 1146bc11b14SDimitry Andric AllocaInt8PtrTy = Int8Ty->getPointerTo( 1156bc11b14SDimitry Andric M.getDataLayout().getAllocaAddrSpace()); 116dff0c46cSDimitry Andric 117139f7f9bSDimitry Andric RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 11839d628a0SDimitry Andric BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC(); 119139f7f9bSDimitry Andric 120dff0c46cSDimitry Andric if (LangOpts.ObjC1) 1213b0f4066SDimitry Andric createObjCRuntime(); 122dff0c46cSDimitry Andric if (LangOpts.OpenCL) 1236122f3e6SDimitry Andric createOpenCLRuntime(); 12459d1ed5bSDimitry Andric if (LangOpts.OpenMP) 12559d1ed5bSDimitry Andric createOpenMPRuntime(); 126dff0c46cSDimitry Andric if (LangOpts.CUDA) 1276122f3e6SDimitry Andric createCUDARuntime(); 128f22ef01cSRoman Divacky 1297ae0e2c9SDimitry Andric // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 13039d628a0SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 1317ae0e2c9SDimitry Andric (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 132e7145dcbSDimitry Andric TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(), 133e7145dcbSDimitry Andric getCXXABI().getMangleContext())); 1342754fe60SDimitry Andric 1353b0f4066SDimitry Andric // If debug info or coverage generation is enabled, create the CGDebugInfo 1363b0f4066SDimitry Andric // object. 137e7145dcbSDimitry Andric if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo || 138e7145dcbSDimitry Andric CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) 139e7145dcbSDimitry Andric DebugInfo.reset(new CGDebugInfo(*this)); 1402754fe60SDimitry Andric 1412754fe60SDimitry Andric Block.GlobalUniqueCount = 0; 1422754fe60SDimitry Andric 1430623d748SDimitry Andric if (C.getLangOpts().ObjC1) 144e7145dcbSDimitry Andric ObjCData.reset(new ObjCEntrypoints()); 14559d1ed5bSDimitry Andric 146e7145dcbSDimitry Andric if (CodeGenOpts.hasProfileClangUse()) { 147e7145dcbSDimitry Andric auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 148e7145dcbSDimitry Andric CodeGenOpts.ProfileInstrumentUsePath); 149e7145dcbSDimitry Andric if (auto E = ReaderOrErr.takeError()) { 15059d1ed5bSDimitry Andric unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 1513dac3a9bSDimitry Andric "Could not read profile %0: %1"); 152e7145dcbSDimitry Andric llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { 153e7145dcbSDimitry Andric getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath 154e7145dcbSDimitry Andric << EI.message(); 155e7145dcbSDimitry Andric }); 15633956c43SDimitry Andric } else 15733956c43SDimitry Andric PGOReader = std::move(ReaderOrErr.get()); 15859d1ed5bSDimitry Andric } 15939d628a0SDimitry Andric 16039d628a0SDimitry Andric // If coverage mapping generation is enabled, create the 16139d628a0SDimitry Andric // CoverageMappingModuleGen object. 16239d628a0SDimitry Andric if (CodeGenOpts.CoverageMapping) 16339d628a0SDimitry Andric CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 164f22ef01cSRoman Divacky } 165f22ef01cSRoman Divacky 166e7145dcbSDimitry Andric CodeGenModule::~CodeGenModule() {} 167f22ef01cSRoman Divacky 168f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() { 1697ae0e2c9SDimitry Andric // This is just isGNUFamily(), but we want to force implementors of 1707ae0e2c9SDimitry Andric // new ABIs to decide how best to do this. 1717ae0e2c9SDimitry Andric switch (LangOpts.ObjCRuntime.getKind()) { 1727ae0e2c9SDimitry Andric case ObjCRuntime::GNUstep: 1737ae0e2c9SDimitry Andric case ObjCRuntime::GCC: 1747ae0e2c9SDimitry Andric case ObjCRuntime::ObjFW: 175e7145dcbSDimitry Andric ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 1767ae0e2c9SDimitry Andric return; 1777ae0e2c9SDimitry Andric 1787ae0e2c9SDimitry Andric case ObjCRuntime::FragileMacOSX: 1797ae0e2c9SDimitry Andric case ObjCRuntime::MacOSX: 1807ae0e2c9SDimitry Andric case ObjCRuntime::iOS: 1810623d748SDimitry Andric case ObjCRuntime::WatchOS: 182e7145dcbSDimitry Andric ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 1837ae0e2c9SDimitry Andric return; 1847ae0e2c9SDimitry Andric } 1857ae0e2c9SDimitry Andric llvm_unreachable("bad runtime kind"); 1866122f3e6SDimitry Andric } 1876122f3e6SDimitry Andric 1886122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() { 189e7145dcbSDimitry Andric OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 1906122f3e6SDimitry Andric } 1916122f3e6SDimitry Andric 19259d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() { 193e7145dcbSDimitry Andric // Select a specialized code generation class based on the target, if any. 194e7145dcbSDimitry Andric // If it does not exist use the default implementation. 19544290647SDimitry Andric switch (getTriple().getArch()) { 196e7145dcbSDimitry Andric case llvm::Triple::nvptx: 197e7145dcbSDimitry Andric case llvm::Triple::nvptx64: 198e7145dcbSDimitry Andric assert(getLangOpts().OpenMPIsDevice && 199e7145dcbSDimitry Andric "OpenMP NVPTX is only prepared to deal with device code."); 200e7145dcbSDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this)); 201e7145dcbSDimitry Andric break; 202e7145dcbSDimitry Andric default: 203e7145dcbSDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 204e7145dcbSDimitry Andric break; 205e7145dcbSDimitry Andric } 20659d1ed5bSDimitry Andric } 20759d1ed5bSDimitry Andric 2086122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() { 209e7145dcbSDimitry Andric CUDARuntime.reset(CreateNVCUDARuntime(*this)); 210f22ef01cSRoman Divacky } 211f22ef01cSRoman Divacky 21239d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 21339d628a0SDimitry Andric Replacements[Name] = C; 21439d628a0SDimitry Andric } 21539d628a0SDimitry Andric 216f785676fSDimitry Andric void CodeGenModule::applyReplacements() { 2178f0fd8f6SDimitry Andric for (auto &I : Replacements) { 2188f0fd8f6SDimitry Andric StringRef MangledName = I.first(); 2198f0fd8f6SDimitry Andric llvm::Constant *Replacement = I.second; 220f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 221f785676fSDimitry Andric if (!Entry) 222f785676fSDimitry Andric continue; 22359d1ed5bSDimitry Andric auto *OldF = cast<llvm::Function>(Entry); 22459d1ed5bSDimitry Andric auto *NewF = dyn_cast<llvm::Function>(Replacement); 225f785676fSDimitry Andric if (!NewF) { 22659d1ed5bSDimitry Andric if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 22759d1ed5bSDimitry Andric NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 22859d1ed5bSDimitry Andric } else { 22959d1ed5bSDimitry Andric auto *CE = cast<llvm::ConstantExpr>(Replacement); 230f785676fSDimitry Andric assert(CE->getOpcode() == llvm::Instruction::BitCast || 231f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::GetElementPtr); 232f785676fSDimitry Andric NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 233f785676fSDimitry Andric } 23459d1ed5bSDimitry Andric } 235f785676fSDimitry Andric 236f785676fSDimitry Andric // Replace old with new, but keep the old order. 237f785676fSDimitry Andric OldF->replaceAllUsesWith(Replacement); 238f785676fSDimitry Andric if (NewF) { 239f785676fSDimitry Andric NewF->removeFromParent(); 2400623d748SDimitry Andric OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 2410623d748SDimitry Andric NewF); 242f785676fSDimitry Andric } 243f785676fSDimitry Andric OldF->eraseFromParent(); 244f785676fSDimitry Andric } 245f785676fSDimitry Andric } 246f785676fSDimitry Andric 2470623d748SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 2480623d748SDimitry Andric GlobalValReplacements.push_back(std::make_pair(GV, C)); 2490623d748SDimitry Andric } 2500623d748SDimitry Andric 2510623d748SDimitry Andric void CodeGenModule::applyGlobalValReplacements() { 2520623d748SDimitry Andric for (auto &I : GlobalValReplacements) { 2530623d748SDimitry Andric llvm::GlobalValue *GV = I.first; 2540623d748SDimitry Andric llvm::Constant *C = I.second; 2550623d748SDimitry Andric 2560623d748SDimitry Andric GV->replaceAllUsesWith(C); 2570623d748SDimitry Andric GV->eraseFromParent(); 2580623d748SDimitry Andric } 2590623d748SDimitry Andric } 2600623d748SDimitry Andric 26159d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a 26259d1ed5bSDimitry Andric // linear structure. 263e7145dcbSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal( 264e7145dcbSDimitry Andric const llvm::GlobalIndirectSymbol &GIS) { 265e7145dcbSDimitry Andric llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited; 266e7145dcbSDimitry Andric const llvm::Constant *C = &GIS; 26759d1ed5bSDimitry Andric for (;;) { 26859d1ed5bSDimitry Andric C = C->stripPointerCasts(); 26959d1ed5bSDimitry Andric if (auto *GO = dyn_cast<llvm::GlobalObject>(C)) 27059d1ed5bSDimitry Andric return GO; 27159d1ed5bSDimitry Andric // stripPointerCasts will not walk over weak aliases. 272e7145dcbSDimitry Andric auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C); 273e7145dcbSDimitry Andric if (!GIS2) 27459d1ed5bSDimitry Andric return nullptr; 275e7145dcbSDimitry Andric if (!Visited.insert(GIS2).second) 27659d1ed5bSDimitry Andric return nullptr; 277e7145dcbSDimitry Andric C = GIS2->getIndirectSymbol(); 27859d1ed5bSDimitry Andric } 27959d1ed5bSDimitry Andric } 28059d1ed5bSDimitry Andric 281f785676fSDimitry Andric void CodeGenModule::checkAliases() { 28259d1ed5bSDimitry Andric // Check if the constructed aliases are well formed. It is really unfortunate 28359d1ed5bSDimitry Andric // that we have to do this in CodeGen, but we only construct mangled names 28459d1ed5bSDimitry Andric // and aliases during codegen. 285f785676fSDimitry Andric bool Error = false; 28659d1ed5bSDimitry Andric DiagnosticsEngine &Diags = getDiags(); 2878f0fd8f6SDimitry Andric for (const GlobalDecl &GD : Aliases) { 28859d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 289e7145dcbSDimitry Andric SourceLocation Location; 290e7145dcbSDimitry Andric bool IsIFunc = D->hasAttr<IFuncAttr>(); 291e7145dcbSDimitry Andric if (const Attr *A = D->getDefiningAttr()) 292e7145dcbSDimitry Andric Location = A->getLocation(); 293e7145dcbSDimitry Andric else 294e7145dcbSDimitry Andric llvm_unreachable("Not an alias or ifunc?"); 295f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 296f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 297e7145dcbSDimitry Andric auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry); 29859d1ed5bSDimitry Andric const llvm::GlobalValue *GV = getAliasedGlobal(*Alias); 29959d1ed5bSDimitry Andric if (!GV) { 300f785676fSDimitry Andric Error = true; 301e7145dcbSDimitry Andric Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 30259d1ed5bSDimitry Andric } else if (GV->isDeclaration()) { 303f785676fSDimitry Andric Error = true; 304e7145dcbSDimitry Andric Diags.Report(Location, diag::err_alias_to_undefined) 305e7145dcbSDimitry Andric << IsIFunc << IsIFunc; 306e7145dcbSDimitry Andric } else if (IsIFunc) { 307e7145dcbSDimitry Andric // Check resolver function type. 308e7145dcbSDimitry Andric llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>( 309e7145dcbSDimitry Andric GV->getType()->getPointerElementType()); 310e7145dcbSDimitry Andric assert(FTy); 311e7145dcbSDimitry Andric if (!FTy->getReturnType()->isPointerTy()) 312e7145dcbSDimitry Andric Diags.Report(Location, diag::err_ifunc_resolver_return); 313e7145dcbSDimitry Andric if (FTy->getNumParams()) 314e7145dcbSDimitry Andric Diags.Report(Location, diag::err_ifunc_resolver_params); 31559d1ed5bSDimitry Andric } 31659d1ed5bSDimitry Andric 317e7145dcbSDimitry Andric llvm::Constant *Aliasee = Alias->getIndirectSymbol(); 31859d1ed5bSDimitry Andric llvm::GlobalValue *AliaseeGV; 31959d1ed5bSDimitry Andric if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 32059d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 32159d1ed5bSDimitry Andric else 32259d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 32359d1ed5bSDimitry Andric 32459d1ed5bSDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 32559d1ed5bSDimitry Andric StringRef AliasSection = SA->getName(); 32659d1ed5bSDimitry Andric if (AliasSection != AliaseeGV->getSection()) 32759d1ed5bSDimitry Andric Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 328e7145dcbSDimitry Andric << AliasSection << IsIFunc << IsIFunc; 32959d1ed5bSDimitry Andric } 33059d1ed5bSDimitry Andric 33159d1ed5bSDimitry Andric // We have to handle alias to weak aliases in here. LLVM itself disallows 33259d1ed5bSDimitry Andric // this since the object semantics would not match the IL one. For 33359d1ed5bSDimitry Andric // compatibility with gcc we implement it by just pointing the alias 33459d1ed5bSDimitry Andric // to its aliasee's aliasee. We also warn, since the user is probably 33559d1ed5bSDimitry Andric // expecting the link to be weak. 336e7145dcbSDimitry Andric if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) { 337e7145dcbSDimitry Andric if (GA->isInterposable()) { 338e7145dcbSDimitry Andric Diags.Report(Location, diag::warn_alias_to_weak_alias) 339e7145dcbSDimitry Andric << GV->getName() << GA->getName() << IsIFunc; 34059d1ed5bSDimitry Andric Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 341e7145dcbSDimitry Andric GA->getIndirectSymbol(), Alias->getType()); 342e7145dcbSDimitry Andric Alias->setIndirectSymbol(Aliasee); 34359d1ed5bSDimitry Andric } 344f785676fSDimitry Andric } 345f785676fSDimitry Andric } 346f785676fSDimitry Andric if (!Error) 347f785676fSDimitry Andric return; 348f785676fSDimitry Andric 3498f0fd8f6SDimitry Andric for (const GlobalDecl &GD : Aliases) { 350f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 351f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 352e7145dcbSDimitry Andric auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry); 353f785676fSDimitry Andric Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 354f785676fSDimitry Andric Alias->eraseFromParent(); 355f785676fSDimitry Andric } 356f785676fSDimitry Andric } 357f785676fSDimitry Andric 35859d1ed5bSDimitry Andric void CodeGenModule::clear() { 35959d1ed5bSDimitry Andric DeferredDeclsToEmit.clear(); 36033956c43SDimitry Andric if (OpenMPRuntime) 36133956c43SDimitry Andric OpenMPRuntime->clear(); 36259d1ed5bSDimitry Andric } 36359d1ed5bSDimitry Andric 36459d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 36559d1ed5bSDimitry Andric StringRef MainFile) { 36659d1ed5bSDimitry Andric if (!hasDiagnostics()) 36759d1ed5bSDimitry Andric return; 36859d1ed5bSDimitry Andric if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 36959d1ed5bSDimitry Andric if (MainFile.empty()) 37059d1ed5bSDimitry Andric MainFile = "<stdin>"; 37159d1ed5bSDimitry Andric Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 372f37b6182SDimitry Andric } else { 373f37b6182SDimitry Andric if (Mismatched > 0) 374f37b6182SDimitry Andric Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; 375f37b6182SDimitry Andric 376f37b6182SDimitry Andric if (Missing > 0) 377f37b6182SDimitry Andric Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; 378f37b6182SDimitry Andric } 37959d1ed5bSDimitry Andric } 38059d1ed5bSDimitry Andric 381f22ef01cSRoman Divacky void CodeGenModule::Release() { 382f22ef01cSRoman Divacky EmitDeferred(); 3830623d748SDimitry Andric applyGlobalValReplacements(); 384f785676fSDimitry Andric applyReplacements(); 385f785676fSDimitry Andric checkAliases(); 386f22ef01cSRoman Divacky EmitCXXGlobalInitFunc(); 387f22ef01cSRoman Divacky EmitCXXGlobalDtorFunc(); 388284c1978SDimitry Andric EmitCXXThreadLocalInitFunc(); 3896122f3e6SDimitry Andric if (ObjCRuntime) 3906122f3e6SDimitry Andric if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 391f22ef01cSRoman Divacky AddGlobalCtor(ObjCInitFunction); 39233956c43SDimitry Andric if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice && 39333956c43SDimitry Andric CUDARuntime) { 39433956c43SDimitry Andric if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction()) 39533956c43SDimitry Andric AddGlobalCtor(CudaCtorFunction); 39633956c43SDimitry Andric if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction()) 39733956c43SDimitry Andric AddGlobalDtor(CudaDtorFunction); 39833956c43SDimitry Andric } 399ea942507SDimitry Andric if (OpenMPRuntime) 400ea942507SDimitry Andric if (llvm::Function *OpenMPRegistrationFunction = 401ea942507SDimitry Andric OpenMPRuntime->emitRegistrationFunction()) 402ea942507SDimitry Andric AddGlobalCtor(OpenMPRegistrationFunction, 0); 4030623d748SDimitry Andric if (PGOReader) { 404e7145dcbSDimitry Andric getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext)); 4050623d748SDimitry Andric if (PGOStats.hasDiagnostics()) 40659d1ed5bSDimitry Andric PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 4070623d748SDimitry Andric } 408f22ef01cSRoman Divacky EmitCtorList(GlobalCtors, "llvm.global_ctors"); 409f22ef01cSRoman Divacky EmitCtorList(GlobalDtors, "llvm.global_dtors"); 4106122f3e6SDimitry Andric EmitGlobalAnnotations(); 411284c1978SDimitry Andric EmitStaticExternCAliases(); 41239d628a0SDimitry Andric EmitDeferredUnusedCoverageMappings(); 41339d628a0SDimitry Andric if (CoverageMapping) 41439d628a0SDimitry Andric CoverageMapping->emit(); 41520e90f04SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 416e7145dcbSDimitry Andric CodeGenFunction(*this).EmitCfiCheckFail(); 41720e90f04SDimitry Andric CodeGenFunction(*this).EmitCfiCheckStub(); 41820e90f04SDimitry Andric } 41920e90f04SDimitry Andric emitAtAvailableLinkGuard(); 42059d1ed5bSDimitry Andric emitLLVMUsed(); 421e7145dcbSDimitry Andric if (SanStats) 422e7145dcbSDimitry Andric SanStats->finish(); 423ffd1746dSEd Schouten 424f785676fSDimitry Andric if (CodeGenOpts.Autolink && 425f785676fSDimitry Andric (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 426139f7f9bSDimitry Andric EmitModuleLinkOptions(); 427139f7f9bSDimitry Andric } 42820e90f04SDimitry Andric 42920e90f04SDimitry Andric // Record mregparm value now so it is visible through rest of codegen. 43020e90f04SDimitry Andric if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 43120e90f04SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", 43220e90f04SDimitry Andric CodeGenOpts.NumRegisterParameters); 43320e90f04SDimitry Andric 4340623d748SDimitry Andric if (CodeGenOpts.DwarfVersion) { 435f785676fSDimitry Andric // We actually want the latest version when there are conflicts. 436f785676fSDimitry Andric // We can change from Warning to Latest if such mode is supported. 437f785676fSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 438f785676fSDimitry Andric CodeGenOpts.DwarfVersion); 4390623d748SDimitry Andric } 4400623d748SDimitry Andric if (CodeGenOpts.EmitCodeView) { 4410623d748SDimitry Andric // Indicate that we want CodeView in the metadata. 4420623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 4430623d748SDimitry Andric } 4440623d748SDimitry Andric if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 4450623d748SDimitry Andric // We don't support LTO with 2 with different StrictVTablePointers 4460623d748SDimitry Andric // FIXME: we could support it by stripping all the information introduced 4470623d748SDimitry Andric // by StrictVTablePointers. 4480623d748SDimitry Andric 4490623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 4500623d748SDimitry Andric 4510623d748SDimitry Andric llvm::Metadata *Ops[2] = { 4520623d748SDimitry Andric llvm::MDString::get(VMContext, "StrictVTablePointers"), 4530623d748SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 4540623d748SDimitry Andric llvm::Type::getInt32Ty(VMContext), 1))}; 4550623d748SDimitry Andric 4560623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Require, 4570623d748SDimitry Andric "StrictVTablePointersRequirement", 4580623d748SDimitry Andric llvm::MDNode::get(VMContext, Ops)); 4590623d748SDimitry Andric } 460f785676fSDimitry Andric if (DebugInfo) 46159d1ed5bSDimitry Andric // We support a single version in the linked module. The LLVM 46259d1ed5bSDimitry Andric // parser will drop debug info with a different version number 46359d1ed5bSDimitry Andric // (and warn about it, too). 46459d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 465f785676fSDimitry Andric llvm::DEBUG_METADATA_VERSION); 466139f7f9bSDimitry Andric 46759d1ed5bSDimitry Andric // We need to record the widths of enums and wchar_t, so that we can generate 46859d1ed5bSDimitry Andric // the correct build attributes in the ARM backend. 46959d1ed5bSDimitry Andric llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 47059d1ed5bSDimitry Andric if ( Arch == llvm::Triple::arm 47159d1ed5bSDimitry Andric || Arch == llvm::Triple::armeb 47259d1ed5bSDimitry Andric || Arch == llvm::Triple::thumb 47359d1ed5bSDimitry Andric || Arch == llvm::Triple::thumbeb) { 47459d1ed5bSDimitry Andric // Width of wchar_t in bytes 47559d1ed5bSDimitry Andric uint64_t WCharWidth = 47659d1ed5bSDimitry Andric Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 47759d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 47859d1ed5bSDimitry Andric 47959d1ed5bSDimitry Andric // The minimum width of an enum in bytes 48059d1ed5bSDimitry Andric uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 48159d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 48259d1ed5bSDimitry Andric } 48359d1ed5bSDimitry Andric 4840623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 4850623d748SDimitry Andric // Indicate that we want cross-DSO control flow integrity checks. 4860623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 4870623d748SDimitry Andric } 4880623d748SDimitry Andric 48944290647SDimitry Andric if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { 490e7145dcbSDimitry Andric // Indicate whether __nvvm_reflect should be configured to flush denormal 491e7145dcbSDimitry Andric // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 492e7145dcbSDimitry Andric // property.) 493e7145dcbSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 494e7145dcbSDimitry Andric LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0); 49539d628a0SDimitry Andric } 49639d628a0SDimitry Andric 497e7145dcbSDimitry Andric if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 498e7145dcbSDimitry Andric assert(PLevel < 3 && "Invalid PIC Level"); 499e7145dcbSDimitry Andric getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 500e7145dcbSDimitry Andric if (Context.getLangOpts().PIE) 501e7145dcbSDimitry Andric getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 50239d628a0SDimitry Andric } 50339d628a0SDimitry Andric 5042754fe60SDimitry Andric SimplifyPersonality(); 5052754fe60SDimitry Andric 506ffd1746dSEd Schouten if (getCodeGenOpts().EmitDeclMetadata) 507ffd1746dSEd Schouten EmitDeclMetadata(); 508bd5abe19SDimitry Andric 509bd5abe19SDimitry Andric if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 510bd5abe19SDimitry Andric EmitCoverageFile(); 5116122f3e6SDimitry Andric 5126122f3e6SDimitry Andric if (DebugInfo) 5136122f3e6SDimitry Andric DebugInfo->finalize(); 514f785676fSDimitry Andric 515f785676fSDimitry Andric EmitVersionIdentMetadata(); 51659d1ed5bSDimitry Andric 51759d1ed5bSDimitry Andric EmitTargetMetadata(); 518f22ef01cSRoman Divacky } 519f22ef01cSRoman Divacky 5203b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 5213b0f4066SDimitry Andric // Make sure that this type is translated. 5223b0f4066SDimitry Andric Types.UpdateCompletedType(TD); 5233b0f4066SDimitry Andric } 5243b0f4066SDimitry Andric 525e7145dcbSDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 526e7145dcbSDimitry Andric // Make sure that this type is translated. 527e7145dcbSDimitry Andric Types.RefreshTypeCacheForClass(RD); 528e7145dcbSDimitry Andric } 529e7145dcbSDimitry Andric 5302754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 5312754fe60SDimitry Andric if (!TBAA) 53259d1ed5bSDimitry Andric return nullptr; 5332754fe60SDimitry Andric return TBAA->getTBAAInfo(QTy); 5342754fe60SDimitry Andric } 5352754fe60SDimitry Andric 536dff0c46cSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 537dff0c46cSDimitry Andric if (!TBAA) 53859d1ed5bSDimitry Andric return nullptr; 539dff0c46cSDimitry Andric return TBAA->getTBAAInfoForVTablePtr(); 540dff0c46cSDimitry Andric } 541dff0c46cSDimitry Andric 5423861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 5433861d79fSDimitry Andric if (!TBAA) 54459d1ed5bSDimitry Andric return nullptr; 5453861d79fSDimitry Andric return TBAA->getTBAAStructInfo(QTy); 5463861d79fSDimitry Andric } 5473861d79fSDimitry Andric 548139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy, 549139f7f9bSDimitry Andric llvm::MDNode *AccessN, 550139f7f9bSDimitry Andric uint64_t O) { 551139f7f9bSDimitry Andric if (!TBAA) 55259d1ed5bSDimitry Andric return nullptr; 553139f7f9bSDimitry Andric return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O); 554139f7f9bSDimitry Andric } 555139f7f9bSDimitry Andric 556f785676fSDimitry Andric /// Decorate the instruction with a TBAA tag. For both scalar TBAA 557f785676fSDimitry Andric /// and struct-path aware TBAA, the tag has the same format: 558f785676fSDimitry Andric /// base type, access type and offset. 559284c1978SDimitry Andric /// When ConvertTypeToTag is true, we create a tag based on the scalar type. 5600623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 561284c1978SDimitry Andric llvm::MDNode *TBAAInfo, 562284c1978SDimitry Andric bool ConvertTypeToTag) { 563f785676fSDimitry Andric if (ConvertTypeToTag && TBAA) 564284c1978SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, 565284c1978SDimitry Andric TBAA->getTBAAScalarTagInfo(TBAAInfo)); 566284c1978SDimitry Andric else 5672754fe60SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 5682754fe60SDimitry Andric } 5692754fe60SDimitry Andric 5700623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup( 5710623d748SDimitry Andric llvm::Instruction *I, const CXXRecordDecl *RD) { 57251690af2SDimitry Andric I->setMetadata(llvm::LLVMContext::MD_invariant_group, 57351690af2SDimitry Andric llvm::MDNode::get(getLLVMContext(), {})); 5740623d748SDimitry Andric } 5750623d748SDimitry Andric 57659d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) { 57759d1ed5bSDimitry Andric unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 57859d1ed5bSDimitry Andric getDiags().Report(Context.getFullLoc(loc), diagID) << message; 579f22ef01cSRoman Divacky } 580f22ef01cSRoman Divacky 581f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 582f22ef01cSRoman Divacky /// specified stmt yet. 583f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 5846122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 585f22ef01cSRoman Divacky "cannot compile this %0 yet"); 586f22ef01cSRoman Divacky std::string Msg = Type; 587f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 588f22ef01cSRoman Divacky << Msg << S->getSourceRange(); 589f22ef01cSRoman Divacky } 590f22ef01cSRoman Divacky 591f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 592f22ef01cSRoman Divacky /// specified decl yet. 593f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 5946122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 595f22ef01cSRoman Divacky "cannot compile this %0 yet"); 596f22ef01cSRoman Divacky std::string Msg = Type; 597f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 598f22ef01cSRoman Divacky } 599f22ef01cSRoman Divacky 60017a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 60117a519f9SDimitry Andric return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 60217a519f9SDimitry Andric } 60317a519f9SDimitry Andric 604f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 6052754fe60SDimitry Andric const NamedDecl *D) const { 606f22ef01cSRoman Divacky // Internal definitions always have default visibility. 607f22ef01cSRoman Divacky if (GV->hasLocalLinkage()) { 608f22ef01cSRoman Divacky GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 609f22ef01cSRoman Divacky return; 610f22ef01cSRoman Divacky } 611f22ef01cSRoman Divacky 6122754fe60SDimitry Andric // Set visibility for definitions. 613139f7f9bSDimitry Andric LinkageInfo LV = D->getLinkageAndVisibility(); 614139f7f9bSDimitry Andric if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 615139f7f9bSDimitry Andric GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 616f22ef01cSRoman Divacky } 617f22ef01cSRoman Divacky 6187ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 6197ae0e2c9SDimitry Andric return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 6207ae0e2c9SDimitry Andric .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 6217ae0e2c9SDimitry Andric .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 6227ae0e2c9SDimitry Andric .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 6237ae0e2c9SDimitry Andric .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 6247ae0e2c9SDimitry Andric } 6257ae0e2c9SDimitry Andric 6267ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 6277ae0e2c9SDimitry Andric CodeGenOptions::TLSModel M) { 6287ae0e2c9SDimitry Andric switch (M) { 6297ae0e2c9SDimitry Andric case CodeGenOptions::GeneralDynamicTLSModel: 6307ae0e2c9SDimitry Andric return llvm::GlobalVariable::GeneralDynamicTLSModel; 6317ae0e2c9SDimitry Andric case CodeGenOptions::LocalDynamicTLSModel: 6327ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalDynamicTLSModel; 6337ae0e2c9SDimitry Andric case CodeGenOptions::InitialExecTLSModel: 6347ae0e2c9SDimitry Andric return llvm::GlobalVariable::InitialExecTLSModel; 6357ae0e2c9SDimitry Andric case CodeGenOptions::LocalExecTLSModel: 6367ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalExecTLSModel; 6377ae0e2c9SDimitry Andric } 6387ae0e2c9SDimitry Andric llvm_unreachable("Invalid TLS model!"); 6397ae0e2c9SDimitry Andric } 6407ae0e2c9SDimitry Andric 64139d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 642284c1978SDimitry Andric assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 6437ae0e2c9SDimitry Andric 64439d628a0SDimitry Andric llvm::GlobalValue::ThreadLocalMode TLM; 6453861d79fSDimitry Andric TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 6467ae0e2c9SDimitry Andric 6477ae0e2c9SDimitry Andric // Override the TLS model if it is explicitly specified. 64859d1ed5bSDimitry Andric if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 6497ae0e2c9SDimitry Andric TLM = GetLLVMTLSModel(Attr->getModel()); 6507ae0e2c9SDimitry Andric } 6517ae0e2c9SDimitry Andric 6527ae0e2c9SDimitry Andric GV->setThreadLocalMode(TLM); 6537ae0e2c9SDimitry Andric } 6547ae0e2c9SDimitry Andric 6556122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 656444ed5c5SDimitry Andric GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 657444ed5c5SDimitry Andric 658444ed5c5SDimitry Andric // Some ABIs don't have constructor variants. Make sure that base and 659444ed5c5SDimitry Andric // complete constructors get mangled the same. 660444ed5c5SDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 661444ed5c5SDimitry Andric if (!getTarget().getCXXABI().hasConstructorVariants()) { 662444ed5c5SDimitry Andric CXXCtorType OrigCtorType = GD.getCtorType(); 663444ed5c5SDimitry Andric assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 664444ed5c5SDimitry Andric if (OrigCtorType == Ctor_Base) 665444ed5c5SDimitry Andric CanonicalGD = GlobalDecl(CD, Ctor_Complete); 666444ed5c5SDimitry Andric } 667444ed5c5SDimitry Andric } 668444ed5c5SDimitry Andric 669444ed5c5SDimitry Andric StringRef &FoundStr = MangledDeclNames[CanonicalGD]; 67059d1ed5bSDimitry Andric if (!FoundStr.empty()) 67159d1ed5bSDimitry Andric return FoundStr; 672f22ef01cSRoman Divacky 67359d1ed5bSDimitry Andric const auto *ND = cast<NamedDecl>(GD.getDecl()); 674dff0c46cSDimitry Andric SmallString<256> Buffer; 67559d1ed5bSDimitry Andric StringRef Str; 67659d1ed5bSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 6772754fe60SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 67859d1ed5bSDimitry Andric if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) 6792754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 68059d1ed5bSDimitry Andric else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) 6812754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 682ffd1746dSEd Schouten else 6832754fe60SDimitry Andric getCXXABI().getMangleContext().mangleName(ND, Out); 68459d1ed5bSDimitry Andric Str = Out.str(); 68559d1ed5bSDimitry Andric } else { 68659d1ed5bSDimitry Andric IdentifierInfo *II = ND->getIdentifier(); 68759d1ed5bSDimitry Andric assert(II && "Attempt to mangle unnamed decl."); 68844290647SDimitry Andric const auto *FD = dyn_cast<FunctionDecl>(ND); 68944290647SDimitry Andric 69044290647SDimitry Andric if (FD && 69144290647SDimitry Andric FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 69244290647SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 69344290647SDimitry Andric Out << "__regcall3__" << II->getName(); 69444290647SDimitry Andric Str = Out.str(); 69544290647SDimitry Andric } else { 69659d1ed5bSDimitry Andric Str = II->getName(); 697ffd1746dSEd Schouten } 69844290647SDimitry Andric } 699ffd1746dSEd Schouten 70039d628a0SDimitry Andric // Keep the first result in the case of a mangling collision. 70139d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Str, GD)); 70239d628a0SDimitry Andric return FoundStr = Result.first->first(); 70359d1ed5bSDimitry Andric } 70459d1ed5bSDimitry Andric 70559d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 706ffd1746dSEd Schouten const BlockDecl *BD) { 7072754fe60SDimitry Andric MangleContext &MangleCtx = getCXXABI().getMangleContext(); 7082754fe60SDimitry Andric const Decl *D = GD.getDecl(); 70959d1ed5bSDimitry Andric 71059d1ed5bSDimitry Andric SmallString<256> Buffer; 71159d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(Buffer); 71259d1ed5bSDimitry Andric if (!D) 7137ae0e2c9SDimitry Andric MangleCtx.mangleGlobalBlock(BD, 7147ae0e2c9SDimitry Andric dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 71559d1ed5bSDimitry Andric else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 7162754fe60SDimitry Andric MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 71759d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 7182754fe60SDimitry Andric MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 7192754fe60SDimitry Andric else 7202754fe60SDimitry Andric MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 72159d1ed5bSDimitry Andric 72239d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 72339d628a0SDimitry Andric return Result.first->first(); 724f22ef01cSRoman Divacky } 725f22ef01cSRoman Divacky 7266122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 727f22ef01cSRoman Divacky return getModule().getNamedValue(Name); 728f22ef01cSRoman Divacky } 729f22ef01cSRoman Divacky 730f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before 731f22ef01cSRoman Divacky /// main() runs. 73259d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 73359d1ed5bSDimitry Andric llvm::Constant *AssociatedData) { 734f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 73559d1ed5bSDimitry Andric GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 736f22ef01cSRoman Divacky } 737f22ef01cSRoman Divacky 738f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called 739f22ef01cSRoman Divacky /// when the module is unloaded. 740f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) { 741f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 74259d1ed5bSDimitry Andric GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 743f22ef01cSRoman Divacky } 744f22ef01cSRoman Divacky 74544290647SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 74644290647SDimitry Andric if (Fns.empty()) return; 74744290647SDimitry Andric 748f22ef01cSRoman Divacky // Ctor function type is void()*. 749bd5abe19SDimitry Andric llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 750f22ef01cSRoman Divacky llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 751f22ef01cSRoman Divacky 75259d1ed5bSDimitry Andric // Get the type of a ctor entry, { i32, void ()*, i8* }. 75359d1ed5bSDimitry Andric llvm::StructType *CtorStructTy = llvm::StructType::get( 7545517e702SDimitry Andric Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy); 755f22ef01cSRoman Divacky 756f22ef01cSRoman Divacky // Construct the constructor and destructor arrays. 75744290647SDimitry Andric ConstantInitBuilder builder(*this); 75844290647SDimitry Andric auto ctors = builder.beginArray(CtorStructTy); 7598f0fd8f6SDimitry Andric for (const auto &I : Fns) { 76044290647SDimitry Andric auto ctor = ctors.beginStruct(CtorStructTy); 76144290647SDimitry Andric ctor.addInt(Int32Ty, I.Priority); 76244290647SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); 76344290647SDimitry Andric if (I.AssociatedData) 76444290647SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); 76544290647SDimitry Andric else 76644290647SDimitry Andric ctor.addNullPointer(VoidPtrTy); 76744290647SDimitry Andric ctor.finishAndAddTo(ctors); 768f22ef01cSRoman Divacky } 769f22ef01cSRoman Divacky 77044290647SDimitry Andric auto list = 77144290647SDimitry Andric ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 77244290647SDimitry Andric /*constant*/ false, 77344290647SDimitry Andric llvm::GlobalValue::AppendingLinkage); 77444290647SDimitry Andric 77544290647SDimitry Andric // The LTO linker doesn't seem to like it when we set an alignment 77644290647SDimitry Andric // on appending variables. Take it off as a workaround. 77744290647SDimitry Andric list->setAlignment(0); 77844290647SDimitry Andric 77944290647SDimitry Andric Fns.clear(); 780f22ef01cSRoman Divacky } 781f22ef01cSRoman Divacky 782f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes 783f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 78459d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 785f785676fSDimitry Andric 786e580952dSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 787f22ef01cSRoman Divacky 78859d1ed5bSDimitry Andric if (isa<CXXDestructorDecl>(D) && 78959d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 79059d1ed5bSDimitry Andric GD.getDtorType())) { 79159d1ed5bSDimitry Andric // Destructor variants in the Microsoft C++ ABI are always internal or 79259d1ed5bSDimitry Andric // linkonce_odr thunks emitted on an as-needed basis. 79359d1ed5bSDimitry Andric return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage 79459d1ed5bSDimitry Andric : llvm::GlobalValue::LinkOnceODRLinkage; 795f22ef01cSRoman Divacky } 796f22ef01cSRoman Divacky 797e7145dcbSDimitry Andric if (isa<CXXConstructorDecl>(D) && 798e7145dcbSDimitry Andric cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 799e7145dcbSDimitry Andric Context.getTargetInfo().getCXXABI().isMicrosoft()) { 800e7145dcbSDimitry Andric // Our approach to inheriting constructors is fundamentally different from 801e7145dcbSDimitry Andric // that used by the MS ABI, so keep our inheriting constructor thunks 802e7145dcbSDimitry Andric // internal rather than trying to pick an unambiguous mangling for them. 803e7145dcbSDimitry Andric return llvm::GlobalValue::InternalLinkage; 804e7145dcbSDimitry Andric } 805e7145dcbSDimitry Andric 80659d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false); 80759d1ed5bSDimitry Andric } 808f22ef01cSRoman Divacky 80997bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) { 81097bc6c73SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 81197bc6c73SDimitry Andric 81297bc6c73SDimitry Andric if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) { 81397bc6c73SDimitry Andric if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) { 81497bc6c73SDimitry Andric // Don't dllexport/import destructor thunks. 81597bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 81697bc6c73SDimitry Andric return; 81797bc6c73SDimitry Andric } 81897bc6c73SDimitry Andric } 81997bc6c73SDimitry Andric 82097bc6c73SDimitry Andric if (FD->hasAttr<DLLImportAttr>()) 82197bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 82297bc6c73SDimitry Andric else if (FD->hasAttr<DLLExportAttr>()) 82397bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 82497bc6c73SDimitry Andric else 82597bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 82697bc6c73SDimitry Andric } 82797bc6c73SDimitry Andric 828e7145dcbSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 8290623d748SDimitry Andric llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 8300623d748SDimitry Andric if (!MDS) return nullptr; 8310623d748SDimitry Andric 83244290647SDimitry Andric return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 8330623d748SDimitry Andric } 8340623d748SDimitry Andric 83559d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D, 83659d1ed5bSDimitry Andric llvm::Function *F) { 83759d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 838f22ef01cSRoman Divacky } 839f22ef01cSRoman Divacky 840f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 841f22ef01cSRoman Divacky const CGFunctionInfo &Info, 842f22ef01cSRoman Divacky llvm::Function *F) { 843f22ef01cSRoman Divacky unsigned CallingConv; 8446bc11b14SDimitry Andric llvm::AttributeList PAL; 8456bc11b14SDimitry Andric ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false); 8466bc11b14SDimitry Andric F->setAttributes(PAL); 847f22ef01cSRoman Divacky F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 848f22ef01cSRoman Divacky } 849f22ef01cSRoman Divacky 8506122f3e6SDimitry Andric /// Determines whether the language options require us to model 8516122f3e6SDimitry Andric /// unwind exceptions. We treat -fexceptions as mandating this 8526122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions 8536122f3e6SDimitry Andric /// enabled. This means, for example, that C with -fexceptions 8546122f3e6SDimitry Andric /// enables this. 855dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) { 8566122f3e6SDimitry Andric // If exceptions are completely disabled, obviously this is false. 857dff0c46cSDimitry Andric if (!LangOpts.Exceptions) return false; 8586122f3e6SDimitry Andric 8596122f3e6SDimitry Andric // If C++ exceptions are enabled, this is true. 860dff0c46cSDimitry Andric if (LangOpts.CXXExceptions) return true; 8616122f3e6SDimitry Andric 8626122f3e6SDimitry Andric // If ObjC exceptions are enabled, this depends on the ABI. 863dff0c46cSDimitry Andric if (LangOpts.ObjCExceptions) { 8647ae0e2c9SDimitry Andric return LangOpts.ObjCRuntime.hasUnwindExceptions(); 8656122f3e6SDimitry Andric } 8666122f3e6SDimitry Andric 8676122f3e6SDimitry Andric return true; 8686122f3e6SDimitry Andric } 8696122f3e6SDimitry Andric 870f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 871f22ef01cSRoman Divacky llvm::Function *F) { 872f785676fSDimitry Andric llvm::AttrBuilder B; 873f785676fSDimitry Andric 874bd5abe19SDimitry Andric if (CodeGenOpts.UnwindTables) 875f785676fSDimitry Andric B.addAttribute(llvm::Attribute::UWTable); 876bd5abe19SDimitry Andric 877dff0c46cSDimitry Andric if (!hasUnwindExceptions(LangOpts)) 878f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoUnwind); 879f22ef01cSRoman Divacky 8800623d748SDimitry Andric if (LangOpts.getStackProtector() == LangOptions::SSPOn) 8810623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtect); 8820623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 8830623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 8840623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 8850623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectReq); 8860623d748SDimitry Andric 8870623d748SDimitry Andric if (!D) { 88844290647SDimitry Andric // If we don't have a declaration to control inlining, the function isn't 88944290647SDimitry Andric // explicitly marked as alwaysinline for semantic reasons, and inlining is 89044290647SDimitry Andric // disabled, mark the function as noinline. 89144290647SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 89244290647SDimitry Andric CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 89344290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 89444290647SDimitry Andric 895f37b6182SDimitry Andric F->addAttributes(llvm::AttributeList::FunctionIndex, B); 8960623d748SDimitry Andric return; 8970623d748SDimitry Andric } 8980623d748SDimitry Andric 89944290647SDimitry Andric if (D->hasAttr<OptimizeNoneAttr>()) { 90044290647SDimitry Andric B.addAttribute(llvm::Attribute::OptimizeNone); 90144290647SDimitry Andric 90244290647SDimitry Andric // OptimizeNone implies noinline; we should not be inlining such functions. 90344290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 90444290647SDimitry Andric assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 90544290647SDimitry Andric "OptimizeNone and AlwaysInline on same function!"); 90644290647SDimitry Andric 90744290647SDimitry Andric // We still need to handle naked functions even though optnone subsumes 90844290647SDimitry Andric // much of their semantics. 90944290647SDimitry Andric if (D->hasAttr<NakedAttr>()) 91044290647SDimitry Andric B.addAttribute(llvm::Attribute::Naked); 91144290647SDimitry Andric 91244290647SDimitry Andric // OptimizeNone wins over OptimizeForSize and MinSize. 91344290647SDimitry Andric F->removeFnAttr(llvm::Attribute::OptimizeForSize); 91444290647SDimitry Andric F->removeFnAttr(llvm::Attribute::MinSize); 91544290647SDimitry Andric } else if (D->hasAttr<NakedAttr>()) { 9166122f3e6SDimitry Andric // Naked implies noinline: we should not be inlining such functions. 917f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Naked); 918f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 91959d1ed5bSDimitry Andric } else if (D->hasAttr<NoDuplicateAttr>()) { 92059d1ed5bSDimitry Andric B.addAttribute(llvm::Attribute::NoDuplicate); 921f785676fSDimitry Andric } else if (D->hasAttr<NoInlineAttr>()) { 922f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 92359d1ed5bSDimitry Andric } else if (D->hasAttr<AlwaysInlineAttr>() && 92444290647SDimitry Andric !F->hasFnAttribute(llvm::Attribute::NoInline)) { 925f785676fSDimitry Andric // (noinline wins over always_inline, and we can't specify both in IR) 926f785676fSDimitry Andric B.addAttribute(llvm::Attribute::AlwaysInline); 92744290647SDimitry Andric } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 92844290647SDimitry Andric // If we're not inlining, then force everything that isn't always_inline to 92944290647SDimitry Andric // carry an explicit noinline attribute. 93044290647SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 93144290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 93244290647SDimitry Andric } else { 93344290647SDimitry Andric // Otherwise, propagate the inline hint attribute and potentially use its 93444290647SDimitry Andric // absence to mark things as noinline. 93544290647SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) { 93644290647SDimitry Andric if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) { 93744290647SDimitry Andric return Redecl->isInlineSpecified(); 93844290647SDimitry Andric })) { 93944290647SDimitry Andric B.addAttribute(llvm::Attribute::InlineHint); 94044290647SDimitry Andric } else if (CodeGenOpts.getInlining() == 94144290647SDimitry Andric CodeGenOptions::OnlyHintInlining && 94244290647SDimitry Andric !FD->isInlined() && 94344290647SDimitry Andric !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 94444290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 94544290647SDimitry Andric } 94644290647SDimitry Andric } 9476122f3e6SDimitry Andric } 9482754fe60SDimitry Andric 94944290647SDimitry Andric // Add other optimization related attributes if we are optimizing this 95044290647SDimitry Andric // function. 95144290647SDimitry Andric if (!D->hasAttr<OptimizeNoneAttr>()) { 952f785676fSDimitry Andric if (D->hasAttr<ColdAttr>()) { 953f785676fSDimitry Andric B.addAttribute(llvm::Attribute::OptimizeForSize); 954f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Cold); 955f785676fSDimitry Andric } 9563861d79fSDimitry Andric 9573861d79fSDimitry Andric if (D->hasAttr<MinSizeAttr>()) 958f785676fSDimitry Andric B.addAttribute(llvm::Attribute::MinSize); 95944290647SDimitry Andric } 960f22ef01cSRoman Divacky 961f37b6182SDimitry Andric F->addAttributes(llvm::AttributeList::FunctionIndex, B); 962f785676fSDimitry Andric 963e580952dSDimitry Andric unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 964e580952dSDimitry Andric if (alignment) 965e580952dSDimitry Andric F->setAlignment(alignment); 966e580952dSDimitry Andric 9670623d748SDimitry Andric // Some C++ ABIs require 2-byte alignment for member functions, in order to 9680623d748SDimitry Andric // reserve a bit for differentiating between virtual and non-virtual member 9690623d748SDimitry Andric // functions. If the current target's C++ ABI requires this and this is a 9700623d748SDimitry Andric // member function, set its alignment accordingly. 9710623d748SDimitry Andric if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 972f22ef01cSRoman Divacky if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 973f22ef01cSRoman Divacky F->setAlignment(2); 974f22ef01cSRoman Divacky } 97544290647SDimitry Andric 97644290647SDimitry Andric // In the cross-dso CFI mode, we want !type attributes on definitions only. 97744290647SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 97844290647SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) 97944290647SDimitry Andric CreateFunctionTypeMetadata(FD, F); 9800623d748SDimitry Andric } 981f22ef01cSRoman Divacky 982f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D, 983f22ef01cSRoman Divacky llvm::GlobalValue *GV) { 9840623d748SDimitry Andric if (const auto *ND = dyn_cast_or_null<NamedDecl>(D)) 9852754fe60SDimitry Andric setGlobalVisibility(GV, ND); 9862754fe60SDimitry Andric else 9872754fe60SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 988f22ef01cSRoman Divacky 9890623d748SDimitry Andric if (D && D->hasAttr<UsedAttr>()) 99059d1ed5bSDimitry Andric addUsedGlobal(GV); 99159d1ed5bSDimitry Andric } 99259d1ed5bSDimitry Andric 99339d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D, 99439d628a0SDimitry Andric llvm::GlobalValue *GV) { 99539d628a0SDimitry Andric SetCommonAttributes(D, GV); 99639d628a0SDimitry Andric 99739d628a0SDimitry Andric // Process the dllexport attribute based on whether the original definition 99839d628a0SDimitry Andric // (not necessarily the aliasee) was exported. 99939d628a0SDimitry Andric if (D->hasAttr<DLLExportAttr>()) 100039d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 100139d628a0SDimitry Andric } 100239d628a0SDimitry Andric 100359d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D, 100459d1ed5bSDimitry Andric llvm::GlobalObject *GO) { 100559d1ed5bSDimitry Andric SetCommonAttributes(D, GO); 1006f22ef01cSRoman Divacky 10070623d748SDimitry Andric if (D) 1008f22ef01cSRoman Divacky if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 100959d1ed5bSDimitry Andric GO->setSection(SA->getName()); 1010f22ef01cSRoman Divacky 101197bc6c73SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 1012f22ef01cSRoman Divacky } 1013f22ef01cSRoman Divacky 1014f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 1015f22ef01cSRoman Divacky llvm::Function *F, 1016f22ef01cSRoman Divacky const CGFunctionInfo &FI) { 1017f22ef01cSRoman Divacky SetLLVMFunctionAttributes(D, FI, F); 1018f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, F); 1019f22ef01cSRoman Divacky 1020f22ef01cSRoman Divacky F->setLinkage(llvm::Function::InternalLinkage); 1021f22ef01cSRoman Divacky 102259d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 102359d1ed5bSDimitry Andric } 102459d1ed5bSDimitry Andric 102559d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, 102659d1ed5bSDimitry Andric const NamedDecl *ND) { 102759d1ed5bSDimitry Andric // Set linkage and visibility in case we never see a definition. 102859d1ed5bSDimitry Andric LinkageInfo LV = ND->getLinkageAndVisibility(); 102959d1ed5bSDimitry Andric if (LV.getLinkage() != ExternalLinkage) { 103059d1ed5bSDimitry Andric // Don't set internal linkage on declarations. 103159d1ed5bSDimitry Andric } else { 103259d1ed5bSDimitry Andric if (ND->hasAttr<DLLImportAttr>()) { 103359d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 103459d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 103559d1ed5bSDimitry Andric } else if (ND->hasAttr<DLLExportAttr>()) { 103659d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 103759d1ed5bSDimitry Andric } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 103859d1ed5bSDimitry Andric // "extern_weak" is overloaded in LLVM; we probably should have 103959d1ed5bSDimitry Andric // separate linkage types for this. 104059d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 104159d1ed5bSDimitry Andric } 104259d1ed5bSDimitry Andric 104359d1ed5bSDimitry Andric // Set visibility on a declaration only if it's explicit. 104459d1ed5bSDimitry Andric if (LV.isVisibilityExplicit()) 104559d1ed5bSDimitry Andric GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility())); 104659d1ed5bSDimitry Andric } 1047f22ef01cSRoman Divacky } 1048f22ef01cSRoman Divacky 1049e7145dcbSDimitry Andric void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD, 10500623d748SDimitry Andric llvm::Function *F) { 10510623d748SDimitry Andric // Only if we are checking indirect calls. 10520623d748SDimitry Andric if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 10530623d748SDimitry Andric return; 10540623d748SDimitry Andric 10550623d748SDimitry Andric // Non-static class methods are handled via vtable pointer checks elsewhere. 10560623d748SDimitry Andric if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 10570623d748SDimitry Andric return; 10580623d748SDimitry Andric 10590623d748SDimitry Andric // Additionally, if building with cross-DSO support... 10600623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 10610623d748SDimitry Andric // Skip available_externally functions. They won't be codegen'ed in the 10620623d748SDimitry Andric // current module anyway. 10630623d748SDimitry Andric if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally) 10640623d748SDimitry Andric return; 10650623d748SDimitry Andric } 10660623d748SDimitry Andric 10670623d748SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 1068e7145dcbSDimitry Andric F->addTypeMetadata(0, MD); 10690623d748SDimitry Andric 10700623d748SDimitry Andric // Emit a hash-based bit set entry for cross-DSO calls. 1071e7145dcbSDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 1072e7145dcbSDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 1073e7145dcbSDimitry Andric F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 10740623d748SDimitry Andric } 10750623d748SDimitry Andric 107639d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 107739d628a0SDimitry Andric bool IsIncompleteFunction, 107839d628a0SDimitry Andric bool IsThunk) { 107933956c43SDimitry Andric if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 10803b0f4066SDimitry Andric // If this is an intrinsic function, set the function's attributes 10813b0f4066SDimitry Andric // to the intrinsic's attributes. 108233956c43SDimitry Andric F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 10833b0f4066SDimitry Andric return; 10843b0f4066SDimitry Andric } 10853b0f4066SDimitry Andric 108659d1ed5bSDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1087f22ef01cSRoman Divacky 1088f22ef01cSRoman Divacky if (!IsIncompleteFunction) 1089dff0c46cSDimitry Andric SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 1090f22ef01cSRoman Divacky 109159d1ed5bSDimitry Andric // Add the Returned attribute for "this", except for iOS 5 and earlier 109259d1ed5bSDimitry Andric // where substantial code, including the libstdc++ dylib, was compiled with 109359d1ed5bSDimitry Andric // GCC and does not actually return "this". 109439d628a0SDimitry Andric if (!IsThunk && getCXXABI().HasThisReturn(GD) && 109544290647SDimitry Andric !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 1096f785676fSDimitry Andric assert(!F->arg_empty() && 1097f785676fSDimitry Andric F->arg_begin()->getType() 1098f785676fSDimitry Andric ->canLosslesslyBitCastTo(F->getReturnType()) && 1099f785676fSDimitry Andric "unexpected this return"); 1100f785676fSDimitry Andric F->addAttribute(1, llvm::Attribute::Returned); 1101f785676fSDimitry Andric } 1102f785676fSDimitry Andric 1103f22ef01cSRoman Divacky // Only a few attributes are set on declarations; these may later be 1104f22ef01cSRoman Divacky // overridden by a definition. 1105f22ef01cSRoman Divacky 110659d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(F, FD); 11072754fe60SDimitry Andric 1108f22ef01cSRoman Divacky if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 1109f22ef01cSRoman Divacky F->setSection(SA->getName()); 1110f785676fSDimitry Andric 1111e7145dcbSDimitry Andric if (FD->isReplaceableGlobalAllocationFunction()) { 1112f785676fSDimitry Andric // A replaceable global allocation function does not act like a builtin by 1113f785676fSDimitry Andric // default, only if it is invoked by a new-expression or delete-expression. 111420e90f04SDimitry Andric F->addAttribute(llvm::AttributeList::FunctionIndex, 1115f785676fSDimitry Andric llvm::Attribute::NoBuiltin); 11160623d748SDimitry Andric 1117e7145dcbSDimitry Andric // A sane operator new returns a non-aliasing pointer. 1118e7145dcbSDimitry Andric // FIXME: Also add NonNull attribute to the return value 1119e7145dcbSDimitry Andric // for the non-nothrow forms? 1120e7145dcbSDimitry Andric auto Kind = FD->getDeclName().getCXXOverloadedOperator(); 1121e7145dcbSDimitry Andric if (getCodeGenOpts().AssumeSaneOperatorNew && 1122e7145dcbSDimitry Andric (Kind == OO_New || Kind == OO_Array_New)) 112320e90f04SDimitry Andric F->addAttribute(llvm::AttributeList::ReturnIndex, 1124e7145dcbSDimitry Andric llvm::Attribute::NoAlias); 1125e7145dcbSDimitry Andric } 1126e7145dcbSDimitry Andric 1127e7145dcbSDimitry Andric if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 1128e7145dcbSDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1129e7145dcbSDimitry Andric else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 1130e7145dcbSDimitry Andric if (MD->isVirtual()) 1131e7145dcbSDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1132e7145dcbSDimitry Andric 113344290647SDimitry Andric // Don't emit entries for function declarations in the cross-DSO mode. This 113444290647SDimitry Andric // is handled with better precision by the receiving DSO. 113544290647SDimitry Andric if (!CodeGenOpts.SanitizeCfiCrossDso) 1136e7145dcbSDimitry Andric CreateFunctionTypeMetadata(FD, F); 1137f22ef01cSRoman Divacky } 1138f22ef01cSRoman Divacky 113959d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 1140f22ef01cSRoman Divacky assert(!GV->isDeclaration() && 1141f22ef01cSRoman Divacky "Only globals with definition can force usage."); 114297bc6c73SDimitry Andric LLVMUsed.emplace_back(GV); 1143f22ef01cSRoman Divacky } 1144f22ef01cSRoman Divacky 114559d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 114659d1ed5bSDimitry Andric assert(!GV->isDeclaration() && 114759d1ed5bSDimitry Andric "Only globals with definition can force usage."); 114897bc6c73SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 114959d1ed5bSDimitry Andric } 115059d1ed5bSDimitry Andric 115159d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name, 1152f37b6182SDimitry Andric std::vector<llvm::WeakTrackingVH> &List) { 1153f22ef01cSRoman Divacky // Don't create llvm.used if there is no need. 115459d1ed5bSDimitry Andric if (List.empty()) 1155f22ef01cSRoman Divacky return; 1156f22ef01cSRoman Divacky 115759d1ed5bSDimitry Andric // Convert List to what ConstantArray needs. 1158dff0c46cSDimitry Andric SmallVector<llvm::Constant*, 8> UsedArray; 115959d1ed5bSDimitry Andric UsedArray.resize(List.size()); 116059d1ed5bSDimitry Andric for (unsigned i = 0, e = List.size(); i != e; ++i) { 1161f22ef01cSRoman Divacky UsedArray[i] = 116244f7b0dcSDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 116344f7b0dcSDimitry Andric cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 1164f22ef01cSRoman Divacky } 1165f22ef01cSRoman Divacky 1166f22ef01cSRoman Divacky if (UsedArray.empty()) 1167f22ef01cSRoman Divacky return; 116859d1ed5bSDimitry Andric llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 1169f22ef01cSRoman Divacky 117059d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 117159d1ed5bSDimitry Andric CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 117259d1ed5bSDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), Name); 1173f22ef01cSRoman Divacky 1174f22ef01cSRoman Divacky GV->setSection("llvm.metadata"); 1175f22ef01cSRoman Divacky } 1176f22ef01cSRoman Divacky 117759d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() { 117859d1ed5bSDimitry Andric emitUsed(*this, "llvm.used", LLVMUsed); 117959d1ed5bSDimitry Andric emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 118059d1ed5bSDimitry Andric } 118159d1ed5bSDimitry Andric 1182f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 118339d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 1184f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1185f785676fSDimitry Andric } 1186f785676fSDimitry Andric 1187f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 1188f785676fSDimitry Andric llvm::SmallString<32> Opt; 1189f785676fSDimitry Andric getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 119039d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1191f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1192f785676fSDimitry Andric } 1193f785676fSDimitry Andric 1194f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) { 1195f785676fSDimitry Andric llvm::SmallString<24> Opt; 1196f785676fSDimitry Andric getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 119739d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1198f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1199f785676fSDimitry Andric } 1200f785676fSDimitry Andric 1201139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules 1202139f7f9bSDimitry Andric /// it depends on, using a postorder walk. 120339d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 120439d628a0SDimitry Andric SmallVectorImpl<llvm::Metadata *> &Metadata, 1205139f7f9bSDimitry Andric llvm::SmallPtrSet<Module *, 16> &Visited) { 1206139f7f9bSDimitry Andric // Import this module's parent. 120739d628a0SDimitry Andric if (Mod->Parent && Visited.insert(Mod->Parent).second) { 1208f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 1209139f7f9bSDimitry Andric } 1210139f7f9bSDimitry Andric 1211139f7f9bSDimitry Andric // Import this module's dependencies. 1212139f7f9bSDimitry Andric for (unsigned I = Mod->Imports.size(); I > 0; --I) { 121339d628a0SDimitry Andric if (Visited.insert(Mod->Imports[I - 1]).second) 1214f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 1215139f7f9bSDimitry Andric } 1216139f7f9bSDimitry Andric 1217139f7f9bSDimitry Andric // Add linker options to link against the libraries/frameworks 1218139f7f9bSDimitry Andric // described by this module. 1219f785676fSDimitry Andric llvm::LLVMContext &Context = CGM.getLLVMContext(); 1220139f7f9bSDimitry Andric for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 1221f785676fSDimitry Andric // Link against a framework. Frameworks are currently Darwin only, so we 1222f785676fSDimitry Andric // don't to ask TargetCodeGenInfo for the spelling of the linker option. 1223139f7f9bSDimitry Andric if (Mod->LinkLibraries[I-1].IsFramework) { 122439d628a0SDimitry Andric llvm::Metadata *Args[2] = { 1225139f7f9bSDimitry Andric llvm::MDString::get(Context, "-framework"), 122639d628a0SDimitry Andric llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 1227139f7f9bSDimitry Andric 1228139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 1229139f7f9bSDimitry Andric continue; 1230139f7f9bSDimitry Andric } 1231139f7f9bSDimitry Andric 1232139f7f9bSDimitry Andric // Link against a library. 1233f785676fSDimitry Andric llvm::SmallString<24> Opt; 1234f785676fSDimitry Andric CGM.getTargetCodeGenInfo().getDependentLibraryOption( 1235f785676fSDimitry Andric Mod->LinkLibraries[I-1].Library, Opt); 123639d628a0SDimitry Andric auto *OptString = llvm::MDString::get(Context, Opt); 1237139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, OptString)); 1238139f7f9bSDimitry Andric } 1239139f7f9bSDimitry Andric } 1240139f7f9bSDimitry Andric 1241139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() { 1242139f7f9bSDimitry Andric // Collect the set of all of the modules we want to visit to emit link 1243139f7f9bSDimitry Andric // options, which is essentially the imported modules and all of their 1244139f7f9bSDimitry Andric // non-explicit child modules. 1245139f7f9bSDimitry Andric llvm::SetVector<clang::Module *> LinkModules; 1246139f7f9bSDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 1247139f7f9bSDimitry Andric SmallVector<clang::Module *, 16> Stack; 1248139f7f9bSDimitry Andric 1249139f7f9bSDimitry Andric // Seed the stack with imported modules. 1250f1a29dd3SDimitry Andric for (Module *M : ImportedModules) { 1251f1a29dd3SDimitry Andric // Do not add any link flags when an implementation TU of a module imports 1252f1a29dd3SDimitry Andric // a header of that same module. 1253f1a29dd3SDimitry Andric if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 1254f1a29dd3SDimitry Andric !getLangOpts().isCompilingModule()) 1255f1a29dd3SDimitry Andric continue; 12568f0fd8f6SDimitry Andric if (Visited.insert(M).second) 12578f0fd8f6SDimitry Andric Stack.push_back(M); 1258f1a29dd3SDimitry Andric } 1259139f7f9bSDimitry Andric 1260139f7f9bSDimitry Andric // Find all of the modules to import, making a little effort to prune 1261139f7f9bSDimitry Andric // non-leaf modules. 1262139f7f9bSDimitry Andric while (!Stack.empty()) { 1263f785676fSDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 1264139f7f9bSDimitry Andric 1265139f7f9bSDimitry Andric bool AnyChildren = false; 1266139f7f9bSDimitry Andric 1267139f7f9bSDimitry Andric // Visit the submodules of this module. 1268139f7f9bSDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 1269139f7f9bSDimitry Andric SubEnd = Mod->submodule_end(); 1270139f7f9bSDimitry Andric Sub != SubEnd; ++Sub) { 1271139f7f9bSDimitry Andric // Skip explicit children; they need to be explicitly imported to be 1272139f7f9bSDimitry Andric // linked against. 1273139f7f9bSDimitry Andric if ((*Sub)->IsExplicit) 1274139f7f9bSDimitry Andric continue; 1275139f7f9bSDimitry Andric 127639d628a0SDimitry Andric if (Visited.insert(*Sub).second) { 1277139f7f9bSDimitry Andric Stack.push_back(*Sub); 1278139f7f9bSDimitry Andric AnyChildren = true; 1279139f7f9bSDimitry Andric } 1280139f7f9bSDimitry Andric } 1281139f7f9bSDimitry Andric 1282139f7f9bSDimitry Andric // We didn't find any children, so add this module to the list of 1283139f7f9bSDimitry Andric // modules to link against. 1284139f7f9bSDimitry Andric if (!AnyChildren) { 1285139f7f9bSDimitry Andric LinkModules.insert(Mod); 1286139f7f9bSDimitry Andric } 1287139f7f9bSDimitry Andric } 1288139f7f9bSDimitry Andric 1289139f7f9bSDimitry Andric // Add link options for all of the imported modules in reverse topological 1290f785676fSDimitry Andric // order. We don't do anything to try to order import link flags with respect 1291f785676fSDimitry Andric // to linker options inserted by things like #pragma comment(). 129239d628a0SDimitry Andric SmallVector<llvm::Metadata *, 16> MetadataArgs; 1293139f7f9bSDimitry Andric Visited.clear(); 12948f0fd8f6SDimitry Andric for (Module *M : LinkModules) 12958f0fd8f6SDimitry Andric if (Visited.insert(M).second) 12968f0fd8f6SDimitry Andric addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 1297139f7f9bSDimitry Andric std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 1298f785676fSDimitry Andric LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 1299139f7f9bSDimitry Andric 1300139f7f9bSDimitry Andric // Add the linker options metadata flag. 1301139f7f9bSDimitry Andric getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options", 1302f785676fSDimitry Andric llvm::MDNode::get(getLLVMContext(), 1303f785676fSDimitry Andric LinkerOptionsMetadata)); 1304139f7f9bSDimitry Andric } 1305139f7f9bSDimitry Andric 1306f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() { 1307f22ef01cSRoman Divacky // Emit code for any potentially referenced deferred decls. Since a 1308f22ef01cSRoman Divacky // previously unused static decl may become used during the generation of code 1309f22ef01cSRoman Divacky // for a static function, iterate until no changes are made. 1310f22ef01cSRoman Divacky 1311f22ef01cSRoman Divacky if (!DeferredVTables.empty()) { 1312139f7f9bSDimitry Andric EmitDeferredVTables(); 1313139f7f9bSDimitry Andric 1314e7145dcbSDimitry Andric // Emitting a vtable doesn't directly cause more vtables to 1315139f7f9bSDimitry Andric // become deferred, although it can cause functions to be 1316e7145dcbSDimitry Andric // emitted that then need those vtables. 1317139f7f9bSDimitry Andric assert(DeferredVTables.empty()); 1318f22ef01cSRoman Divacky } 1319f22ef01cSRoman Divacky 1320e7145dcbSDimitry Andric // Stop if we're out of both deferred vtables and deferred declarations. 132133956c43SDimitry Andric if (DeferredDeclsToEmit.empty()) 132233956c43SDimitry Andric return; 1323139f7f9bSDimitry Andric 132433956c43SDimitry Andric // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 132533956c43SDimitry Andric // work, it will not interfere with this. 1326f37b6182SDimitry Andric std::vector<GlobalDecl> CurDeclsToEmit; 132733956c43SDimitry Andric CurDeclsToEmit.swap(DeferredDeclsToEmit); 132833956c43SDimitry Andric 1329f37b6182SDimitry Andric for (GlobalDecl &D : CurDeclsToEmit) { 13300623d748SDimitry Andric // We should call GetAddrOfGlobal with IsForDefinition set to true in order 13310623d748SDimitry Andric // to get GlobalValue with exactly the type we need, not something that 13320623d748SDimitry Andric // might had been created for another decl with the same mangled name but 13330623d748SDimitry Andric // different type. 1334e7145dcbSDimitry Andric llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 133544290647SDimitry Andric GetAddrOfGlobal(D, ForDefinition)); 1336e7145dcbSDimitry Andric 1337e7145dcbSDimitry Andric // In case of different address spaces, we may still get a cast, even with 1338e7145dcbSDimitry Andric // IsForDefinition equal to true. Query mangled names table to get 1339e7145dcbSDimitry Andric // GlobalValue. 134039d628a0SDimitry Andric if (!GV) 134139d628a0SDimitry Andric GV = GetGlobalValue(getMangledName(D)); 134239d628a0SDimitry Andric 1343e7145dcbSDimitry Andric // Make sure GetGlobalValue returned non-null. 1344e7145dcbSDimitry Andric assert(GV); 1345e7145dcbSDimitry Andric 1346f22ef01cSRoman Divacky // Check to see if we've already emitted this. This is necessary 1347f22ef01cSRoman Divacky // for a couple of reasons: first, decls can end up in the 1348f22ef01cSRoman Divacky // deferred-decls queue multiple times, and second, decls can end 1349f22ef01cSRoman Divacky // up with definitions in unusual ways (e.g. by an extern inline 1350f22ef01cSRoman Divacky // function acquiring a strong function redefinition). Just 1351f22ef01cSRoman Divacky // ignore these cases. 1352e7145dcbSDimitry Andric if (!GV->isDeclaration()) 1353f22ef01cSRoman Divacky continue; 1354f22ef01cSRoman Divacky 1355f22ef01cSRoman Divacky // Otherwise, emit the definition and move on to the next one. 135659d1ed5bSDimitry Andric EmitGlobalDefinition(D, GV); 135733956c43SDimitry Andric 135833956c43SDimitry Andric // If we found out that we need to emit more decls, do that recursively. 135933956c43SDimitry Andric // This has the advantage that the decls are emitted in a DFS and related 136033956c43SDimitry Andric // ones are close together, which is convenient for testing. 136133956c43SDimitry Andric if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 136233956c43SDimitry Andric EmitDeferred(); 136333956c43SDimitry Andric assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 136433956c43SDimitry Andric } 1365f22ef01cSRoman Divacky } 1366f22ef01cSRoman Divacky } 1367f22ef01cSRoman Divacky 13686122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() { 13696122f3e6SDimitry Andric if (Annotations.empty()) 13706122f3e6SDimitry Andric return; 13716122f3e6SDimitry Andric 13726122f3e6SDimitry Andric // Create a new global variable for the ConstantStruct in the Module. 13736122f3e6SDimitry Andric llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 13746122f3e6SDimitry Andric Annotations[0]->getType(), Annotations.size()), Annotations); 137559d1ed5bSDimitry Andric auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 137659d1ed5bSDimitry Andric llvm::GlobalValue::AppendingLinkage, 137759d1ed5bSDimitry Andric Array, "llvm.global.annotations"); 13786122f3e6SDimitry Andric gv->setSection(AnnotationSection); 13796122f3e6SDimitry Andric } 13806122f3e6SDimitry Andric 1381139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1382f785676fSDimitry Andric llvm::Constant *&AStr = AnnotationStrings[Str]; 1383f785676fSDimitry Andric if (AStr) 1384f785676fSDimitry Andric return AStr; 13856122f3e6SDimitry Andric 13866122f3e6SDimitry Andric // Not found yet, create a new global. 1387dff0c46cSDimitry Andric llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 138859d1ed5bSDimitry Andric auto *gv = 138959d1ed5bSDimitry Andric new llvm::GlobalVariable(getModule(), s->getType(), true, 139059d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, s, ".str"); 13916122f3e6SDimitry Andric gv->setSection(AnnotationSection); 1392e7145dcbSDimitry Andric gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1393f785676fSDimitry Andric AStr = gv; 13946122f3e6SDimitry Andric return gv; 13956122f3e6SDimitry Andric } 13966122f3e6SDimitry Andric 13976122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 13986122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 13996122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(Loc); 14006122f3e6SDimitry Andric if (PLoc.isValid()) 14016122f3e6SDimitry Andric return EmitAnnotationString(PLoc.getFilename()); 14026122f3e6SDimitry Andric return EmitAnnotationString(SM.getBufferName(Loc)); 14036122f3e6SDimitry Andric } 14046122f3e6SDimitry Andric 14056122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 14066122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 14076122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(L); 14086122f3e6SDimitry Andric unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 14096122f3e6SDimitry Andric SM.getExpansionLineNumber(L); 14106122f3e6SDimitry Andric return llvm::ConstantInt::get(Int32Ty, LineNo); 14116122f3e6SDimitry Andric } 14126122f3e6SDimitry Andric 1413f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1414f22ef01cSRoman Divacky const AnnotateAttr *AA, 14156122f3e6SDimitry Andric SourceLocation L) { 14166122f3e6SDimitry Andric // Get the globals for file name, annotation, and the line number. 14176122f3e6SDimitry Andric llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 14186122f3e6SDimitry Andric *UnitGV = EmitAnnotationUnit(L), 14196122f3e6SDimitry Andric *LineNoCst = EmitAnnotationLineNo(L); 1420f22ef01cSRoman Divacky 1421f22ef01cSRoman Divacky // Create the ConstantStruct for the global annotation. 1422f22ef01cSRoman Divacky llvm::Constant *Fields[4] = { 14236122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 14246122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 14256122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 14266122f3e6SDimitry Andric LineNoCst 1427f22ef01cSRoman Divacky }; 142817a519f9SDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 1429f22ef01cSRoman Divacky } 1430f22ef01cSRoman Divacky 14316122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 14326122f3e6SDimitry Andric llvm::GlobalValue *GV) { 14336122f3e6SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 14346122f3e6SDimitry Andric // Get the struct elements for these annotations. 143559d1ed5bSDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 143659d1ed5bSDimitry Andric Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 14376122f3e6SDimitry Andric } 14386122f3e6SDimitry Andric 143939d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn, 144039d628a0SDimitry Andric SourceLocation Loc) const { 144139d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 144239d628a0SDimitry Andric // Blacklist by function name. 144339d628a0SDimitry Andric if (SanitizerBL.isBlacklistedFunction(Fn->getName())) 144439d628a0SDimitry Andric return true; 144539d628a0SDimitry Andric // Blacklist by location. 14460623d748SDimitry Andric if (Loc.isValid()) 144739d628a0SDimitry Andric return SanitizerBL.isBlacklistedLocation(Loc); 144839d628a0SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 144939d628a0SDimitry Andric // it's located in the main file. 145039d628a0SDimitry Andric auto &SM = Context.getSourceManager(); 145139d628a0SDimitry Andric if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 145239d628a0SDimitry Andric return SanitizerBL.isBlacklistedFile(MainFile->getName()); 145339d628a0SDimitry Andric } 145439d628a0SDimitry Andric return false; 145539d628a0SDimitry Andric } 145639d628a0SDimitry Andric 145739d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 145839d628a0SDimitry Andric SourceLocation Loc, QualType Ty, 145939d628a0SDimitry Andric StringRef Category) const { 14608f0fd8f6SDimitry Andric // For now globals can be blacklisted only in ASan and KASan. 14618f0fd8f6SDimitry Andric if (!LangOpts.Sanitize.hasOneOf( 14628f0fd8f6SDimitry Andric SanitizerKind::Address | SanitizerKind::KernelAddress)) 146339d628a0SDimitry Andric return false; 146439d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 146539d628a0SDimitry Andric if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category)) 146639d628a0SDimitry Andric return true; 146739d628a0SDimitry Andric if (SanitizerBL.isBlacklistedLocation(Loc, Category)) 146839d628a0SDimitry Andric return true; 146939d628a0SDimitry Andric // Check global type. 147039d628a0SDimitry Andric if (!Ty.isNull()) { 147139d628a0SDimitry Andric // Drill down the array types: if global variable of a fixed type is 147239d628a0SDimitry Andric // blacklisted, we also don't instrument arrays of them. 147339d628a0SDimitry Andric while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 147439d628a0SDimitry Andric Ty = AT->getElementType(); 147539d628a0SDimitry Andric Ty = Ty.getCanonicalType().getUnqualifiedType(); 147639d628a0SDimitry Andric // We allow to blacklist only record types (classes, structs etc.) 147739d628a0SDimitry Andric if (Ty->isRecordType()) { 147839d628a0SDimitry Andric std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 147939d628a0SDimitry Andric if (SanitizerBL.isBlacklistedType(TypeStr, Category)) 148039d628a0SDimitry Andric return true; 148139d628a0SDimitry Andric } 148239d628a0SDimitry Andric } 148339d628a0SDimitry Andric return false; 148439d628a0SDimitry Andric } 148539d628a0SDimitry Andric 148620e90f04SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 148720e90f04SDimitry Andric StringRef Category) const { 148820e90f04SDimitry Andric if (!LangOpts.XRayInstrument) 148920e90f04SDimitry Andric return false; 149020e90f04SDimitry Andric const auto &XRayFilter = getContext().getXRayFilter(); 149120e90f04SDimitry Andric using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 149220e90f04SDimitry Andric auto Attr = XRayFunctionFilter::ImbueAttribute::NONE; 149320e90f04SDimitry Andric if (Loc.isValid()) 149420e90f04SDimitry Andric Attr = XRayFilter.shouldImbueLocation(Loc, Category); 149520e90f04SDimitry Andric if (Attr == ImbueAttr::NONE) 149620e90f04SDimitry Andric Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 149720e90f04SDimitry Andric switch (Attr) { 149820e90f04SDimitry Andric case ImbueAttr::NONE: 149920e90f04SDimitry Andric return false; 150020e90f04SDimitry Andric case ImbueAttr::ALWAYS: 150120e90f04SDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 150220e90f04SDimitry Andric break; 150320e90f04SDimitry Andric case ImbueAttr::NEVER: 150420e90f04SDimitry Andric Fn->addFnAttr("function-instrument", "xray-never"); 150520e90f04SDimitry Andric break; 150620e90f04SDimitry Andric } 150720e90f04SDimitry Andric return true; 150820e90f04SDimitry Andric } 150920e90f04SDimitry Andric 151039d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 1511e580952dSDimitry Andric // Never defer when EmitAllDecls is specified. 1512dff0c46cSDimitry Andric if (LangOpts.EmitAllDecls) 151339d628a0SDimitry Andric return true; 151439d628a0SDimitry Andric 151539d628a0SDimitry Andric return getContext().DeclMustBeEmitted(Global); 151639d628a0SDimitry Andric } 151739d628a0SDimitry Andric 151839d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 151939d628a0SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) 152039d628a0SDimitry Andric if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 152139d628a0SDimitry Andric // Implicit template instantiations may change linkage if they are later 152239d628a0SDimitry Andric // explicitly instantiated, so they should not be emitted eagerly. 1523f22ef01cSRoman Divacky return false; 1524e7145dcbSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(Global)) 1525e7145dcbSDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 1526e7145dcbSDimitry Andric ASTContext::InlineVariableDefinitionKind::WeakUnknown) 1527e7145dcbSDimitry Andric // A definition of an inline constexpr static data member may change 1528e7145dcbSDimitry Andric // linkage later if it's redeclared outside the class. 1529e7145dcbSDimitry Andric return false; 1530875ed548SDimitry Andric // If OpenMP is enabled and threadprivates must be generated like TLS, delay 1531875ed548SDimitry Andric // codegen for global variables, because they may be marked as threadprivate. 1532875ed548SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 1533875ed548SDimitry Andric getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global)) 1534875ed548SDimitry Andric return false; 1535f22ef01cSRoman Divacky 153639d628a0SDimitry Andric return true; 1537f22ef01cSRoman Divacky } 1538f22ef01cSRoman Divacky 15390623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor( 15403861d79fSDimitry Andric const CXXUuidofExpr* E) { 15413861d79fSDimitry Andric // Sema has verified that IIDSource has a __declspec(uuid()), and that its 15423861d79fSDimitry Andric // well-formed. 1543e7145dcbSDimitry Andric StringRef Uuid = E->getUuidStr(); 1544f785676fSDimitry Andric std::string Name = "_GUID_" + Uuid.lower(); 1545f785676fSDimitry Andric std::replace(Name.begin(), Name.end(), '-', '_'); 15463861d79fSDimitry Andric 1547e7145dcbSDimitry Andric // The UUID descriptor should be pointer aligned. 1548e7145dcbSDimitry Andric CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 15490623d748SDimitry Andric 15503861d79fSDimitry Andric // Look for an existing global. 15513861d79fSDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 15520623d748SDimitry Andric return ConstantAddress(GV, Alignment); 15533861d79fSDimitry Andric 155439d628a0SDimitry Andric llvm::Constant *Init = EmitUuidofInitializer(Uuid); 15553861d79fSDimitry Andric assert(Init && "failed to initialize as constant"); 15563861d79fSDimitry Andric 155759d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 1558f785676fSDimitry Andric getModule(), Init->getType(), 1559f785676fSDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 156033956c43SDimitry Andric if (supportsCOMDAT()) 156133956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 15620623d748SDimitry Andric return ConstantAddress(GV, Alignment); 15633861d79fSDimitry Andric } 15643861d79fSDimitry Andric 15650623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1566f22ef01cSRoman Divacky const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1567f22ef01cSRoman Divacky assert(AA && "No alias?"); 1568f22ef01cSRoman Divacky 15690623d748SDimitry Andric CharUnits Alignment = getContext().getDeclAlign(VD); 15706122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1571f22ef01cSRoman Divacky 1572f22ef01cSRoman Divacky // See if there is already something with the target's name in the module. 1573f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 15743861d79fSDimitry Andric if (Entry) { 15753861d79fSDimitry Andric unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 15760623d748SDimitry Andric auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 15770623d748SDimitry Andric return ConstantAddress(Ptr, Alignment); 15783861d79fSDimitry Andric } 1579f22ef01cSRoman Divacky 1580f22ef01cSRoman Divacky llvm::Constant *Aliasee; 1581f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 15823861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 15833861d79fSDimitry Andric GlobalDecl(cast<FunctionDecl>(VD)), 15842754fe60SDimitry Andric /*ForVTable=*/false); 1585f22ef01cSRoman Divacky else 1586f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 158759d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 158859d1ed5bSDimitry Andric nullptr); 15893861d79fSDimitry Andric 159059d1ed5bSDimitry Andric auto *F = cast<llvm::GlobalValue>(Aliasee); 1591f22ef01cSRoman Divacky F->setLinkage(llvm::Function::ExternalWeakLinkage); 1592f22ef01cSRoman Divacky WeakRefReferences.insert(F); 1593f22ef01cSRoman Divacky 15940623d748SDimitry Andric return ConstantAddress(Aliasee, Alignment); 1595f22ef01cSRoman Divacky } 1596f22ef01cSRoman Divacky 1597f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) { 159859d1ed5bSDimitry Andric const auto *Global = cast<ValueDecl>(GD.getDecl()); 1599f22ef01cSRoman Divacky 1600f22ef01cSRoman Divacky // Weak references don't produce any output by themselves. 1601f22ef01cSRoman Divacky if (Global->hasAttr<WeakRefAttr>()) 1602f22ef01cSRoman Divacky return; 1603f22ef01cSRoman Divacky 1604f22ef01cSRoman Divacky // If this is an alias definition (which otherwise looks like a declaration) 1605f22ef01cSRoman Divacky // emit it now. 1606f22ef01cSRoman Divacky if (Global->hasAttr<AliasAttr>()) 1607f22ef01cSRoman Divacky return EmitAliasDefinition(GD); 1608f22ef01cSRoman Divacky 1609e7145dcbSDimitry Andric // IFunc like an alias whose value is resolved at runtime by calling resolver. 1610e7145dcbSDimitry Andric if (Global->hasAttr<IFuncAttr>()) 1611e7145dcbSDimitry Andric return emitIFuncDefinition(GD); 1612e7145dcbSDimitry Andric 16136122f3e6SDimitry Andric // If this is CUDA, be selective about which declarations we emit. 1614dff0c46cSDimitry Andric if (LangOpts.CUDA) { 161533956c43SDimitry Andric if (LangOpts.CUDAIsDevice) { 16166122f3e6SDimitry Andric if (!Global->hasAttr<CUDADeviceAttr>() && 16176122f3e6SDimitry Andric !Global->hasAttr<CUDAGlobalAttr>() && 16186122f3e6SDimitry Andric !Global->hasAttr<CUDAConstantAttr>() && 16196122f3e6SDimitry Andric !Global->hasAttr<CUDASharedAttr>()) 16206122f3e6SDimitry Andric return; 16216122f3e6SDimitry Andric } else { 1622e7145dcbSDimitry Andric // We need to emit host-side 'shadows' for all global 1623e7145dcbSDimitry Andric // device-side variables because the CUDA runtime needs their 1624e7145dcbSDimitry Andric // size and host-side address in order to provide access to 1625e7145dcbSDimitry Andric // their device-side incarnations. 1626e7145dcbSDimitry Andric 1627e7145dcbSDimitry Andric // So device-only functions are the only things we skip. 1628e7145dcbSDimitry Andric if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 1629e7145dcbSDimitry Andric Global->hasAttr<CUDADeviceAttr>()) 16306122f3e6SDimitry Andric return; 1631e7145dcbSDimitry Andric 1632e7145dcbSDimitry Andric assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 1633e7145dcbSDimitry Andric "Expected Variable or Function"); 1634e580952dSDimitry Andric } 1635e580952dSDimitry Andric } 1636e580952dSDimitry Andric 1637e7145dcbSDimitry Andric if (LangOpts.OpenMP) { 1638ea942507SDimitry Andric // If this is OpenMP device, check if it is legal to emit this global 1639ea942507SDimitry Andric // normally. 1640ea942507SDimitry Andric if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 1641ea942507SDimitry Andric return; 1642e7145dcbSDimitry Andric if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 1643e7145dcbSDimitry Andric if (MustBeEmitted(Global)) 1644e7145dcbSDimitry Andric EmitOMPDeclareReduction(DRD); 1645e7145dcbSDimitry Andric return; 1646e7145dcbSDimitry Andric } 1647e7145dcbSDimitry Andric } 1648ea942507SDimitry Andric 16496122f3e6SDimitry Andric // Ignore declarations, they will be emitted on their first use. 165059d1ed5bSDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 1651f22ef01cSRoman Divacky // Forward declarations are emitted lazily on first use. 16526122f3e6SDimitry Andric if (!FD->doesThisDeclarationHaveABody()) { 16536122f3e6SDimitry Andric if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1654f22ef01cSRoman Divacky return; 16556122f3e6SDimitry Andric 16566122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 165759d1ed5bSDimitry Andric 165859d1ed5bSDimitry Andric // Compute the function info and LLVM type. 165959d1ed5bSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 166059d1ed5bSDimitry Andric llvm::Type *Ty = getTypes().GetFunctionType(FI); 166159d1ed5bSDimitry Andric 166259d1ed5bSDimitry Andric GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 166359d1ed5bSDimitry Andric /*DontDefer=*/false); 16646122f3e6SDimitry Andric return; 16656122f3e6SDimitry Andric } 1666f22ef01cSRoman Divacky } else { 166759d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(Global); 1668f22ef01cSRoman Divacky assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1669e7145dcbSDimitry Andric // We need to emit device-side global CUDA variables even if a 1670e7145dcbSDimitry Andric // variable does not have a definition -- we still need to define 1671e7145dcbSDimitry Andric // host-side shadow for it. 1672e7145dcbSDimitry Andric bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice && 1673e7145dcbSDimitry Andric !VD->hasDefinition() && 1674e7145dcbSDimitry Andric (VD->hasAttr<CUDAConstantAttr>() || 1675e7145dcbSDimitry Andric VD->hasAttr<CUDADeviceAttr>()); 1676e7145dcbSDimitry Andric if (!MustEmitForCuda && 1677e7145dcbSDimitry Andric VD->isThisDeclarationADefinition() != VarDecl::Definition && 1678e7145dcbSDimitry Andric !Context.isMSStaticDataMemberInlineDefinition(VD)) { 1679e7145dcbSDimitry Andric // If this declaration may have caused an inline variable definition to 1680e7145dcbSDimitry Andric // change linkage, make sure that it's emitted. 1681e7145dcbSDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 1682e7145dcbSDimitry Andric ASTContext::InlineVariableDefinitionKind::Strong) 1683e7145dcbSDimitry Andric GetAddrOfGlobalVar(VD); 1684f22ef01cSRoman Divacky return; 1685f22ef01cSRoman Divacky } 1686e7145dcbSDimitry Andric } 1687f22ef01cSRoman Divacky 168839d628a0SDimitry Andric // Defer code generation to first use when possible, e.g. if this is an inline 168939d628a0SDimitry Andric // function. If the global must always be emitted, do it eagerly if possible 169039d628a0SDimitry Andric // to benefit from cache locality. 169139d628a0SDimitry Andric if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 1692f22ef01cSRoman Divacky // Emit the definition if it can't be deferred. 1693f22ef01cSRoman Divacky EmitGlobalDefinition(GD); 1694f22ef01cSRoman Divacky return; 1695f22ef01cSRoman Divacky } 1696f22ef01cSRoman Divacky 1697e580952dSDimitry Andric // If we're deferring emission of a C++ variable with an 1698e580952dSDimitry Andric // initializer, remember the order in which it appeared in the file. 1699dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1700e580952dSDimitry Andric cast<VarDecl>(Global)->hasInit()) { 1701e580952dSDimitry Andric DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 170259d1ed5bSDimitry Andric CXXGlobalInits.push_back(nullptr); 1703e580952dSDimitry Andric } 1704e580952dSDimitry Andric 17056122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 1706f37b6182SDimitry Andric if (GetGlobalValue(MangledName) != nullptr) { 170739d628a0SDimitry Andric // The value has already been used and should therefore be emitted. 1708f37b6182SDimitry Andric addDeferredDeclToEmit(GD); 170939d628a0SDimitry Andric } else if (MustBeEmitted(Global)) { 171039d628a0SDimitry Andric // The value must be emitted, but cannot be emitted eagerly. 171139d628a0SDimitry Andric assert(!MayBeEmittedEagerly(Global)); 1712f37b6182SDimitry Andric addDeferredDeclToEmit(GD); 171339d628a0SDimitry Andric } else { 1714f22ef01cSRoman Divacky // Otherwise, remember that we saw a deferred decl with this name. The 1715f22ef01cSRoman Divacky // first use of the mangled name will cause it to move into 1716f22ef01cSRoman Divacky // DeferredDeclsToEmit. 1717f22ef01cSRoman Divacky DeferredDecls[MangledName] = GD; 1718f22ef01cSRoman Divacky } 1719f22ef01cSRoman Divacky } 1720f22ef01cSRoman Divacky 172120e90f04SDimitry Andric // Check if T is a class type with a destructor that's not dllimport. 172220e90f04SDimitry Andric static bool HasNonDllImportDtor(QualType T) { 172320e90f04SDimitry Andric if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 172420e90f04SDimitry Andric if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 172520e90f04SDimitry Andric if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 172620e90f04SDimitry Andric return true; 172720e90f04SDimitry Andric 172820e90f04SDimitry Andric return false; 172920e90f04SDimitry Andric } 173020e90f04SDimitry Andric 1731f8254f43SDimitry Andric namespace { 1732f8254f43SDimitry Andric struct FunctionIsDirectlyRecursive : 1733f8254f43SDimitry Andric public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1734f8254f43SDimitry Andric const StringRef Name; 1735dff0c46cSDimitry Andric const Builtin::Context &BI; 1736f8254f43SDimitry Andric bool Result; 1737dff0c46cSDimitry Andric FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1738dff0c46cSDimitry Andric Name(N), BI(C), Result(false) { 1739f8254f43SDimitry Andric } 1740f8254f43SDimitry Andric typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1741f8254f43SDimitry Andric 1742f8254f43SDimitry Andric bool TraverseCallExpr(CallExpr *E) { 1743dff0c46cSDimitry Andric const FunctionDecl *FD = E->getDirectCallee(); 1744dff0c46cSDimitry Andric if (!FD) 1745f8254f43SDimitry Andric return true; 1746dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1747dff0c46cSDimitry Andric if (Attr && Name == Attr->getLabel()) { 1748dff0c46cSDimitry Andric Result = true; 1749dff0c46cSDimitry Andric return false; 1750dff0c46cSDimitry Andric } 1751dff0c46cSDimitry Andric unsigned BuiltinID = FD->getBuiltinID(); 17523dac3a9bSDimitry Andric if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 1753f8254f43SDimitry Andric return true; 17540623d748SDimitry Andric StringRef BuiltinName = BI.getName(BuiltinID); 1755dff0c46cSDimitry Andric if (BuiltinName.startswith("__builtin_") && 1756dff0c46cSDimitry Andric Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1757f8254f43SDimitry Andric Result = true; 1758f8254f43SDimitry Andric return false; 1759f8254f43SDimitry Andric } 1760f8254f43SDimitry Andric return true; 1761f8254f43SDimitry Andric } 1762f8254f43SDimitry Andric }; 17630623d748SDimitry Andric 176420e90f04SDimitry Andric // Make sure we're not referencing non-imported vars or functions. 17650623d748SDimitry Andric struct DLLImportFunctionVisitor 17660623d748SDimitry Andric : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 17670623d748SDimitry Andric bool SafeToInline = true; 17680623d748SDimitry Andric 176944290647SDimitry Andric bool shouldVisitImplicitCode() const { return true; } 177044290647SDimitry Andric 17710623d748SDimitry Andric bool VisitVarDecl(VarDecl *VD) { 177220e90f04SDimitry Andric if (VD->getTLSKind()) { 17730623d748SDimitry Andric // A thread-local variable cannot be imported. 177420e90f04SDimitry Andric SafeToInline = false; 17750623d748SDimitry Andric return SafeToInline; 17760623d748SDimitry Andric } 17770623d748SDimitry Andric 177820e90f04SDimitry Andric // A variable definition might imply a destructor call. 177920e90f04SDimitry Andric if (VD->isThisDeclarationADefinition()) 178020e90f04SDimitry Andric SafeToInline = !HasNonDllImportDtor(VD->getType()); 178120e90f04SDimitry Andric 178220e90f04SDimitry Andric return SafeToInline; 178320e90f04SDimitry Andric } 178420e90f04SDimitry Andric 178520e90f04SDimitry Andric bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 178620e90f04SDimitry Andric if (const auto *D = E->getTemporary()->getDestructor()) 178720e90f04SDimitry Andric SafeToInline = D->hasAttr<DLLImportAttr>(); 178820e90f04SDimitry Andric return SafeToInline; 178920e90f04SDimitry Andric } 179020e90f04SDimitry Andric 17910623d748SDimitry Andric bool VisitDeclRefExpr(DeclRefExpr *E) { 17920623d748SDimitry Andric ValueDecl *VD = E->getDecl(); 17930623d748SDimitry Andric if (isa<FunctionDecl>(VD)) 17940623d748SDimitry Andric SafeToInline = VD->hasAttr<DLLImportAttr>(); 17950623d748SDimitry Andric else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 17960623d748SDimitry Andric SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 17970623d748SDimitry Andric return SafeToInline; 17980623d748SDimitry Andric } 179920e90f04SDimitry Andric 180044290647SDimitry Andric bool VisitCXXConstructExpr(CXXConstructExpr *E) { 180144290647SDimitry Andric SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 180244290647SDimitry Andric return SafeToInline; 180344290647SDimitry Andric } 180420e90f04SDimitry Andric 180520e90f04SDimitry Andric bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 180620e90f04SDimitry Andric CXXMethodDecl *M = E->getMethodDecl(); 180720e90f04SDimitry Andric if (!M) { 180820e90f04SDimitry Andric // Call through a pointer to member function. This is safe to inline. 180920e90f04SDimitry Andric SafeToInline = true; 181020e90f04SDimitry Andric } else { 181120e90f04SDimitry Andric SafeToInline = M->hasAttr<DLLImportAttr>(); 181220e90f04SDimitry Andric } 181320e90f04SDimitry Andric return SafeToInline; 181420e90f04SDimitry Andric } 181520e90f04SDimitry Andric 18160623d748SDimitry Andric bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 18170623d748SDimitry Andric SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 18180623d748SDimitry Andric return SafeToInline; 18190623d748SDimitry Andric } 182020e90f04SDimitry Andric 18210623d748SDimitry Andric bool VisitCXXNewExpr(CXXNewExpr *E) { 18220623d748SDimitry Andric SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 18230623d748SDimitry Andric return SafeToInline; 18240623d748SDimitry Andric } 18250623d748SDimitry Andric }; 1826f8254f43SDimitry Andric } 1827f8254f43SDimitry Andric 1828dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another 1829dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin, 1830dff0c46cSDimitry Andric // ends up pointing to itself. 1831f8254f43SDimitry Andric bool 1832dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1833dff0c46cSDimitry Andric StringRef Name; 1834dff0c46cSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1835dff0c46cSDimitry Andric // asm labels are a special kind of mangling we have to support. 1836dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1837dff0c46cSDimitry Andric if (!Attr) 1838f8254f43SDimitry Andric return false; 1839dff0c46cSDimitry Andric Name = Attr->getLabel(); 1840dff0c46cSDimitry Andric } else { 1841dff0c46cSDimitry Andric Name = FD->getName(); 1842dff0c46cSDimitry Andric } 1843f8254f43SDimitry Andric 1844dff0c46cSDimitry Andric FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1845dff0c46cSDimitry Andric Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1846f8254f43SDimitry Andric return Walker.Result; 1847f8254f43SDimitry Andric } 1848f8254f43SDimitry Andric 184944290647SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1850f785676fSDimitry Andric if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1851f8254f43SDimitry Andric return true; 185259d1ed5bSDimitry Andric const auto *F = cast<FunctionDecl>(GD.getDecl()); 185359d1ed5bSDimitry Andric if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1854f8254f43SDimitry Andric return false; 18550623d748SDimitry Andric 18560623d748SDimitry Andric if (F->hasAttr<DLLImportAttr>()) { 18570623d748SDimitry Andric // Check whether it would be safe to inline this dllimport function. 18580623d748SDimitry Andric DLLImportFunctionVisitor Visitor; 18590623d748SDimitry Andric Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 18600623d748SDimitry Andric if (!Visitor.SafeToInline) 18610623d748SDimitry Andric return false; 186244290647SDimitry Andric 186344290647SDimitry Andric if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 186444290647SDimitry Andric // Implicit destructor invocations aren't captured in the AST, so the 186544290647SDimitry Andric // check above can't see them. Check for them manually here. 186644290647SDimitry Andric for (const Decl *Member : Dtor->getParent()->decls()) 186744290647SDimitry Andric if (isa<FieldDecl>(Member)) 186844290647SDimitry Andric if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 186944290647SDimitry Andric return false; 187044290647SDimitry Andric for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 187144290647SDimitry Andric if (HasNonDllImportDtor(B.getType())) 187244290647SDimitry Andric return false; 187344290647SDimitry Andric } 18740623d748SDimitry Andric } 18750623d748SDimitry Andric 1876f8254f43SDimitry Andric // PR9614. Avoid cases where the source code is lying to us. An available 1877f8254f43SDimitry Andric // externally function should have an equivalent function somewhere else, 1878f8254f43SDimitry Andric // but a function that calls itself is clearly not equivalent to the real 1879f8254f43SDimitry Andric // implementation. 1880f8254f43SDimitry Andric // This happens in glibc's btowc and in some configure checks. 1881dff0c46cSDimitry Andric return !isTriviallyRecursive(F); 1882f8254f43SDimitry Andric } 1883f8254f43SDimitry Andric 188459d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 188559d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 1886f22ef01cSRoman Divacky 1887f22ef01cSRoman Divacky PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1888f22ef01cSRoman Divacky Context.getSourceManager(), 1889f22ef01cSRoman Divacky "Generating code for declaration"); 1890f22ef01cSRoman Divacky 1891f785676fSDimitry Andric if (isa<FunctionDecl>(D)) { 1892ffd1746dSEd Schouten // At -O0, don't generate IR for functions with available_externally 1893ffd1746dSEd Schouten // linkage. 1894f785676fSDimitry Andric if (!shouldEmitFunction(GD)) 1895ffd1746dSEd Schouten return; 1896ffd1746dSEd Schouten 189759d1ed5bSDimitry Andric if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 1898bd5abe19SDimitry Andric // Make sure to emit the definition(s) before we emit the thunks. 1899bd5abe19SDimitry Andric // This is necessary for the generation of certain thunks. 190059d1ed5bSDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 190139d628a0SDimitry Andric ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); 190259d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 190339d628a0SDimitry Andric ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); 1904bd5abe19SDimitry Andric else 190559d1ed5bSDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 1906bd5abe19SDimitry Andric 1907f22ef01cSRoman Divacky if (Method->isVirtual()) 1908f22ef01cSRoman Divacky getVTables().EmitThunks(GD); 1909f22ef01cSRoman Divacky 1910bd5abe19SDimitry Andric return; 1911ffd1746dSEd Schouten } 1912f22ef01cSRoman Divacky 191359d1ed5bSDimitry Andric return EmitGlobalFunctionDefinition(GD, GV); 1914ffd1746dSEd Schouten } 1915f22ef01cSRoman Divacky 191659d1ed5bSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 1917e7145dcbSDimitry Andric return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 1918f22ef01cSRoman Divacky 19196122f3e6SDimitry Andric llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1920f22ef01cSRoman Divacky } 1921f22ef01cSRoman Divacky 19220623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 19230623d748SDimitry Andric llvm::Function *NewFn); 19240623d748SDimitry Andric 1925f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1926f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there 1927f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 1928f22ef01cSRoman Divacky /// bitcasted to the right type. 1929f22ef01cSRoman Divacky /// 1930f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 1931f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created. 193220e90f04SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 193320e90f04SDimitry Andric StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 193420e90f04SDimitry Andric bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 193544290647SDimitry Andric ForDefinition_t IsForDefinition) { 1936f785676fSDimitry Andric const Decl *D = GD.getDecl(); 1937f785676fSDimitry Andric 1938f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 1939f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1940f22ef01cSRoman Divacky if (Entry) { 19413861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 1942f785676fSDimitry Andric const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 1943f22ef01cSRoman Divacky if (FD && !FD->hasAttr<WeakAttr>()) 1944f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 1945f22ef01cSRoman Divacky } 1946f22ef01cSRoman Divacky 194739d628a0SDimitry Andric // Handle dropped DLL attributes. 194839d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 194939d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 195039d628a0SDimitry Andric 19510623d748SDimitry Andric // If there are two attempts to define the same mangled name, issue an 19520623d748SDimitry Andric // error. 19530623d748SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 19540623d748SDimitry Andric GlobalDecl OtherGD; 1955e7145dcbSDimitry Andric // Check that GD is not yet in DiagnosedConflictingDefinitions is required 1956e7145dcbSDimitry Andric // to make sure that we issue an error only once. 19570623d748SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 19580623d748SDimitry Andric (GD.getCanonicalDecl().getDecl() != 19590623d748SDimitry Andric OtherGD.getCanonicalDecl().getDecl()) && 19600623d748SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 19610623d748SDimitry Andric getDiags().Report(D->getLocation(), 19620623d748SDimitry Andric diag::err_duplicate_mangled_name); 19630623d748SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 19640623d748SDimitry Andric diag::note_previous_definition); 19650623d748SDimitry Andric } 19660623d748SDimitry Andric } 19670623d748SDimitry Andric 19680623d748SDimitry Andric if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 19690623d748SDimitry Andric (Entry->getType()->getElementType() == Ty)) { 1970f22ef01cSRoman Divacky return Entry; 19710623d748SDimitry Andric } 1972f22ef01cSRoman Divacky 1973f22ef01cSRoman Divacky // Make sure the result is of the correct type. 19740623d748SDimitry Andric // (If function is requested for a definition, we always need to create a new 19750623d748SDimitry Andric // function, not just return a bitcast.) 19760623d748SDimitry Andric if (!IsForDefinition) 197717a519f9SDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1978f22ef01cSRoman Divacky } 1979f22ef01cSRoman Divacky 1980f22ef01cSRoman Divacky // This function doesn't have a complete type (for example, the return 1981f22ef01cSRoman Divacky // type is an incomplete struct). Use a fake type instead, and make 1982f22ef01cSRoman Divacky // sure not to try to set attributes. 1983f22ef01cSRoman Divacky bool IsIncompleteFunction = false; 1984f22ef01cSRoman Divacky 19856122f3e6SDimitry Andric llvm::FunctionType *FTy; 1986f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(Ty)) { 1987f22ef01cSRoman Divacky FTy = cast<llvm::FunctionType>(Ty); 1988f22ef01cSRoman Divacky } else { 1989bd5abe19SDimitry Andric FTy = llvm::FunctionType::get(VoidTy, false); 1990f22ef01cSRoman Divacky IsIncompleteFunction = true; 1991f22ef01cSRoman Divacky } 1992ffd1746dSEd Schouten 19930623d748SDimitry Andric llvm::Function *F = 19940623d748SDimitry Andric llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 19950623d748SDimitry Andric Entry ? StringRef() : MangledName, &getModule()); 19960623d748SDimitry Andric 19970623d748SDimitry Andric // If we already created a function with the same mangled name (but different 19980623d748SDimitry Andric // type) before, take its name and add it to the list of functions to be 19990623d748SDimitry Andric // replaced with F at the end of CodeGen. 20000623d748SDimitry Andric // 20010623d748SDimitry Andric // This happens if there is a prototype for a function (e.g. "int f()") and 20020623d748SDimitry Andric // then a definition of a different type (e.g. "int f(int x)"). 20030623d748SDimitry Andric if (Entry) { 20040623d748SDimitry Andric F->takeName(Entry); 20050623d748SDimitry Andric 20060623d748SDimitry Andric // This might be an implementation of a function without a prototype, in 20070623d748SDimitry Andric // which case, try to do special replacement of calls which match the new 20080623d748SDimitry Andric // prototype. The really key thing here is that we also potentially drop 20090623d748SDimitry Andric // arguments from the call site so as to make a direct call, which makes the 20100623d748SDimitry Andric // inliner happier and suppresses a number of optimizer warnings (!) about 20110623d748SDimitry Andric // dropping arguments. 20120623d748SDimitry Andric if (!Entry->use_empty()) { 20130623d748SDimitry Andric ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 20140623d748SDimitry Andric Entry->removeDeadConstantUsers(); 20150623d748SDimitry Andric } 20160623d748SDimitry Andric 20170623d748SDimitry Andric llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 20180623d748SDimitry Andric F, Entry->getType()->getElementType()->getPointerTo()); 20190623d748SDimitry Andric addGlobalValReplacement(Entry, BC); 20200623d748SDimitry Andric } 20210623d748SDimitry Andric 2022f22ef01cSRoman Divacky assert(F->getName() == MangledName && "name was uniqued!"); 2023f785676fSDimitry Andric if (D) 202439d628a0SDimitry Andric SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 202520e90f04SDimitry Andric if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) { 202620e90f04SDimitry Andric llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex); 2027f37b6182SDimitry Andric F->addAttributes(llvm::AttributeList::FunctionIndex, B); 2028139f7f9bSDimitry Andric } 2029f22ef01cSRoman Divacky 203059d1ed5bSDimitry Andric if (!DontDefer) { 203159d1ed5bSDimitry Andric // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 203259d1ed5bSDimitry Andric // each other bottoming out with the base dtor. Therefore we emit non-base 203359d1ed5bSDimitry Andric // dtors on usage, even if there is no dtor definition in the TU. 203459d1ed5bSDimitry Andric if (D && isa<CXXDestructorDecl>(D) && 203559d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 203659d1ed5bSDimitry Andric GD.getDtorType())) 2037f37b6182SDimitry Andric addDeferredDeclToEmit(GD); 203859d1ed5bSDimitry Andric 2039f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 2040f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 2041f22ef01cSRoman Divacky // of the file. 204259d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 2043f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 204459d1ed5bSDimitry Andric // Move the potentially referenced deferred decl to the 204559d1ed5bSDimitry Andric // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 204659d1ed5bSDimitry Andric // don't need it anymore). 2047f37b6182SDimitry Andric addDeferredDeclToEmit(DDI->second); 2048f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 20492754fe60SDimitry Andric 20502754fe60SDimitry Andric // Otherwise, there are cases we have to worry about where we're 20512754fe60SDimitry Andric // using a declaration for which we must emit a definition but where 20522754fe60SDimitry Andric // we might not find a top-level definition: 20532754fe60SDimitry Andric // - member functions defined inline in their classes 20542754fe60SDimitry Andric // - friend functions defined inline in some class 20552754fe60SDimitry Andric // - special member functions with implicit definitions 20562754fe60SDimitry Andric // If we ever change our AST traversal to walk into class methods, 20572754fe60SDimitry Andric // this will be unnecessary. 20582754fe60SDimitry Andric // 205959d1ed5bSDimitry Andric // We also don't emit a definition for a function if it's going to be an 206039d628a0SDimitry Andric // entry in a vtable, unless it's already marked as used. 2061f785676fSDimitry Andric } else if (getLangOpts().CPlusPlus && D) { 20622754fe60SDimitry Andric // Look for a declaration that's lexically in a record. 206339d628a0SDimitry Andric for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 206439d628a0SDimitry Andric FD = FD->getPreviousDecl()) { 20652754fe60SDimitry Andric if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 206639d628a0SDimitry Andric if (FD->doesThisDeclarationHaveABody()) { 2067f37b6182SDimitry Andric addDeferredDeclToEmit(GD.getWithDecl(FD)); 20682754fe60SDimitry Andric break; 2069f22ef01cSRoman Divacky } 2070f22ef01cSRoman Divacky } 207139d628a0SDimitry Andric } 2072f22ef01cSRoman Divacky } 207359d1ed5bSDimitry Andric } 2074f22ef01cSRoman Divacky 2075f22ef01cSRoman Divacky // Make sure the result is of the requested type. 2076f22ef01cSRoman Divacky if (!IsIncompleteFunction) { 2077f22ef01cSRoman Divacky assert(F->getType()->getElementType() == Ty); 2078f22ef01cSRoman Divacky return F; 2079f22ef01cSRoman Divacky } 2080f22ef01cSRoman Divacky 208117a519f9SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2082f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(F, PTy); 2083f22ef01cSRoman Divacky } 2084f22ef01cSRoman Divacky 2085f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function. If Ty is 2086f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to 2087f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function). 2088f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 20896122f3e6SDimitry Andric llvm::Type *Ty, 209059d1ed5bSDimitry Andric bool ForVTable, 20910623d748SDimitry Andric bool DontDefer, 209244290647SDimitry Andric ForDefinition_t IsForDefinition) { 2093f22ef01cSRoman Divacky // If there was no specific requested type, just convert it now. 20940623d748SDimitry Andric if (!Ty) { 20950623d748SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 20960623d748SDimitry Andric auto CanonTy = Context.getCanonicalType(FD->getType()); 20970623d748SDimitry Andric Ty = getTypes().ConvertFunctionType(CanonTy, FD); 20980623d748SDimitry Andric } 2099ffd1746dSEd Schouten 21006122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 21010623d748SDimitry Andric return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 210220e90f04SDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), 21030623d748SDimitry Andric IsForDefinition); 2104f22ef01cSRoman Divacky } 2105f22ef01cSRoman Divacky 210644290647SDimitry Andric static const FunctionDecl * 210744290647SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 210844290647SDimitry Andric TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 210944290647SDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 211044290647SDimitry Andric 211144290647SDimitry Andric IdentifierInfo &CII = C.Idents.get(Name); 211244290647SDimitry Andric for (const auto &Result : DC->lookup(&CII)) 211344290647SDimitry Andric if (const auto FD = dyn_cast<FunctionDecl>(Result)) 211444290647SDimitry Andric return FD; 211544290647SDimitry Andric 211644290647SDimitry Andric if (!C.getLangOpts().CPlusPlus) 211744290647SDimitry Andric return nullptr; 211844290647SDimitry Andric 211944290647SDimitry Andric // Demangle the premangled name from getTerminateFn() 212044290647SDimitry Andric IdentifierInfo &CXXII = 212144290647SDimitry Andric (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ") 212244290647SDimitry Andric ? C.Idents.get("terminate") 212344290647SDimitry Andric : C.Idents.get(Name); 212444290647SDimitry Andric 212544290647SDimitry Andric for (const auto &N : {"__cxxabiv1", "std"}) { 212644290647SDimitry Andric IdentifierInfo &NS = C.Idents.get(N); 212744290647SDimitry Andric for (const auto &Result : DC->lookup(&NS)) { 212844290647SDimitry Andric NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 212944290647SDimitry Andric if (auto LSD = dyn_cast<LinkageSpecDecl>(Result)) 213044290647SDimitry Andric for (const auto &Result : LSD->lookup(&NS)) 213144290647SDimitry Andric if ((ND = dyn_cast<NamespaceDecl>(Result))) 213244290647SDimitry Andric break; 213344290647SDimitry Andric 213444290647SDimitry Andric if (ND) 213544290647SDimitry Andric for (const auto &Result : ND->lookup(&CXXII)) 213644290647SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 213744290647SDimitry Andric return FD; 213844290647SDimitry Andric } 213944290647SDimitry Andric } 214044290647SDimitry Andric 214144290647SDimitry Andric return nullptr; 214244290647SDimitry Andric } 214344290647SDimitry Andric 2144f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified 2145f22ef01cSRoman Divacky /// type and name. 2146f22ef01cSRoman Divacky llvm::Constant * 214744290647SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 214820e90f04SDimitry Andric llvm::AttributeList ExtraAttrs, 214944290647SDimitry Andric bool Local) { 215059d1ed5bSDimitry Andric llvm::Constant *C = 215159d1ed5bSDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 215244290647SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, 215344290647SDimitry Andric ExtraAttrs); 215444290647SDimitry Andric 215544290647SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) { 215644290647SDimitry Andric if (F->empty()) { 2157139f7f9bSDimitry Andric F->setCallingConv(getRuntimeCC()); 215844290647SDimitry Andric 215944290647SDimitry Andric if (!Local && getTriple().isOSBinFormatCOFF() && 216044290647SDimitry Andric !getCodeGenOpts().LTOVisibilityPublicStd) { 216144290647SDimitry Andric const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 216244290647SDimitry Andric if (!FD || FD->hasAttr<DLLImportAttr>()) { 216344290647SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 216444290647SDimitry Andric F->setLinkage(llvm::GlobalValue::ExternalLinkage); 216544290647SDimitry Andric } 216644290647SDimitry Andric } 216744290647SDimitry Andric } 216844290647SDimitry Andric } 216944290647SDimitry Andric 2170139f7f9bSDimitry Andric return C; 2171f22ef01cSRoman Divacky } 2172f22ef01cSRoman Divacky 217339d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified 217439d628a0SDimitry Andric /// type and name. 217539d628a0SDimitry Andric llvm::Constant * 217620e90f04SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name, 217720e90f04SDimitry Andric llvm::AttributeList ExtraAttrs) { 217839d628a0SDimitry Andric llvm::Constant *C = 217939d628a0SDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 218039d628a0SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 218139d628a0SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) 218239d628a0SDimitry Andric if (F->empty()) 218339d628a0SDimitry Andric F->setCallingConv(getBuiltinCC()); 218439d628a0SDimitry Andric return C; 218539d628a0SDimitry Andric } 218639d628a0SDimitry Andric 2187dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted 2188dff0c46cSDimitry Andric /// as a constant. 2189dff0c46cSDimitry Andric /// 2190dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs 2191dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is 2192dff0c46cSDimitry Andric /// not written to during its construction. 2193dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 2194dff0c46cSDimitry Andric if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 2195f22ef01cSRoman Divacky return false; 2196bd5abe19SDimitry Andric 2197dff0c46cSDimitry Andric if (Context.getLangOpts().CPlusPlus) { 2198dff0c46cSDimitry Andric if (const CXXRecordDecl *Record 2199dff0c46cSDimitry Andric = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 2200dff0c46cSDimitry Andric return ExcludeCtor && !Record->hasMutableFields() && 2201dff0c46cSDimitry Andric Record->hasTrivialDestructor(); 2202f22ef01cSRoman Divacky } 2203bd5abe19SDimitry Andric 2204f22ef01cSRoman Divacky return true; 2205f22ef01cSRoman Divacky } 2206f22ef01cSRoman Divacky 2207f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 2208f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type. If there 2209f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 2210f22ef01cSRoman Divacky /// bitcasted to the right type. 2211f22ef01cSRoman Divacky /// 2212f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 2213f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created. 2214e7145dcbSDimitry Andric /// 2215e7145dcbSDimitry Andric /// If IsForDefinition is true, it is guranteed that an actual global with 2216e7145dcbSDimitry Andric /// type Ty will be returned, not conversion of a variable with the same 2217e7145dcbSDimitry Andric /// mangled name but some other type. 2218f22ef01cSRoman Divacky llvm::Constant * 22196122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 22206122f3e6SDimitry Andric llvm::PointerType *Ty, 2221e7145dcbSDimitry Andric const VarDecl *D, 222244290647SDimitry Andric ForDefinition_t IsForDefinition) { 2223f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 2224f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2225f22ef01cSRoman Divacky if (Entry) { 22263861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 2227f22ef01cSRoman Divacky if (D && !D->hasAttr<WeakAttr>()) 2228f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 2229f22ef01cSRoman Divacky } 2230f22ef01cSRoman Divacky 223139d628a0SDimitry Andric // Handle dropped DLL attributes. 223239d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 223339d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 223439d628a0SDimitry Andric 2235f22ef01cSRoman Divacky if (Entry->getType() == Ty) 2236f22ef01cSRoman Divacky return Entry; 2237f22ef01cSRoman Divacky 2238e7145dcbSDimitry Andric // If there are two attempts to define the same mangled name, issue an 2239e7145dcbSDimitry Andric // error. 2240e7145dcbSDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 2241e7145dcbSDimitry Andric GlobalDecl OtherGD; 2242e7145dcbSDimitry Andric const VarDecl *OtherD; 2243e7145dcbSDimitry Andric 2244e7145dcbSDimitry Andric // Check that D is not yet in DiagnosedConflictingDefinitions is required 2245e7145dcbSDimitry Andric // to make sure that we issue an error only once. 2246e7145dcbSDimitry Andric if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 2247e7145dcbSDimitry Andric (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 2248e7145dcbSDimitry Andric (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 2249e7145dcbSDimitry Andric OtherD->hasInit() && 2250e7145dcbSDimitry Andric DiagnosedConflictingDefinitions.insert(D).second) { 2251e7145dcbSDimitry Andric getDiags().Report(D->getLocation(), 2252e7145dcbSDimitry Andric diag::err_duplicate_mangled_name); 2253e7145dcbSDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 2254e7145dcbSDimitry Andric diag::note_previous_definition); 2255e7145dcbSDimitry Andric } 2256e7145dcbSDimitry Andric } 2257e7145dcbSDimitry Andric 2258f22ef01cSRoman Divacky // Make sure the result is of the correct type. 2259f785676fSDimitry Andric if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 2260f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 2261f785676fSDimitry Andric 2262e7145dcbSDimitry Andric // (If global is requested for a definition, we always need to create a new 2263e7145dcbSDimitry Andric // global, not just return a bitcast.) 2264e7145dcbSDimitry Andric if (!IsForDefinition) 2265f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(Entry, Ty); 2266f22ef01cSRoman Divacky } 2267f22ef01cSRoman Divacky 226859d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 226959d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 227059d1ed5bSDimitry Andric getModule(), Ty->getElementType(), false, 227159d1ed5bSDimitry Andric llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 227259d1ed5bSDimitry Andric llvm::GlobalVariable::NotThreadLocal, AddrSpace); 227359d1ed5bSDimitry Andric 2274e7145dcbSDimitry Andric // If we already created a global with the same mangled name (but different 2275e7145dcbSDimitry Andric // type) before, take its name and remove it from its parent. 2276e7145dcbSDimitry Andric if (Entry) { 2277e7145dcbSDimitry Andric GV->takeName(Entry); 2278e7145dcbSDimitry Andric 2279e7145dcbSDimitry Andric if (!Entry->use_empty()) { 2280e7145dcbSDimitry Andric llvm::Constant *NewPtrForOldDecl = 2281e7145dcbSDimitry Andric llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2282e7145dcbSDimitry Andric Entry->replaceAllUsesWith(NewPtrForOldDecl); 2283e7145dcbSDimitry Andric } 2284e7145dcbSDimitry Andric 2285e7145dcbSDimitry Andric Entry->eraseFromParent(); 2286e7145dcbSDimitry Andric } 2287e7145dcbSDimitry Andric 2288f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 2289f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 2290f22ef01cSRoman Divacky // of the file. 229159d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 2292f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 2293f22ef01cSRoman Divacky // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 2294f22ef01cSRoman Divacky // list, and remove it from DeferredDecls (since we don't need it anymore). 2295f37b6182SDimitry Andric addDeferredDeclToEmit(DDI->second); 2296f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 2297f22ef01cSRoman Divacky } 2298f22ef01cSRoman Divacky 2299f22ef01cSRoman Divacky // Handle things which are present even on external declarations. 2300f22ef01cSRoman Divacky if (D) { 2301f22ef01cSRoman Divacky // FIXME: This code is overly simple and should be merged with other global 2302f22ef01cSRoman Divacky // handling. 2303dff0c46cSDimitry Andric GV->setConstant(isTypeConstant(D->getType(), false)); 2304f22ef01cSRoman Divacky 230533956c43SDimitry Andric GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 230633956c43SDimitry Andric 230759d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(GV, D); 23082754fe60SDimitry Andric 2309284c1978SDimitry Andric if (D->getTLSKind()) { 2310284c1978SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 23110623d748SDimitry Andric CXXThreadLocals.push_back(D); 23127ae0e2c9SDimitry Andric setTLSMode(GV, *D); 2313f22ef01cSRoman Divacky } 2314f785676fSDimitry Andric 2315f785676fSDimitry Andric // If required by the ABI, treat declarations of static data members with 2316f785676fSDimitry Andric // inline initializers as definitions. 231759d1ed5bSDimitry Andric if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 2318f785676fSDimitry Andric EmitGlobalVarDefinition(D); 2319284c1978SDimitry Andric } 2320f22ef01cSRoman Divacky 232159d1ed5bSDimitry Andric // Handle XCore specific ABI requirements. 232244290647SDimitry Andric if (getTriple().getArch() == llvm::Triple::xcore && 232359d1ed5bSDimitry Andric D->getLanguageLinkage() == CLanguageLinkage && 232459d1ed5bSDimitry Andric D->getType().isConstant(Context) && 232559d1ed5bSDimitry Andric isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 232659d1ed5bSDimitry Andric GV->setSection(".cp.rodata"); 232759d1ed5bSDimitry Andric } 232859d1ed5bSDimitry Andric 23297ae0e2c9SDimitry Andric if (AddrSpace != Ty->getAddressSpace()) 2330f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty); 2331f785676fSDimitry Andric 2332f22ef01cSRoman Divacky return GV; 2333f22ef01cSRoman Divacky } 2334f22ef01cSRoman Divacky 23350623d748SDimitry Andric llvm::Constant * 23360623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, 233744290647SDimitry Andric ForDefinition_t IsForDefinition) { 233844290647SDimitry Andric const Decl *D = GD.getDecl(); 233944290647SDimitry Andric if (isa<CXXConstructorDecl>(D)) 234044290647SDimitry Andric return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D), 23410623d748SDimitry Andric getFromCtorType(GD.getCtorType()), 23420623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 23430623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 234444290647SDimitry Andric else if (isa<CXXDestructorDecl>(D)) 234544290647SDimitry Andric return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D), 23460623d748SDimitry Andric getFromDtorType(GD.getDtorType()), 23470623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 23480623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 234944290647SDimitry Andric else if (isa<CXXMethodDecl>(D)) { 23500623d748SDimitry Andric auto FInfo = &getTypes().arrangeCXXMethodDeclaration( 235144290647SDimitry Andric cast<CXXMethodDecl>(D)); 23520623d748SDimitry Andric auto Ty = getTypes().GetFunctionType(*FInfo); 23530623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 23540623d748SDimitry Andric IsForDefinition); 235544290647SDimitry Andric } else if (isa<FunctionDecl>(D)) { 23560623d748SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 23570623d748SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 23580623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 23590623d748SDimitry Andric IsForDefinition); 23600623d748SDimitry Andric } else 236144290647SDimitry Andric return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, 2362e7145dcbSDimitry Andric IsForDefinition); 23630623d748SDimitry Andric } 2364f22ef01cSRoman Divacky 23652754fe60SDimitry Andric llvm::GlobalVariable * 23666122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 23676122f3e6SDimitry Andric llvm::Type *Ty, 23682754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage) { 23692754fe60SDimitry Andric llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 237059d1ed5bSDimitry Andric llvm::GlobalVariable *OldGV = nullptr; 23712754fe60SDimitry Andric 23722754fe60SDimitry Andric if (GV) { 23732754fe60SDimitry Andric // Check if the variable has the right type. 23742754fe60SDimitry Andric if (GV->getType()->getElementType() == Ty) 23752754fe60SDimitry Andric return GV; 23762754fe60SDimitry Andric 23772754fe60SDimitry Andric // Because C++ name mangling, the only way we can end up with an already 23782754fe60SDimitry Andric // existing global with the same name is if it has been declared extern "C". 23792754fe60SDimitry Andric assert(GV->isDeclaration() && "Declaration has wrong type!"); 23802754fe60SDimitry Andric OldGV = GV; 23812754fe60SDimitry Andric } 23822754fe60SDimitry Andric 23832754fe60SDimitry Andric // Create a new variable. 23842754fe60SDimitry Andric GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 238559d1ed5bSDimitry Andric Linkage, nullptr, Name); 23862754fe60SDimitry Andric 23872754fe60SDimitry Andric if (OldGV) { 23882754fe60SDimitry Andric // Replace occurrences of the old variable if needed. 23892754fe60SDimitry Andric GV->takeName(OldGV); 23902754fe60SDimitry Andric 23912754fe60SDimitry Andric if (!OldGV->use_empty()) { 23922754fe60SDimitry Andric llvm::Constant *NewPtrForOldDecl = 23932754fe60SDimitry Andric llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 23942754fe60SDimitry Andric OldGV->replaceAllUsesWith(NewPtrForOldDecl); 23952754fe60SDimitry Andric } 23962754fe60SDimitry Andric 23972754fe60SDimitry Andric OldGV->eraseFromParent(); 23982754fe60SDimitry Andric } 23992754fe60SDimitry Andric 240033956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker() && 240133956c43SDimitry Andric !GV->hasAvailableExternallyLinkage()) 240233956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 240333956c43SDimitry Andric 24042754fe60SDimitry Andric return GV; 24052754fe60SDimitry Andric } 24062754fe60SDimitry Andric 2407f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 2408f22ef01cSRoman Divacky /// given global variable. If Ty is non-null and if the global doesn't exist, 2409cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the 2410e7145dcbSDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guranteed 2411e7145dcbSDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a 2412e7145dcbSDimitry Andric /// variable with the same mangled name but some other type. 2413f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 2414e7145dcbSDimitry Andric llvm::Type *Ty, 241544290647SDimitry Andric ForDefinition_t IsForDefinition) { 2416f22ef01cSRoman Divacky assert(D->hasGlobalStorage() && "Not a global variable"); 2417f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 241859d1ed5bSDimitry Andric if (!Ty) 2419f22ef01cSRoman Divacky Ty = getTypes().ConvertTypeForMem(ASTTy); 2420f22ef01cSRoman Divacky 24216122f3e6SDimitry Andric llvm::PointerType *PTy = 24223b0f4066SDimitry Andric llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 2423f22ef01cSRoman Divacky 24246122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2425e7145dcbSDimitry Andric return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition); 2426f22ef01cSRoman Divacky } 2427f22ef01cSRoman Divacky 2428f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the 2429f22ef01cSRoman Divacky /// specified type and name. 2430f22ef01cSRoman Divacky llvm::Constant * 24316122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 24326122f3e6SDimitry Andric StringRef Name) { 243359d1ed5bSDimitry Andric return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr); 2434f22ef01cSRoman Divacky } 2435f22ef01cSRoman Divacky 2436f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 2437f22ef01cSRoman Divacky assert(!D->getInit() && "Cannot emit definite definitions here!"); 2438f22ef01cSRoman Divacky 24396122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2440e7145dcbSDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(MangledName); 2441e7145dcbSDimitry Andric 2442e7145dcbSDimitry Andric // We already have a definition, not declaration, with the same mangled name. 2443e7145dcbSDimitry Andric // Emitting of declaration is not required (and actually overwrites emitted 2444e7145dcbSDimitry Andric // definition). 2445e7145dcbSDimitry Andric if (GV && !GV->isDeclaration()) 2446e7145dcbSDimitry Andric return; 2447e7145dcbSDimitry Andric 2448e7145dcbSDimitry Andric // If we have not seen a reference to this variable yet, place it into the 2449e7145dcbSDimitry Andric // deferred declarations table to be emitted if needed later. 2450e7145dcbSDimitry Andric if (!MustBeEmitted(D) && !GV) { 2451f22ef01cSRoman Divacky DeferredDecls[MangledName] = D; 2452f22ef01cSRoman Divacky return; 2453f22ef01cSRoman Divacky } 2454f22ef01cSRoman Divacky 2455f22ef01cSRoman Divacky // The tentative definition is the only definition. 2456f22ef01cSRoman Divacky EmitGlobalVarDefinition(D); 2457f22ef01cSRoman Divacky } 2458f22ef01cSRoman Divacky 24596122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 24602754fe60SDimitry Andric return Context.toCharUnitsFromBits( 24610623d748SDimitry Andric getDataLayout().getTypeStoreSizeInBits(Ty)); 2462f22ef01cSRoman Divacky } 2463f22ef01cSRoman Divacky 24647ae0e2c9SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 24657ae0e2c9SDimitry Andric unsigned AddrSpace) { 2466e7145dcbSDimitry Andric if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) { 24677ae0e2c9SDimitry Andric if (D->hasAttr<CUDAConstantAttr>()) 24687ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 24697ae0e2c9SDimitry Andric else if (D->hasAttr<CUDASharedAttr>()) 24707ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 24717ae0e2c9SDimitry Andric else 24727ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 24737ae0e2c9SDimitry Andric } 24747ae0e2c9SDimitry Andric 24757ae0e2c9SDimitry Andric return AddrSpace; 24767ae0e2c9SDimitry Andric } 24777ae0e2c9SDimitry Andric 2478284c1978SDimitry Andric template<typename SomeDecl> 2479284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 2480284c1978SDimitry Andric llvm::GlobalValue *GV) { 2481284c1978SDimitry Andric if (!getLangOpts().CPlusPlus) 2482284c1978SDimitry Andric return; 2483284c1978SDimitry Andric 2484284c1978SDimitry Andric // Must have 'used' attribute, or else inline assembly can't rely on 2485284c1978SDimitry Andric // the name existing. 2486284c1978SDimitry Andric if (!D->template hasAttr<UsedAttr>()) 2487284c1978SDimitry Andric return; 2488284c1978SDimitry Andric 2489284c1978SDimitry Andric // Must have internal linkage and an ordinary name. 2490f785676fSDimitry Andric if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 2491284c1978SDimitry Andric return; 2492284c1978SDimitry Andric 2493284c1978SDimitry Andric // Must be in an extern "C" context. Entities declared directly within 2494284c1978SDimitry Andric // a record are not extern "C" even if the record is in such a context. 2495f785676fSDimitry Andric const SomeDecl *First = D->getFirstDecl(); 2496284c1978SDimitry Andric if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 2497284c1978SDimitry Andric return; 2498284c1978SDimitry Andric 2499284c1978SDimitry Andric // OK, this is an internal linkage entity inside an extern "C" linkage 2500284c1978SDimitry Andric // specification. Make a note of that so we can give it the "expected" 2501284c1978SDimitry Andric // mangled name if nothing else is using that name. 2502284c1978SDimitry Andric std::pair<StaticExternCMap::iterator, bool> R = 2503284c1978SDimitry Andric StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 2504284c1978SDimitry Andric 2505284c1978SDimitry Andric // If we have multiple internal linkage entities with the same name 2506284c1978SDimitry Andric // in extern "C" regions, none of them gets that name. 2507284c1978SDimitry Andric if (!R.second) 250859d1ed5bSDimitry Andric R.first->second = nullptr; 2509284c1978SDimitry Andric } 2510284c1978SDimitry Andric 251133956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 251233956c43SDimitry Andric if (!CGM.supportsCOMDAT()) 251333956c43SDimitry Andric return false; 251433956c43SDimitry Andric 251533956c43SDimitry Andric if (D.hasAttr<SelectAnyAttr>()) 251633956c43SDimitry Andric return true; 251733956c43SDimitry Andric 251833956c43SDimitry Andric GVALinkage Linkage; 251933956c43SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(&D)) 252033956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 252133956c43SDimitry Andric else 252233956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 252333956c43SDimitry Andric 252433956c43SDimitry Andric switch (Linkage) { 252533956c43SDimitry Andric case GVA_Internal: 252633956c43SDimitry Andric case GVA_AvailableExternally: 252733956c43SDimitry Andric case GVA_StrongExternal: 252833956c43SDimitry Andric return false; 252933956c43SDimitry Andric case GVA_DiscardableODR: 253033956c43SDimitry Andric case GVA_StrongODR: 253133956c43SDimitry Andric return true; 253233956c43SDimitry Andric } 253333956c43SDimitry Andric llvm_unreachable("No such linkage"); 253433956c43SDimitry Andric } 253533956c43SDimitry Andric 253633956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 253733956c43SDimitry Andric llvm::GlobalObject &GO) { 253833956c43SDimitry Andric if (!shouldBeInCOMDAT(*this, D)) 253933956c43SDimitry Andric return; 254033956c43SDimitry Andric GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 254133956c43SDimitry Andric } 254233956c43SDimitry Andric 2543e7145dcbSDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition. 2544e7145dcbSDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 2545e7145dcbSDimitry Andric bool IsTentative) { 254644290647SDimitry Andric // OpenCL global variables of sampler type are translated to function calls, 254744290647SDimitry Andric // therefore no need to be translated. 2548f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 254944290647SDimitry Andric if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 255044290647SDimitry Andric return; 255144290647SDimitry Andric 255244290647SDimitry Andric llvm::Constant *Init = nullptr; 2553dff0c46cSDimitry Andric CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2554dff0c46cSDimitry Andric bool NeedsGlobalCtor = false; 2555dff0c46cSDimitry Andric bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 2556f22ef01cSRoman Divacky 2557dff0c46cSDimitry Andric const VarDecl *InitDecl; 2558dff0c46cSDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 2559f22ef01cSRoman Divacky 2560e7145dcbSDimitry Andric // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 2561e7145dcbSDimitry Andric // as part of their declaration." Sema has already checked for 2562e7145dcbSDimitry Andric // error cases, so we just need to set Init to UndefValue. 2563e7145dcbSDimitry Andric if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 2564e7145dcbSDimitry Andric D->hasAttr<CUDASharedAttr>()) 25650623d748SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 2566e7145dcbSDimitry Andric else if (!InitExpr) { 2567f22ef01cSRoman Divacky // This is a tentative definition; tentative definitions are 2568f22ef01cSRoman Divacky // implicitly initialized with { 0 }. 2569f22ef01cSRoman Divacky // 2570f22ef01cSRoman Divacky // Note that tentative definitions are only emitted at the end of 2571f22ef01cSRoman Divacky // a translation unit, so they should never have incomplete 2572f22ef01cSRoman Divacky // type. In addition, EmitTentativeDefinition makes sure that we 2573f22ef01cSRoman Divacky // never attempt to emit a tentative definition if a real one 2574f22ef01cSRoman Divacky // exists. A use may still exists, however, so we still may need 2575f22ef01cSRoman Divacky // to do a RAUW. 2576f22ef01cSRoman Divacky assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 2577f22ef01cSRoman Divacky Init = EmitNullConstant(D->getType()); 2578f22ef01cSRoman Divacky } else { 25797ae0e2c9SDimitry Andric initializedGlobalDecl = GlobalDecl(D); 2580dff0c46cSDimitry Andric Init = EmitConstantInit(*InitDecl); 2581f785676fSDimitry Andric 2582f22ef01cSRoman Divacky if (!Init) { 2583f22ef01cSRoman Divacky QualType T = InitExpr->getType(); 2584f22ef01cSRoman Divacky if (D->getType()->isReferenceType()) 2585f22ef01cSRoman Divacky T = D->getType(); 2586f22ef01cSRoman Divacky 2587dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus) { 2588f22ef01cSRoman Divacky Init = EmitNullConstant(T); 2589dff0c46cSDimitry Andric NeedsGlobalCtor = true; 2590f22ef01cSRoman Divacky } else { 2591f22ef01cSRoman Divacky ErrorUnsupported(D, "static initializer"); 2592f22ef01cSRoman Divacky Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 2593f22ef01cSRoman Divacky } 2594e580952dSDimitry Andric } else { 2595e580952dSDimitry Andric // We don't need an initializer, so remove the entry for the delayed 2596dff0c46cSDimitry Andric // initializer position (just in case this entry was delayed) if we 2597dff0c46cSDimitry Andric // also don't need to register a destructor. 2598dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 2599e580952dSDimitry Andric DelayedCXXInitPosition.erase(D); 2600f22ef01cSRoman Divacky } 2601f22ef01cSRoman Divacky } 2602f22ef01cSRoman Divacky 26036122f3e6SDimitry Andric llvm::Type* InitType = Init->getType(); 2604e7145dcbSDimitry Andric llvm::Constant *Entry = 260544290647SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 2606f22ef01cSRoman Divacky 2607f22ef01cSRoman Divacky // Strip off a bitcast if we got one back. 260859d1ed5bSDimitry Andric if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2609f22ef01cSRoman Divacky assert(CE->getOpcode() == llvm::Instruction::BitCast || 2610f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 2611f785676fSDimitry Andric // All zero index gep. 2612f22ef01cSRoman Divacky CE->getOpcode() == llvm::Instruction::GetElementPtr); 2613f22ef01cSRoman Divacky Entry = CE->getOperand(0); 2614f22ef01cSRoman Divacky } 2615f22ef01cSRoman Divacky 2616f22ef01cSRoman Divacky // Entry is now either a Function or GlobalVariable. 261759d1ed5bSDimitry Andric auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 2618f22ef01cSRoman Divacky 2619f22ef01cSRoman Divacky // We have a definition after a declaration with the wrong type. 2620f22ef01cSRoman Divacky // We must make a new GlobalVariable* and update everything that used OldGV 2621f22ef01cSRoman Divacky // (a declaration or tentative definition) with the new GlobalVariable* 2622f22ef01cSRoman Divacky // (which will be a definition). 2623f22ef01cSRoman Divacky // 2624f22ef01cSRoman Divacky // This happens if there is a prototype for a global (e.g. 2625f22ef01cSRoman Divacky // "extern int x[];") and then a definition of a different type (e.g. 2626f22ef01cSRoman Divacky // "int x[10];"). This also happens when an initializer has a different type 2627f22ef01cSRoman Divacky // from the type of the global (this happens with unions). 262859d1ed5bSDimitry Andric if (!GV || 2629f22ef01cSRoman Divacky GV->getType()->getElementType() != InitType || 26303b0f4066SDimitry Andric GV->getType()->getAddressSpace() != 26317ae0e2c9SDimitry Andric GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 2632f22ef01cSRoman Divacky 2633f22ef01cSRoman Divacky // Move the old entry aside so that we'll create a new one. 26346122f3e6SDimitry Andric Entry->setName(StringRef()); 2635f22ef01cSRoman Divacky 2636f22ef01cSRoman Divacky // Make a new global with the correct type, this is now guaranteed to work. 2637e7145dcbSDimitry Andric GV = cast<llvm::GlobalVariable>( 263844290647SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))); 2639f22ef01cSRoman Divacky 2640f22ef01cSRoman Divacky // Replace all uses of the old global with the new global 2641f22ef01cSRoman Divacky llvm::Constant *NewPtrForOldDecl = 2642f22ef01cSRoman Divacky llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2643f22ef01cSRoman Divacky Entry->replaceAllUsesWith(NewPtrForOldDecl); 2644f22ef01cSRoman Divacky 2645f22ef01cSRoman Divacky // Erase the old global, since it is no longer used. 2646f22ef01cSRoman Divacky cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 2647f22ef01cSRoman Divacky } 2648f22ef01cSRoman Divacky 2649284c1978SDimitry Andric MaybeHandleStaticInExternC(D, GV); 2650284c1978SDimitry Andric 26516122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 26526122f3e6SDimitry Andric AddGlobalAnnotations(D, GV); 2653f22ef01cSRoman Divacky 2654e7145dcbSDimitry Andric // Set the llvm linkage type as appropriate. 2655e7145dcbSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 2656e7145dcbSDimitry Andric getLLVMLinkageVarDefinition(D, GV->isConstant()); 2657e7145dcbSDimitry Andric 26580623d748SDimitry Andric // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 26590623d748SDimitry Andric // the device. [...]" 26600623d748SDimitry Andric // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 26610623d748SDimitry Andric // __device__, declares a variable that: [...] 26620623d748SDimitry Andric // Is accessible from all the threads within the grid and from the host 26630623d748SDimitry Andric // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 26640623d748SDimitry Andric // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 2665e7145dcbSDimitry Andric if (GV && LangOpts.CUDA) { 2666e7145dcbSDimitry Andric if (LangOpts.CUDAIsDevice) { 2667e7145dcbSDimitry Andric if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) 26680623d748SDimitry Andric GV->setExternallyInitialized(true); 2669e7145dcbSDimitry Andric } else { 2670e7145dcbSDimitry Andric // Host-side shadows of external declarations of device-side 2671e7145dcbSDimitry Andric // global variables become internal definitions. These have to 2672e7145dcbSDimitry Andric // be internal in order to prevent name conflicts with global 2673e7145dcbSDimitry Andric // host variables with the same name in a different TUs. 2674e7145dcbSDimitry Andric if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) { 2675e7145dcbSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 2676e7145dcbSDimitry Andric 2677e7145dcbSDimitry Andric // Shadow variables and their properties must be registered 2678e7145dcbSDimitry Andric // with CUDA runtime. 2679e7145dcbSDimitry Andric unsigned Flags = 0; 2680e7145dcbSDimitry Andric if (!D->hasDefinition()) 2681e7145dcbSDimitry Andric Flags |= CGCUDARuntime::ExternDeviceVar; 2682e7145dcbSDimitry Andric if (D->hasAttr<CUDAConstantAttr>()) 2683e7145dcbSDimitry Andric Flags |= CGCUDARuntime::ConstantDeviceVar; 2684e7145dcbSDimitry Andric getCUDARuntime().registerDeviceVar(*GV, Flags); 2685e7145dcbSDimitry Andric } else if (D->hasAttr<CUDASharedAttr>()) 2686e7145dcbSDimitry Andric // __shared__ variables are odd. Shadows do get created, but 2687e7145dcbSDimitry Andric // they are not registered with the CUDA runtime, so they 2688e7145dcbSDimitry Andric // can't really be used to access their device-side 2689e7145dcbSDimitry Andric // counterparts. It's not clear yet whether it's nvcc's bug or 2690e7145dcbSDimitry Andric // a feature, but we've got to do the same for compatibility. 2691e7145dcbSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 2692e7145dcbSDimitry Andric } 26930623d748SDimitry Andric } 2694f22ef01cSRoman Divacky GV->setInitializer(Init); 2695f22ef01cSRoman Divacky 2696f22ef01cSRoman Divacky // If it is safe to mark the global 'constant', do so now. 2697dff0c46cSDimitry Andric GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 2698dff0c46cSDimitry Andric isTypeConstant(D->getType(), true)); 2699f22ef01cSRoman Divacky 270039d628a0SDimitry Andric // If it is in a read-only section, mark it 'constant'. 270139d628a0SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 270239d628a0SDimitry Andric const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 270339d628a0SDimitry Andric if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 270439d628a0SDimitry Andric GV->setConstant(true); 270539d628a0SDimitry Andric } 270639d628a0SDimitry Andric 2707f22ef01cSRoman Divacky GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 2708f22ef01cSRoman Divacky 2709f785676fSDimitry Andric 27100623d748SDimitry Andric // On Darwin, if the normal linkage of a C++ thread_local variable is 27110623d748SDimitry Andric // LinkOnce or Weak, we keep the normal linkage to prevent multiple 27120623d748SDimitry Andric // copies within a linkage unit; otherwise, the backing variable has 27130623d748SDimitry Andric // internal linkage and all accesses should just be calls to the 271459d1ed5bSDimitry Andric // Itanium-specified entry point, which has the normal linkage of the 27150623d748SDimitry Andric // variable. This is to preserve the ability to change the implementation 27160623d748SDimitry Andric // behind the scenes. 271739d628a0SDimitry Andric if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic && 27180623d748SDimitry Andric Context.getTargetInfo().getTriple().isOSDarwin() && 27190623d748SDimitry Andric !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) && 27200623d748SDimitry Andric !llvm::GlobalVariable::isWeakLinkage(Linkage)) 272159d1ed5bSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 272259d1ed5bSDimitry Andric 272359d1ed5bSDimitry Andric GV->setLinkage(Linkage); 272459d1ed5bSDimitry Andric if (D->hasAttr<DLLImportAttr>()) 272559d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 272659d1ed5bSDimitry Andric else if (D->hasAttr<DLLExportAttr>()) 272759d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 272839d628a0SDimitry Andric else 272939d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 2730f785676fSDimitry Andric 273144290647SDimitry Andric if (Linkage == llvm::GlobalVariable::CommonLinkage) { 2732f22ef01cSRoman Divacky // common vars aren't constant even if declared const. 2733f22ef01cSRoman Divacky GV->setConstant(false); 273444290647SDimitry Andric // Tentative definition of global variables may be initialized with 273544290647SDimitry Andric // non-zero null pointers. In this case they should have weak linkage 273644290647SDimitry Andric // since common linkage must have zero initializer and must not have 273744290647SDimitry Andric // explicit section therefore cannot have non-zero initial value. 273844290647SDimitry Andric if (!GV->getInitializer()->isNullValue()) 273944290647SDimitry Andric GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 274044290647SDimitry Andric } 2741f22ef01cSRoman Divacky 274259d1ed5bSDimitry Andric setNonAliasAttributes(D, GV); 2743f22ef01cSRoman Divacky 274439d628a0SDimitry Andric if (D->getTLSKind() && !GV->isThreadLocal()) { 274539d628a0SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 27460623d748SDimitry Andric CXXThreadLocals.push_back(D); 274739d628a0SDimitry Andric setTLSMode(GV, *D); 274839d628a0SDimitry Andric } 274939d628a0SDimitry Andric 275033956c43SDimitry Andric maybeSetTrivialComdat(*D, *GV); 275133956c43SDimitry Andric 27522754fe60SDimitry Andric // Emit the initializer function if necessary. 2753dff0c46cSDimitry Andric if (NeedsGlobalCtor || NeedsGlobalDtor) 2754dff0c46cSDimitry Andric EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 27552754fe60SDimitry Andric 275639d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 27573861d79fSDimitry Andric 2758f22ef01cSRoman Divacky // Emit global variable debug information. 27596122f3e6SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 2760e7145dcbSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 2761f22ef01cSRoman Divacky DI->EmitGlobalVariable(GV, D); 2762f22ef01cSRoman Divacky } 2763f22ef01cSRoman Divacky 276439d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context, 276533956c43SDimitry Andric CodeGenModule &CGM, const VarDecl *D, 276633956c43SDimitry Andric bool NoCommon) { 276759d1ed5bSDimitry Andric // Don't give variables common linkage if -fno-common was specified unless it 276859d1ed5bSDimitry Andric // was overridden by a NoCommon attribute. 276959d1ed5bSDimitry Andric if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 277059d1ed5bSDimitry Andric return true; 277159d1ed5bSDimitry Andric 277259d1ed5bSDimitry Andric // C11 6.9.2/2: 277359d1ed5bSDimitry Andric // A declaration of an identifier for an object that has file scope without 277459d1ed5bSDimitry Andric // an initializer, and without a storage-class specifier or with the 277559d1ed5bSDimitry Andric // storage-class specifier static, constitutes a tentative definition. 277659d1ed5bSDimitry Andric if (D->getInit() || D->hasExternalStorage()) 277759d1ed5bSDimitry Andric return true; 277859d1ed5bSDimitry Andric 277959d1ed5bSDimitry Andric // A variable cannot be both common and exist in a section. 278059d1ed5bSDimitry Andric if (D->hasAttr<SectionAttr>()) 278159d1ed5bSDimitry Andric return true; 278259d1ed5bSDimitry Andric 278359d1ed5bSDimitry Andric // Thread local vars aren't considered common linkage. 278459d1ed5bSDimitry Andric if (D->getTLSKind()) 278559d1ed5bSDimitry Andric return true; 278659d1ed5bSDimitry Andric 278759d1ed5bSDimitry Andric // Tentative definitions marked with WeakImportAttr are true definitions. 278859d1ed5bSDimitry Andric if (D->hasAttr<WeakImportAttr>()) 278959d1ed5bSDimitry Andric return true; 279059d1ed5bSDimitry Andric 279133956c43SDimitry Andric // A variable cannot be both common and exist in a comdat. 279233956c43SDimitry Andric if (shouldBeInCOMDAT(CGM, *D)) 279333956c43SDimitry Andric return true; 279433956c43SDimitry Andric 2795e7145dcbSDimitry Andric // Declarations with a required alignment do not have common linkage in MSVC 279639d628a0SDimitry Andric // mode. 27970623d748SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 279833956c43SDimitry Andric if (D->hasAttr<AlignedAttr>()) 279939d628a0SDimitry Andric return true; 280033956c43SDimitry Andric QualType VarType = D->getType(); 280133956c43SDimitry Andric if (Context.isAlignmentRequired(VarType)) 280233956c43SDimitry Andric return true; 280333956c43SDimitry Andric 280433956c43SDimitry Andric if (const auto *RT = VarType->getAs<RecordType>()) { 280533956c43SDimitry Andric const RecordDecl *RD = RT->getDecl(); 280633956c43SDimitry Andric for (const FieldDecl *FD : RD->fields()) { 280733956c43SDimitry Andric if (FD->isBitField()) 280833956c43SDimitry Andric continue; 280933956c43SDimitry Andric if (FD->hasAttr<AlignedAttr>()) 281033956c43SDimitry Andric return true; 281133956c43SDimitry Andric if (Context.isAlignmentRequired(FD->getType())) 281233956c43SDimitry Andric return true; 281333956c43SDimitry Andric } 281433956c43SDimitry Andric } 281533956c43SDimitry Andric } 281639d628a0SDimitry Andric 281759d1ed5bSDimitry Andric return false; 281859d1ed5bSDimitry Andric } 281959d1ed5bSDimitry Andric 282059d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 282159d1ed5bSDimitry Andric const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 28222754fe60SDimitry Andric if (Linkage == GVA_Internal) 28232754fe60SDimitry Andric return llvm::Function::InternalLinkage; 282459d1ed5bSDimitry Andric 282559d1ed5bSDimitry Andric if (D->hasAttr<WeakAttr>()) { 282659d1ed5bSDimitry Andric if (IsConstantVariable) 282759d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 282859d1ed5bSDimitry Andric else 282959d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakAnyLinkage; 283059d1ed5bSDimitry Andric } 283159d1ed5bSDimitry Andric 283259d1ed5bSDimitry Andric // We are guaranteed to have a strong definition somewhere else, 283359d1ed5bSDimitry Andric // so we can use available_externally linkage. 283459d1ed5bSDimitry Andric if (Linkage == GVA_AvailableExternally) 283520e90f04SDimitry Andric return llvm::GlobalValue::AvailableExternallyLinkage; 283659d1ed5bSDimitry Andric 283759d1ed5bSDimitry Andric // Note that Apple's kernel linker doesn't support symbol 283859d1ed5bSDimitry Andric // coalescing, so we need to avoid linkonce and weak linkages there. 283959d1ed5bSDimitry Andric // Normally, this means we just map to internal, but for explicit 284059d1ed5bSDimitry Andric // instantiations we'll map to external. 284159d1ed5bSDimitry Andric 284259d1ed5bSDimitry Andric // In C++, the compiler has to emit a definition in every translation unit 284359d1ed5bSDimitry Andric // that references the function. We should use linkonce_odr because 284459d1ed5bSDimitry Andric // a) if all references in this translation unit are optimized away, we 284559d1ed5bSDimitry Andric // don't need to codegen it. b) if the function persists, it needs to be 284659d1ed5bSDimitry Andric // merged with other definitions. c) C++ has the ODR, so we know the 284759d1ed5bSDimitry Andric // definition is dependable. 284859d1ed5bSDimitry Andric if (Linkage == GVA_DiscardableODR) 284959d1ed5bSDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 285059d1ed5bSDimitry Andric : llvm::Function::InternalLinkage; 285159d1ed5bSDimitry Andric 285259d1ed5bSDimitry Andric // An explicit instantiation of a template has weak linkage, since 285359d1ed5bSDimitry Andric // explicit instantiations can occur in multiple translation units 285459d1ed5bSDimitry Andric // and must all be equivalent. However, we are not allowed to 285559d1ed5bSDimitry Andric // throw away these explicit instantiations. 2856e7145dcbSDimitry Andric // 2857e7145dcbSDimitry Andric // We don't currently support CUDA device code spread out across multiple TUs, 2858e7145dcbSDimitry Andric // so say that CUDA templates are either external (for kernels) or internal. 2859e7145dcbSDimitry Andric // This lets llvm perform aggressive inter-procedural optimizations. 2860e7145dcbSDimitry Andric if (Linkage == GVA_StrongODR) { 2861e7145dcbSDimitry Andric if (Context.getLangOpts().AppleKext) 2862e7145dcbSDimitry Andric return llvm::Function::ExternalLinkage; 2863e7145dcbSDimitry Andric if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) 2864e7145dcbSDimitry Andric return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 2865e7145dcbSDimitry Andric : llvm::Function::InternalLinkage; 2866e7145dcbSDimitry Andric return llvm::Function::WeakODRLinkage; 2867e7145dcbSDimitry Andric } 286859d1ed5bSDimitry Andric 286959d1ed5bSDimitry Andric // C++ doesn't have tentative definitions and thus cannot have common 287059d1ed5bSDimitry Andric // linkage. 287159d1ed5bSDimitry Andric if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 287233956c43SDimitry Andric !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 287339d628a0SDimitry Andric CodeGenOpts.NoCommon)) 287459d1ed5bSDimitry Andric return llvm::GlobalVariable::CommonLinkage; 287559d1ed5bSDimitry Andric 2876f785676fSDimitry Andric // selectany symbols are externally visible, so use weak instead of 2877f785676fSDimitry Andric // linkonce. MSVC optimizes away references to const selectany globals, so 2878f785676fSDimitry Andric // all definitions should be the same and ODR linkage should be used. 2879f785676fSDimitry Andric // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 288059d1ed5bSDimitry Andric if (D->hasAttr<SelectAnyAttr>()) 2881f785676fSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 288259d1ed5bSDimitry Andric 288359d1ed5bSDimitry Andric // Otherwise, we have strong external linkage. 288459d1ed5bSDimitry Andric assert(Linkage == GVA_StrongExternal); 28852754fe60SDimitry Andric return llvm::GlobalVariable::ExternalLinkage; 28862754fe60SDimitry Andric } 28872754fe60SDimitry Andric 288859d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 288959d1ed5bSDimitry Andric const VarDecl *VD, bool IsConstant) { 289059d1ed5bSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 289159d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 289259d1ed5bSDimitry Andric } 289359d1ed5bSDimitry Andric 2894139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type. 2895139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites 2896139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 2897139f7f9bSDimitry Andric llvm::Function *newFn) { 2898139f7f9bSDimitry Andric // Fast path. 2899139f7f9bSDimitry Andric if (old->use_empty()) return; 2900139f7f9bSDimitry Andric 2901139f7f9bSDimitry Andric llvm::Type *newRetTy = newFn->getReturnType(); 2902139f7f9bSDimitry Andric SmallVector<llvm::Value*, 4> newArgs; 29030623d748SDimitry Andric SmallVector<llvm::OperandBundleDef, 1> newBundles; 2904139f7f9bSDimitry Andric 2905139f7f9bSDimitry Andric for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 2906139f7f9bSDimitry Andric ui != ue; ) { 2907139f7f9bSDimitry Andric llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 290859d1ed5bSDimitry Andric llvm::User *user = use->getUser(); 2909139f7f9bSDimitry Andric 2910139f7f9bSDimitry Andric // Recognize and replace uses of bitcasts. Most calls to 2911139f7f9bSDimitry Andric // unprototyped functions will use bitcasts. 291259d1ed5bSDimitry Andric if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 2913139f7f9bSDimitry Andric if (bitcast->getOpcode() == llvm::Instruction::BitCast) 2914139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(bitcast, newFn); 2915139f7f9bSDimitry Andric continue; 2916139f7f9bSDimitry Andric } 2917139f7f9bSDimitry Andric 2918139f7f9bSDimitry Andric // Recognize calls to the function. 2919139f7f9bSDimitry Andric llvm::CallSite callSite(user); 2920139f7f9bSDimitry Andric if (!callSite) continue; 292159d1ed5bSDimitry Andric if (!callSite.isCallee(&*use)) continue; 2922139f7f9bSDimitry Andric 2923139f7f9bSDimitry Andric // If the return types don't match exactly, then we can't 2924139f7f9bSDimitry Andric // transform this call unless it's dead. 2925139f7f9bSDimitry Andric if (callSite->getType() != newRetTy && !callSite->use_empty()) 2926139f7f9bSDimitry Andric continue; 2927139f7f9bSDimitry Andric 2928139f7f9bSDimitry Andric // Get the call site's attribute list. 292920e90f04SDimitry Andric SmallVector<llvm::AttributeSet, 8> newArgAttrs; 293020e90f04SDimitry Andric llvm::AttributeList oldAttrs = callSite.getAttributes(); 2931139f7f9bSDimitry Andric 2932139f7f9bSDimitry Andric // If the function was passed too few arguments, don't transform. 2933139f7f9bSDimitry Andric unsigned newNumArgs = newFn->arg_size(); 2934139f7f9bSDimitry Andric if (callSite.arg_size() < newNumArgs) continue; 2935139f7f9bSDimitry Andric 2936139f7f9bSDimitry Andric // If extra arguments were passed, we silently drop them. 2937139f7f9bSDimitry Andric // If any of the types mismatch, we don't transform. 2938139f7f9bSDimitry Andric unsigned argNo = 0; 2939139f7f9bSDimitry Andric bool dontTransform = false; 294020e90f04SDimitry Andric for (llvm::Argument &A : newFn->args()) { 294120e90f04SDimitry Andric if (callSite.getArgument(argNo)->getType() != A.getType()) { 2942139f7f9bSDimitry Andric dontTransform = true; 2943139f7f9bSDimitry Andric break; 2944139f7f9bSDimitry Andric } 2945139f7f9bSDimitry Andric 2946139f7f9bSDimitry Andric // Add any parameter attributes. 294720e90f04SDimitry Andric newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo)); 294820e90f04SDimitry Andric argNo++; 2949139f7f9bSDimitry Andric } 2950139f7f9bSDimitry Andric if (dontTransform) 2951139f7f9bSDimitry Andric continue; 2952139f7f9bSDimitry Andric 2953139f7f9bSDimitry Andric // Okay, we can transform this. Create the new call instruction and copy 2954139f7f9bSDimitry Andric // over the required information. 2955139f7f9bSDimitry Andric newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 2956139f7f9bSDimitry Andric 29570623d748SDimitry Andric // Copy over any operand bundles. 29580623d748SDimitry Andric callSite.getOperandBundlesAsDefs(newBundles); 29590623d748SDimitry Andric 2960139f7f9bSDimitry Andric llvm::CallSite newCall; 2961139f7f9bSDimitry Andric if (callSite.isCall()) { 29620623d748SDimitry Andric newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "", 2963139f7f9bSDimitry Andric callSite.getInstruction()); 2964139f7f9bSDimitry Andric } else { 296559d1ed5bSDimitry Andric auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction()); 2966139f7f9bSDimitry Andric newCall = llvm::InvokeInst::Create(newFn, 2967139f7f9bSDimitry Andric oldInvoke->getNormalDest(), 2968139f7f9bSDimitry Andric oldInvoke->getUnwindDest(), 29690623d748SDimitry Andric newArgs, newBundles, "", 2970139f7f9bSDimitry Andric callSite.getInstruction()); 2971139f7f9bSDimitry Andric } 2972139f7f9bSDimitry Andric newArgs.clear(); // for the next iteration 2973139f7f9bSDimitry Andric 2974139f7f9bSDimitry Andric if (!newCall->getType()->isVoidTy()) 2975139f7f9bSDimitry Andric newCall->takeName(callSite.getInstruction()); 297620e90f04SDimitry Andric newCall.setAttributes(llvm::AttributeList::get( 297720e90f04SDimitry Andric newFn->getContext(), oldAttrs.getFnAttributes(), 297820e90f04SDimitry Andric oldAttrs.getRetAttributes(), newArgAttrs)); 2979139f7f9bSDimitry Andric newCall.setCallingConv(callSite.getCallingConv()); 2980139f7f9bSDimitry Andric 2981139f7f9bSDimitry Andric // Finally, remove the old call, replacing any uses with the new one. 2982139f7f9bSDimitry Andric if (!callSite->use_empty()) 2983139f7f9bSDimitry Andric callSite->replaceAllUsesWith(newCall.getInstruction()); 2984139f7f9bSDimitry Andric 2985139f7f9bSDimitry Andric // Copy debug location attached to CI. 298633956c43SDimitry Andric if (callSite->getDebugLoc()) 2987139f7f9bSDimitry Andric newCall->setDebugLoc(callSite->getDebugLoc()); 29880623d748SDimitry Andric 2989139f7f9bSDimitry Andric callSite->eraseFromParent(); 2990139f7f9bSDimitry Andric } 2991139f7f9bSDimitry Andric } 2992139f7f9bSDimitry Andric 2993f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 2994f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}". If there are 2995f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to 2996f22ef01cSRoman Divacky /// call the new function directly. 2997f22ef01cSRoman Divacky /// 2998f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to 2999f22ef01cSRoman Divacky /// functions to be able to inline them. If there is a bitcast in the way, it 3000f22ef01cSRoman Divacky /// won't inline them. Instcombine normally deletes these calls, but it isn't 3001f22ef01cSRoman Divacky /// run at -O0. 3002f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 3003f22ef01cSRoman Divacky llvm::Function *NewFn) { 3004f22ef01cSRoman Divacky // If we're redefining a global as a function, don't transform it. 3005139f7f9bSDimitry Andric if (!isa<llvm::Function>(Old)) return; 3006f22ef01cSRoman Divacky 3007139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(Old, NewFn); 3008f22ef01cSRoman Divacky } 3009f22ef01cSRoman Divacky 3010dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 3011e7145dcbSDimitry Andric auto DK = VD->isThisDeclarationADefinition(); 3012e7145dcbSDimitry Andric if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 3013e7145dcbSDimitry Andric return; 3014e7145dcbSDimitry Andric 3015dff0c46cSDimitry Andric TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 3016dff0c46cSDimitry Andric // If we have a definition, this might be a deferred decl. If the 3017dff0c46cSDimitry Andric // instantiation is explicit, make sure we emit it at the end. 3018dff0c46cSDimitry Andric if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 3019dff0c46cSDimitry Andric GetAddrOfGlobalVar(VD); 3020139f7f9bSDimitry Andric 3021139f7f9bSDimitry Andric EmitTopLevelDecl(VD); 3022dff0c46cSDimitry Andric } 3023f22ef01cSRoman Divacky 302459d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 302559d1ed5bSDimitry Andric llvm::GlobalValue *GV) { 302659d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 30273b0f4066SDimitry Andric 30283b0f4066SDimitry Andric // Compute the function info and LLVM type. 3029dff0c46cSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3030dff0c46cSDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 30313b0f4066SDimitry Andric 3032f22ef01cSRoman Divacky // Get or create the prototype for the function. 30330623d748SDimitry Andric if (!GV || (GV->getType()->getElementType() != Ty)) 30340623d748SDimitry Andric GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 30350623d748SDimitry Andric /*DontDefer=*/true, 303644290647SDimitry Andric ForDefinition)); 3037f22ef01cSRoman Divacky 30380623d748SDimitry Andric // Already emitted. 30390623d748SDimitry Andric if (!GV->isDeclaration()) 3040f785676fSDimitry Andric return; 3041f22ef01cSRoman Divacky 30422754fe60SDimitry Andric // We need to set linkage and visibility on the function before 30432754fe60SDimitry Andric // generating code for it because various parts of IR generation 30442754fe60SDimitry Andric // want to propagate this information down (e.g. to local static 30452754fe60SDimitry Andric // declarations). 304659d1ed5bSDimitry Andric auto *Fn = cast<llvm::Function>(GV); 3047f785676fSDimitry Andric setFunctionLinkage(GD, Fn); 304897bc6c73SDimitry Andric setFunctionDLLStorageClass(GD, Fn); 3049f22ef01cSRoman Divacky 305059d1ed5bSDimitry Andric // FIXME: this is redundant with part of setFunctionDefinitionAttributes 30512754fe60SDimitry Andric setGlobalVisibility(Fn, D); 30522754fe60SDimitry Andric 3053284c1978SDimitry Andric MaybeHandleStaticInExternC(D, Fn); 3054284c1978SDimitry Andric 305533956c43SDimitry Andric maybeSetTrivialComdat(*D, *Fn); 305633956c43SDimitry Andric 30573b0f4066SDimitry Andric CodeGenFunction(*this).GenerateCode(D, Fn, FI); 3058f22ef01cSRoman Divacky 305959d1ed5bSDimitry Andric setFunctionDefinitionAttributes(D, Fn); 3060f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, Fn); 3061f22ef01cSRoman Divacky 3062f22ef01cSRoman Divacky if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 3063f22ef01cSRoman Divacky AddGlobalCtor(Fn, CA->getPriority()); 3064f22ef01cSRoman Divacky if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 3065f22ef01cSRoman Divacky AddGlobalDtor(Fn, DA->getPriority()); 30666122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 30676122f3e6SDimitry Andric AddGlobalAnnotations(D, Fn); 3068f22ef01cSRoman Divacky } 3069f22ef01cSRoman Divacky 3070f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 307159d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 3072f22ef01cSRoman Divacky const AliasAttr *AA = D->getAttr<AliasAttr>(); 3073f22ef01cSRoman Divacky assert(AA && "Not an alias?"); 3074f22ef01cSRoman Divacky 30756122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 3076f22ef01cSRoman Divacky 30779a4b3118SDimitry Andric if (AA->getAliasee() == MangledName) { 3078e7145dcbSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 30799a4b3118SDimitry Andric return; 30809a4b3118SDimitry Andric } 30819a4b3118SDimitry Andric 3082f22ef01cSRoman Divacky // If there is a definition in the module, then it wins over the alias. 3083f22ef01cSRoman Divacky // This is dubious, but allow it to be safe. Just ignore the alias. 3084f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3085f22ef01cSRoman Divacky if (Entry && !Entry->isDeclaration()) 3086f22ef01cSRoman Divacky return; 3087f22ef01cSRoman Divacky 3088f785676fSDimitry Andric Aliases.push_back(GD); 3089f785676fSDimitry Andric 30906122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 3091f22ef01cSRoman Divacky 3092f22ef01cSRoman Divacky // Create a reference to the named value. This ensures that it is emitted 3093f22ef01cSRoman Divacky // if a deferred decl. 3094f22ef01cSRoman Divacky llvm::Constant *Aliasee; 3095f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 30963861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 30972754fe60SDimitry Andric /*ForVTable=*/false); 3098f22ef01cSRoman Divacky else 3099f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 310059d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 310139d628a0SDimitry Andric /*D=*/nullptr); 3102f22ef01cSRoman Divacky 3103f22ef01cSRoman Divacky // Create the new alias itself, but don't set a name yet. 310459d1ed5bSDimitry Andric auto *GA = llvm::GlobalAlias::create( 31050623d748SDimitry Andric DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule()); 3106f22ef01cSRoman Divacky 3107f22ef01cSRoman Divacky if (Entry) { 310859d1ed5bSDimitry Andric if (GA->getAliasee() == Entry) { 3109e7145dcbSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 311059d1ed5bSDimitry Andric return; 311159d1ed5bSDimitry Andric } 311259d1ed5bSDimitry Andric 3113f22ef01cSRoman Divacky assert(Entry->isDeclaration()); 3114f22ef01cSRoman Divacky 3115f22ef01cSRoman Divacky // If there is a declaration in the module, then we had an extern followed 3116f22ef01cSRoman Divacky // by the alias, as in: 3117f22ef01cSRoman Divacky // extern int test6(); 3118f22ef01cSRoman Divacky // ... 3119f22ef01cSRoman Divacky // int test6() __attribute__((alias("test7"))); 3120f22ef01cSRoman Divacky // 3121f22ef01cSRoman Divacky // Remove it and replace uses of it with the alias. 3122f22ef01cSRoman Divacky GA->takeName(Entry); 3123f22ef01cSRoman Divacky 3124f22ef01cSRoman Divacky Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 3125f22ef01cSRoman Divacky Entry->getType())); 3126f22ef01cSRoman Divacky Entry->eraseFromParent(); 3127f22ef01cSRoman Divacky } else { 3128ffd1746dSEd Schouten GA->setName(MangledName); 3129f22ef01cSRoman Divacky } 3130f22ef01cSRoman Divacky 3131f22ef01cSRoman Divacky // Set attributes which are particular to an alias; this is a 3132f22ef01cSRoman Divacky // specialization of the attributes which may be set on a global 3133f22ef01cSRoman Divacky // variable/function. 313439d628a0SDimitry Andric if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 31353b0f4066SDimitry Andric D->isWeakImported()) { 3136f22ef01cSRoman Divacky GA->setLinkage(llvm::Function::WeakAnyLinkage); 3137f22ef01cSRoman Divacky } 3138f22ef01cSRoman Divacky 313939d628a0SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 314039d628a0SDimitry Andric if (VD->getTLSKind()) 314139d628a0SDimitry Andric setTLSMode(GA, *VD); 314239d628a0SDimitry Andric 314339d628a0SDimitry Andric setAliasAttributes(D, GA); 3144f22ef01cSRoman Divacky } 3145f22ef01cSRoman Divacky 3146e7145dcbSDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 3147e7145dcbSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 3148e7145dcbSDimitry Andric const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 3149e7145dcbSDimitry Andric assert(IFA && "Not an ifunc?"); 3150e7145dcbSDimitry Andric 3151e7145dcbSDimitry Andric StringRef MangledName = getMangledName(GD); 3152e7145dcbSDimitry Andric 3153e7145dcbSDimitry Andric if (IFA->getResolver() == MangledName) { 3154e7145dcbSDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 3155e7145dcbSDimitry Andric return; 3156e7145dcbSDimitry Andric } 3157e7145dcbSDimitry Andric 3158e7145dcbSDimitry Andric // Report an error if some definition overrides ifunc. 3159e7145dcbSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3160e7145dcbSDimitry Andric if (Entry && !Entry->isDeclaration()) { 3161e7145dcbSDimitry Andric GlobalDecl OtherGD; 3162e7145dcbSDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 3163e7145dcbSDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 3164e7145dcbSDimitry Andric Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name); 3165e7145dcbSDimitry Andric Diags.Report(OtherGD.getDecl()->getLocation(), 3166e7145dcbSDimitry Andric diag::note_previous_definition); 3167e7145dcbSDimitry Andric } 3168e7145dcbSDimitry Andric return; 3169e7145dcbSDimitry Andric } 3170e7145dcbSDimitry Andric 3171e7145dcbSDimitry Andric Aliases.push_back(GD); 3172e7145dcbSDimitry Andric 3173e7145dcbSDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 3174e7145dcbSDimitry Andric llvm::Constant *Resolver = 3175e7145dcbSDimitry Andric GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD, 3176e7145dcbSDimitry Andric /*ForVTable=*/false); 3177e7145dcbSDimitry Andric llvm::GlobalIFunc *GIF = 3178e7145dcbSDimitry Andric llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 3179e7145dcbSDimitry Andric "", Resolver, &getModule()); 3180e7145dcbSDimitry Andric if (Entry) { 3181e7145dcbSDimitry Andric if (GIF->getResolver() == Entry) { 3182e7145dcbSDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 3183e7145dcbSDimitry Andric return; 3184e7145dcbSDimitry Andric } 3185e7145dcbSDimitry Andric assert(Entry->isDeclaration()); 3186e7145dcbSDimitry Andric 3187e7145dcbSDimitry Andric // If there is a declaration in the module, then we had an extern followed 3188e7145dcbSDimitry Andric // by the ifunc, as in: 3189e7145dcbSDimitry Andric // extern int test(); 3190e7145dcbSDimitry Andric // ... 3191e7145dcbSDimitry Andric // int test() __attribute__((ifunc("resolver"))); 3192e7145dcbSDimitry Andric // 3193e7145dcbSDimitry Andric // Remove it and replace uses of it with the ifunc. 3194e7145dcbSDimitry Andric GIF->takeName(Entry); 3195e7145dcbSDimitry Andric 3196e7145dcbSDimitry Andric Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 3197e7145dcbSDimitry Andric Entry->getType())); 3198e7145dcbSDimitry Andric Entry->eraseFromParent(); 3199e7145dcbSDimitry Andric } else 3200e7145dcbSDimitry Andric GIF->setName(MangledName); 3201e7145dcbSDimitry Andric 3202e7145dcbSDimitry Andric SetCommonAttributes(D, GIF); 3203e7145dcbSDimitry Andric } 3204e7145dcbSDimitry Andric 320517a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 32066122f3e6SDimitry Andric ArrayRef<llvm::Type*> Tys) { 320717a519f9SDimitry Andric return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 320817a519f9SDimitry Andric Tys); 3209f22ef01cSRoman Divacky } 3210f22ef01cSRoman Divacky 321133956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 321233956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 321333956c43SDimitry Andric const StringLiteral *Literal, bool TargetIsLSB, 321433956c43SDimitry Andric bool &IsUTF16, unsigned &StringLength) { 32156122f3e6SDimitry Andric StringRef String = Literal->getString(); 3216e580952dSDimitry Andric unsigned NumBytes = String.size(); 3217f22ef01cSRoman Divacky 3218f22ef01cSRoman Divacky // Check for simple case. 3219f22ef01cSRoman Divacky if (!Literal->containsNonAsciiOrNull()) { 3220f22ef01cSRoman Divacky StringLength = NumBytes; 322139d628a0SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 3222f22ef01cSRoman Divacky } 3223f22ef01cSRoman Divacky 3224dff0c46cSDimitry Andric // Otherwise, convert the UTF8 literals into a string of shorts. 3225dff0c46cSDimitry Andric IsUTF16 = true; 3226dff0c46cSDimitry Andric 322744290647SDimitry Andric SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 322844290647SDimitry Andric const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 322944290647SDimitry Andric llvm::UTF16 *ToPtr = &ToBuf[0]; 3230f22ef01cSRoman Divacky 323144290647SDimitry Andric (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 323244290647SDimitry Andric ToPtr + NumBytes, llvm::strictConversion); 3233f22ef01cSRoman Divacky 3234f22ef01cSRoman Divacky // ConvertUTF8toUTF16 returns the length in ToPtr. 3235f22ef01cSRoman Divacky StringLength = ToPtr - &ToBuf[0]; 3236f22ef01cSRoman Divacky 3237dff0c46cSDimitry Andric // Add an explicit null. 3238dff0c46cSDimitry Andric *ToPtr = 0; 323939d628a0SDimitry Andric return *Map.insert(std::make_pair( 324039d628a0SDimitry Andric StringRef(reinterpret_cast<const char *>(ToBuf.data()), 324139d628a0SDimitry Andric (StringLength + 1) * 2), 324239d628a0SDimitry Andric nullptr)).first; 3243f22ef01cSRoman Divacky } 3244f22ef01cSRoman Divacky 32450623d748SDimitry Andric ConstantAddress 3246f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 3247f22ef01cSRoman Divacky unsigned StringLength = 0; 3248f22ef01cSRoman Divacky bool isUTF16 = false; 324933956c43SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 3250f22ef01cSRoman Divacky GetConstantCFStringEntry(CFConstantStringMap, Literal, 325133956c43SDimitry Andric getDataLayout().isLittleEndian(), isUTF16, 325233956c43SDimitry Andric StringLength); 3253f22ef01cSRoman Divacky 325439d628a0SDimitry Andric if (auto *C = Entry.second) 32550623d748SDimitry Andric return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 3256f22ef01cSRoman Divacky 3257dff0c46cSDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 3258f22ef01cSRoman Divacky llvm::Constant *Zeros[] = { Zero, Zero }; 3259f22ef01cSRoman Divacky 3260f22ef01cSRoman Divacky // If we don't already have it, get __CFConstantStringClassReference. 3261f22ef01cSRoman Divacky if (!CFConstantStringClassRef) { 32626122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 3263f22ef01cSRoman Divacky Ty = llvm::ArrayType::get(Ty, 0); 3264e7145dcbSDimitry Andric llvm::Constant *GV = 3265e7145dcbSDimitry Andric CreateRuntimeVariable(Ty, "__CFConstantStringClassReference"); 3266e7145dcbSDimitry Andric 326744290647SDimitry Andric if (getTriple().isOSBinFormatCOFF()) { 3268e7145dcbSDimitry Andric IdentifierInfo &II = getContext().Idents.get(GV->getName()); 3269e7145dcbSDimitry Andric TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl(); 3270e7145dcbSDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 3271e7145dcbSDimitry Andric llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV); 3272e7145dcbSDimitry Andric 3273e7145dcbSDimitry Andric const VarDecl *VD = nullptr; 3274e7145dcbSDimitry Andric for (const auto &Result : DC->lookup(&II)) 3275e7145dcbSDimitry Andric if ((VD = dyn_cast<VarDecl>(Result))) 3276e7145dcbSDimitry Andric break; 3277e7145dcbSDimitry Andric 3278e7145dcbSDimitry Andric if (!VD || !VD->hasAttr<DLLExportAttr>()) { 3279e7145dcbSDimitry Andric CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3280e7145dcbSDimitry Andric CGV->setLinkage(llvm::GlobalValue::ExternalLinkage); 3281e7145dcbSDimitry Andric } else { 3282e7145dcbSDimitry Andric CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 3283e7145dcbSDimitry Andric CGV->setLinkage(llvm::GlobalValue::ExternalLinkage); 3284e7145dcbSDimitry Andric } 3285e7145dcbSDimitry Andric } 3286e7145dcbSDimitry Andric 3287f22ef01cSRoman Divacky // Decay array -> ptr 328844290647SDimitry Andric CFConstantStringClassRef = 328944290647SDimitry Andric llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros); 3290e7145dcbSDimitry Andric } 3291f22ef01cSRoman Divacky 3292f22ef01cSRoman Divacky QualType CFTy = getContext().getCFConstantStringType(); 3293f22ef01cSRoman Divacky 329459d1ed5bSDimitry Andric auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 3295f22ef01cSRoman Divacky 329644290647SDimitry Andric ConstantInitBuilder Builder(*this); 329744290647SDimitry Andric auto Fields = Builder.beginStruct(STy); 3298f22ef01cSRoman Divacky 3299f22ef01cSRoman Divacky // Class pointer. 330044290647SDimitry Andric Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef)); 3301f22ef01cSRoman Divacky 3302f22ef01cSRoman Divacky // Flags. 330344290647SDimitry Andric Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 3304f22ef01cSRoman Divacky 3305f22ef01cSRoman Divacky // String pointer. 330659d1ed5bSDimitry Andric llvm::Constant *C = nullptr; 3307dff0c46cSDimitry Andric if (isUTF16) { 33080623d748SDimitry Andric auto Arr = llvm::makeArrayRef( 330939d628a0SDimitry Andric reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 331039d628a0SDimitry Andric Entry.first().size() / 2); 3311dff0c46cSDimitry Andric C = llvm::ConstantDataArray::get(VMContext, Arr); 3312dff0c46cSDimitry Andric } else { 331339d628a0SDimitry Andric C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 3314dff0c46cSDimitry Andric } 3315f22ef01cSRoman Divacky 3316dff0c46cSDimitry Andric // Note: -fwritable-strings doesn't make the backing store strings of 3317dff0c46cSDimitry Andric // CFStrings writable. (See <rdar://problem/10657500>) 331859d1ed5bSDimitry Andric auto *GV = 3319dff0c46cSDimitry Andric new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 332059d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, C, ".str"); 3321e7145dcbSDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3322284c1978SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 3323284c1978SDimitry Andric // of the string is via this class initializer. 3324e7145dcbSDimitry Andric CharUnits Align = isUTF16 3325e7145dcbSDimitry Andric ? getContext().getTypeAlignInChars(getContext().ShortTy) 3326e7145dcbSDimitry Andric : getContext().getTypeAlignInChars(getContext().CharTy); 3327f22ef01cSRoman Divacky GV->setAlignment(Align.getQuantity()); 3328e7145dcbSDimitry Andric 3329e7145dcbSDimitry Andric // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 3330e7145dcbSDimitry Andric // Without it LLVM can merge the string with a non unnamed_addr one during 3331e7145dcbSDimitry Andric // LTO. Doing that changes the section it ends in, which surprises ld64. 333244290647SDimitry Andric if (getTriple().isOSBinFormatMachO()) 3333e7145dcbSDimitry Andric GV->setSection(isUTF16 ? "__TEXT,__ustring" 3334e7145dcbSDimitry Andric : "__TEXT,__cstring,cstring_literals"); 3335dff0c46cSDimitry Andric 3336dff0c46cSDimitry Andric // String. 333744290647SDimitry Andric llvm::Constant *Str = 333833956c43SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 3339f22ef01cSRoman Divacky 3340dff0c46cSDimitry Andric if (isUTF16) 3341dff0c46cSDimitry Andric // Cast the UTF16 string to the correct type. 334244290647SDimitry Andric Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 334344290647SDimitry Andric Fields.add(Str); 3344dff0c46cSDimitry Andric 3345f22ef01cSRoman Divacky // String length. 334644290647SDimitry Andric auto Ty = getTypes().ConvertType(getContext().LongTy); 334744290647SDimitry Andric Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength); 3348f22ef01cSRoman Divacky 33490623d748SDimitry Andric CharUnits Alignment = getPointerAlign(); 33500623d748SDimitry Andric 3351f22ef01cSRoman Divacky // The struct. 335244290647SDimitry Andric GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 335344290647SDimitry Andric /*isConstant=*/false, 335444290647SDimitry Andric llvm::GlobalVariable::PrivateLinkage); 335544290647SDimitry Andric switch (getTriple().getObjectFormat()) { 3356e7145dcbSDimitry Andric case llvm::Triple::UnknownObjectFormat: 3357e7145dcbSDimitry Andric llvm_unreachable("unknown file format"); 3358e7145dcbSDimitry Andric case llvm::Triple::COFF: 3359e7145dcbSDimitry Andric case llvm::Triple::ELF: 336020e90f04SDimitry Andric case llvm::Triple::Wasm: 3361e7145dcbSDimitry Andric GV->setSection("cfstring"); 3362e7145dcbSDimitry Andric break; 3363e7145dcbSDimitry Andric case llvm::Triple::MachO: 3364e7145dcbSDimitry Andric GV->setSection("__DATA,__cfstring"); 3365e7145dcbSDimitry Andric break; 3366e7145dcbSDimitry Andric } 336739d628a0SDimitry Andric Entry.second = GV; 3368f22ef01cSRoman Divacky 33690623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3370f22ef01cSRoman Divacky } 3371f22ef01cSRoman Divacky 33726122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() { 33736122f3e6SDimitry Andric if (ObjCFastEnumerationStateType.isNull()) { 337459d1ed5bSDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 33756122f3e6SDimitry Andric D->startDefinition(); 33766122f3e6SDimitry Andric 33776122f3e6SDimitry Andric QualType FieldTypes[] = { 33786122f3e6SDimitry Andric Context.UnsignedLongTy, 33796122f3e6SDimitry Andric Context.getPointerType(Context.getObjCIdType()), 33806122f3e6SDimitry Andric Context.getPointerType(Context.UnsignedLongTy), 33816122f3e6SDimitry Andric Context.getConstantArrayType(Context.UnsignedLongTy, 33826122f3e6SDimitry Andric llvm::APInt(32, 5), ArrayType::Normal, 0) 33836122f3e6SDimitry Andric }; 33846122f3e6SDimitry Andric 33856122f3e6SDimitry Andric for (size_t i = 0; i < 4; ++i) { 33866122f3e6SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, 33876122f3e6SDimitry Andric D, 33886122f3e6SDimitry Andric SourceLocation(), 338959d1ed5bSDimitry Andric SourceLocation(), nullptr, 339059d1ed5bSDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 339159d1ed5bSDimitry Andric /*BitWidth=*/nullptr, 33926122f3e6SDimitry Andric /*Mutable=*/false, 33937ae0e2c9SDimitry Andric ICIS_NoInit); 33946122f3e6SDimitry Andric Field->setAccess(AS_public); 33956122f3e6SDimitry Andric D->addDecl(Field); 33966122f3e6SDimitry Andric } 33976122f3e6SDimitry Andric 33986122f3e6SDimitry Andric D->completeDefinition(); 33996122f3e6SDimitry Andric ObjCFastEnumerationStateType = Context.getTagDeclType(D); 34006122f3e6SDimitry Andric } 34016122f3e6SDimitry Andric 34026122f3e6SDimitry Andric return ObjCFastEnumerationStateType; 34036122f3e6SDimitry Andric } 34046122f3e6SDimitry Andric 3405dff0c46cSDimitry Andric llvm::Constant * 3406dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 3407dff0c46cSDimitry Andric assert(!E->getType()->isPointerType() && "Strings are always arrays"); 3408f22ef01cSRoman Divacky 3409dff0c46cSDimitry Andric // Don't emit it as the address of the string, emit the string data itself 3410dff0c46cSDimitry Andric // as an inline array. 3411dff0c46cSDimitry Andric if (E->getCharByteWidth() == 1) { 3412dff0c46cSDimitry Andric SmallString<64> Str(E->getString()); 3413f22ef01cSRoman Divacky 3414dff0c46cSDimitry Andric // Resize the string to the right size, which is indicated by its type. 3415dff0c46cSDimitry Andric const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 3416dff0c46cSDimitry Andric Str.resize(CAT->getSize().getZExtValue()); 3417dff0c46cSDimitry Andric return llvm::ConstantDataArray::getString(VMContext, Str, false); 34186122f3e6SDimitry Andric } 3419f22ef01cSRoman Divacky 342059d1ed5bSDimitry Andric auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 3421dff0c46cSDimitry Andric llvm::Type *ElemTy = AType->getElementType(); 3422dff0c46cSDimitry Andric unsigned NumElements = AType->getNumElements(); 3423f22ef01cSRoman Divacky 3424dff0c46cSDimitry Andric // Wide strings have either 2-byte or 4-byte elements. 3425dff0c46cSDimitry Andric if (ElemTy->getPrimitiveSizeInBits() == 16) { 3426dff0c46cSDimitry Andric SmallVector<uint16_t, 32> Elements; 3427dff0c46cSDimitry Andric Elements.reserve(NumElements); 3428dff0c46cSDimitry Andric 3429dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3430dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 3431dff0c46cSDimitry Andric Elements.resize(NumElements); 3432dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 3433dff0c46cSDimitry Andric } 3434dff0c46cSDimitry Andric 3435dff0c46cSDimitry Andric assert(ElemTy->getPrimitiveSizeInBits() == 32); 3436dff0c46cSDimitry Andric SmallVector<uint32_t, 32> Elements; 3437dff0c46cSDimitry Andric Elements.reserve(NumElements); 3438dff0c46cSDimitry Andric 3439dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3440dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 3441dff0c46cSDimitry Andric Elements.resize(NumElements); 3442dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 3443f22ef01cSRoman Divacky } 3444f22ef01cSRoman Divacky 344559d1ed5bSDimitry Andric static llvm::GlobalVariable * 344659d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 344759d1ed5bSDimitry Andric CodeGenModule &CGM, StringRef GlobalName, 34480623d748SDimitry Andric CharUnits Alignment) { 344959d1ed5bSDimitry Andric // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 345059d1ed5bSDimitry Andric unsigned AddrSpace = 0; 345159d1ed5bSDimitry Andric if (CGM.getLangOpts().OpenCL) 345259d1ed5bSDimitry Andric AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 3453dff0c46cSDimitry Andric 345433956c43SDimitry Andric llvm::Module &M = CGM.getModule(); 345559d1ed5bSDimitry Andric // Create a global variable for this string 345659d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 345733956c43SDimitry Andric M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 345833956c43SDimitry Andric nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 34590623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 3460e7145dcbSDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 346133956c43SDimitry Andric if (GV->isWeakForLinker()) { 346233956c43SDimitry Andric assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 346333956c43SDimitry Andric GV->setComdat(M.getOrInsertComdat(GV->getName())); 346433956c43SDimitry Andric } 346533956c43SDimitry Andric 346659d1ed5bSDimitry Andric return GV; 3467f22ef01cSRoman Divacky } 3468dff0c46cSDimitry Andric 346959d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 347059d1ed5bSDimitry Andric /// constant array for the given string literal. 34710623d748SDimitry Andric ConstantAddress 347239d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 347339d628a0SDimitry Andric StringRef Name) { 34740623d748SDimitry Andric CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 3475dff0c46cSDimitry Andric 347659d1ed5bSDimitry Andric llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 347759d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 347859d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 347959d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 348059d1ed5bSDimitry Andric if (auto GV = *Entry) { 34810623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 34820623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 34830623d748SDimitry Andric return ConstantAddress(GV, Alignment); 348459d1ed5bSDimitry Andric } 348559d1ed5bSDimitry Andric } 348659d1ed5bSDimitry Andric 348759d1ed5bSDimitry Andric SmallString<256> MangledNameBuffer; 348859d1ed5bSDimitry Andric StringRef GlobalVariableName; 348959d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes LT; 349059d1ed5bSDimitry Andric 349159d1ed5bSDimitry Andric // Mangle the string literal if the ABI allows for it. However, we cannot 349259d1ed5bSDimitry Andric // do this if we are compiling with ASan or -fwritable-strings because they 349359d1ed5bSDimitry Andric // rely on strings having normal linkage. 349439d628a0SDimitry Andric if (!LangOpts.WritableStrings && 349539d628a0SDimitry Andric !LangOpts.Sanitize.has(SanitizerKind::Address) && 349659d1ed5bSDimitry Andric getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { 349759d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(MangledNameBuffer); 349859d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 349959d1ed5bSDimitry Andric 350059d1ed5bSDimitry Andric LT = llvm::GlobalValue::LinkOnceODRLinkage; 350159d1ed5bSDimitry Andric GlobalVariableName = MangledNameBuffer; 350259d1ed5bSDimitry Andric } else { 350359d1ed5bSDimitry Andric LT = llvm::GlobalValue::PrivateLinkage; 350439d628a0SDimitry Andric GlobalVariableName = Name; 350559d1ed5bSDimitry Andric } 350659d1ed5bSDimitry Andric 350759d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 350859d1ed5bSDimitry Andric if (Entry) 350959d1ed5bSDimitry Andric *Entry = GV; 351059d1ed5bSDimitry Andric 351139d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 351239d628a0SDimitry Andric QualType()); 35130623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3514f22ef01cSRoman Divacky } 3515f22ef01cSRoman Divacky 3516f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 3517f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node. 35180623d748SDimitry Andric ConstantAddress 3519f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 3520f22ef01cSRoman Divacky std::string Str; 3521f22ef01cSRoman Divacky getContext().getObjCEncodingForType(E->getEncodedType(), Str); 3522f22ef01cSRoman Divacky 3523f22ef01cSRoman Divacky return GetAddrOfConstantCString(Str); 3524f22ef01cSRoman Divacky } 3525f22ef01cSRoman Divacky 352659d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing 352759d1ed5bSDimitry Andric /// the literal and a terminating '\0' character. 352859d1ed5bSDimitry Andric /// The result has pointer to array type. 35290623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString( 35300623d748SDimitry Andric const std::string &Str, const char *GlobalName) { 353159d1ed5bSDimitry Andric StringRef StrWithNull(Str.c_str(), Str.size() + 1); 35320623d748SDimitry Andric CharUnits Alignment = 35330623d748SDimitry Andric getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 3534f22ef01cSRoman Divacky 353559d1ed5bSDimitry Andric llvm::Constant *C = 353659d1ed5bSDimitry Andric llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 353759d1ed5bSDimitry Andric 353859d1ed5bSDimitry Andric // Don't share any string literals if strings aren't constant. 353959d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 354059d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 354159d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 354259d1ed5bSDimitry Andric if (auto GV = *Entry) { 35430623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 35440623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 35450623d748SDimitry Andric return ConstantAddress(GV, Alignment); 354659d1ed5bSDimitry Andric } 354759d1ed5bSDimitry Andric } 354859d1ed5bSDimitry Andric 3549f22ef01cSRoman Divacky // Get the default prefix if a name wasn't specified. 3550f22ef01cSRoman Divacky if (!GlobalName) 3551f22ef01cSRoman Divacky GlobalName = ".str"; 3552f22ef01cSRoman Divacky // Create a global variable for this. 355359d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 355459d1ed5bSDimitry Andric GlobalName, Alignment); 355559d1ed5bSDimitry Andric if (Entry) 355659d1ed5bSDimitry Andric *Entry = GV; 35570623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3558f22ef01cSRoman Divacky } 3559f22ef01cSRoman Divacky 35600623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 3561f785676fSDimitry Andric const MaterializeTemporaryExpr *E, const Expr *Init) { 3562f785676fSDimitry Andric assert((E->getStorageDuration() == SD_Static || 3563f785676fSDimitry Andric E->getStorageDuration() == SD_Thread) && "not a global temporary"); 356459d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 3565f785676fSDimitry Andric 3566f785676fSDimitry Andric // If we're not materializing a subobject of the temporary, keep the 3567f785676fSDimitry Andric // cv-qualifiers from the type of the MaterializeTemporaryExpr. 3568f785676fSDimitry Andric QualType MaterializedType = Init->getType(); 3569f785676fSDimitry Andric if (Init == E->GetTemporaryExpr()) 3570f785676fSDimitry Andric MaterializedType = E->getType(); 3571f785676fSDimitry Andric 35720623d748SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 35730623d748SDimitry Andric 35740623d748SDimitry Andric if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E]) 35750623d748SDimitry Andric return ConstantAddress(Slot, Align); 3576f785676fSDimitry Andric 3577f785676fSDimitry Andric // FIXME: If an externally-visible declaration extends multiple temporaries, 3578f785676fSDimitry Andric // we need to give each temporary the same name in every translation unit (and 3579f785676fSDimitry Andric // we also need to make the temporaries externally-visible). 3580f785676fSDimitry Andric SmallString<256> Name; 3581f785676fSDimitry Andric llvm::raw_svector_ostream Out(Name); 358259d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleReferenceTemporary( 358359d1ed5bSDimitry Andric VD, E->getManglingNumber(), Out); 3584f785676fSDimitry Andric 358559d1ed5bSDimitry Andric APValue *Value = nullptr; 3586f785676fSDimitry Andric if (E->getStorageDuration() == SD_Static) { 3587f785676fSDimitry Andric // We might have a cached constant initializer for this temporary. Note 3588f785676fSDimitry Andric // that this might have a different value from the value computed by 3589f785676fSDimitry Andric // evaluating the initializer if the surrounding constant expression 3590f785676fSDimitry Andric // modifies the temporary. 3591f785676fSDimitry Andric Value = getContext().getMaterializedTemporaryValue(E, false); 3592f785676fSDimitry Andric if (Value && Value->isUninit()) 359359d1ed5bSDimitry Andric Value = nullptr; 3594f785676fSDimitry Andric } 3595f785676fSDimitry Andric 3596f785676fSDimitry Andric // Try evaluating it now, it might have a constant initializer. 3597f785676fSDimitry Andric Expr::EvalResult EvalResult; 3598f785676fSDimitry Andric if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 3599f785676fSDimitry Andric !EvalResult.hasSideEffects()) 3600f785676fSDimitry Andric Value = &EvalResult.Val; 3601f785676fSDimitry Andric 360259d1ed5bSDimitry Andric llvm::Constant *InitialValue = nullptr; 3603f785676fSDimitry Andric bool Constant = false; 3604f785676fSDimitry Andric llvm::Type *Type; 3605f785676fSDimitry Andric if (Value) { 3606f785676fSDimitry Andric // The temporary has a constant initializer, use it. 360759d1ed5bSDimitry Andric InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr); 3608f785676fSDimitry Andric Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 3609f785676fSDimitry Andric Type = InitialValue->getType(); 3610f785676fSDimitry Andric } else { 3611f785676fSDimitry Andric // No initializer, the initialization will be provided when we 3612f785676fSDimitry Andric // initialize the declaration which performed lifetime extension. 3613f785676fSDimitry Andric Type = getTypes().ConvertTypeForMem(MaterializedType); 3614f785676fSDimitry Andric } 3615f785676fSDimitry Andric 3616f785676fSDimitry Andric // Create a global variable for this lifetime-extended temporary. 361759d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 361859d1ed5bSDimitry Andric getLLVMLinkageVarDefinition(VD, Constant); 361933956c43SDimitry Andric if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 362033956c43SDimitry Andric const VarDecl *InitVD; 362133956c43SDimitry Andric if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 362233956c43SDimitry Andric isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 362333956c43SDimitry Andric // Temporaries defined inside a class get linkonce_odr linkage because the 362433956c43SDimitry Andric // class can be defined in multipe translation units. 362533956c43SDimitry Andric Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 362633956c43SDimitry Andric } else { 362733956c43SDimitry Andric // There is no need for this temporary to have external linkage if the 362833956c43SDimitry Andric // VarDecl has external linkage. 362933956c43SDimitry Andric Linkage = llvm::GlobalVariable::InternalLinkage; 363033956c43SDimitry Andric } 363133956c43SDimitry Andric } 363259d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace( 363359d1ed5bSDimitry Andric VD, getContext().getTargetAddressSpace(MaterializedType)); 363459d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 363559d1ed5bSDimitry Andric getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 363659d1ed5bSDimitry Andric /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, 363759d1ed5bSDimitry Andric AddrSpace); 363859d1ed5bSDimitry Andric setGlobalVisibility(GV, VD); 36390623d748SDimitry Andric GV->setAlignment(Align.getQuantity()); 364033956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker()) 364133956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3642f785676fSDimitry Andric if (VD->getTLSKind()) 3643f785676fSDimitry Andric setTLSMode(GV, *VD); 36440623d748SDimitry Andric MaterializedGlobalTemporaryMap[E] = GV; 36450623d748SDimitry Andric return ConstantAddress(GV, Align); 3646f785676fSDimitry Andric } 3647f785676fSDimitry Andric 3648f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized 3649f22ef01cSRoman Divacky /// properties for an implementation. 3650f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const 3651f22ef01cSRoman Divacky ObjCImplementationDecl *D) { 365259d1ed5bSDimitry Andric for (const auto *PID : D->property_impls()) { 3653f22ef01cSRoman Divacky // Dynamic is just for type-checking. 3654f22ef01cSRoman Divacky if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 3655f22ef01cSRoman Divacky ObjCPropertyDecl *PD = PID->getPropertyDecl(); 3656f22ef01cSRoman Divacky 3657f22ef01cSRoman Divacky // Determine which methods need to be implemented, some may have 36583861d79fSDimitry Andric // been overridden. Note that ::isPropertyAccessor is not the method 3659f22ef01cSRoman Divacky // we want, that just indicates if the decl came from a 3660f22ef01cSRoman Divacky // property. What we want to know is if the method is defined in 3661f22ef01cSRoman Divacky // this implementation. 3662f22ef01cSRoman Divacky if (!D->getInstanceMethod(PD->getGetterName())) 3663f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCGetter( 3664f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3665f22ef01cSRoman Divacky if (!PD->isReadOnly() && 3666f22ef01cSRoman Divacky !D->getInstanceMethod(PD->getSetterName())) 3667f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCSetter( 3668f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3669f22ef01cSRoman Divacky } 3670f22ef01cSRoman Divacky } 3671f22ef01cSRoman Divacky } 3672f22ef01cSRoman Divacky 36733b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) { 36746122f3e6SDimitry Andric const ObjCInterfaceDecl *iface = impl->getClassInterface(); 36756122f3e6SDimitry Andric for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 36763b0f4066SDimitry Andric ivar; ivar = ivar->getNextIvar()) 36773b0f4066SDimitry Andric if (ivar->getType().isDestructedType()) 36783b0f4066SDimitry Andric return true; 36793b0f4066SDimitry Andric 36803b0f4066SDimitry Andric return false; 36813b0f4066SDimitry Andric } 36823b0f4066SDimitry Andric 368339d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM, 368439d628a0SDimitry Andric ObjCImplementationDecl *D) { 368539d628a0SDimitry Andric CodeGenFunction CGF(CGM); 368639d628a0SDimitry Andric for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 368739d628a0SDimitry Andric E = D->init_end(); B != E; ++B) { 368839d628a0SDimitry Andric CXXCtorInitializer *CtorInitExp = *B; 368939d628a0SDimitry Andric Expr *Init = CtorInitExp->getInit(); 369039d628a0SDimitry Andric if (!CGF.isTrivialInitializer(Init)) 369139d628a0SDimitry Andric return false; 369239d628a0SDimitry Andric } 369339d628a0SDimitry Andric return true; 369439d628a0SDimitry Andric } 369539d628a0SDimitry Andric 3696f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization 3697f22ef01cSRoman Divacky /// for an implementation. 3698f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 36993b0f4066SDimitry Andric // We might need a .cxx_destruct even if we don't have any ivar initializers. 37003b0f4066SDimitry Andric if (needsDestructMethod(D)) { 3701f22ef01cSRoman Divacky IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 3702f22ef01cSRoman Divacky Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 37033b0f4066SDimitry Andric ObjCMethodDecl *DTORMethod = 37043b0f4066SDimitry Andric ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 370559d1ed5bSDimitry Andric cxxSelector, getContext().VoidTy, nullptr, D, 37066122f3e6SDimitry Andric /*isInstance=*/true, /*isVariadic=*/false, 37073861d79fSDimitry Andric /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 37086122f3e6SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 3709f22ef01cSRoman Divacky D->addInstanceMethod(DTORMethod); 3710f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 37113861d79fSDimitry Andric D->setHasDestructors(true); 37123b0f4066SDimitry Andric } 3713f22ef01cSRoman Divacky 37143b0f4066SDimitry Andric // If the implementation doesn't have any ivar initializers, we don't need 37153b0f4066SDimitry Andric // a .cxx_construct. 371639d628a0SDimitry Andric if (D->getNumIvarInitializers() == 0 || 371739d628a0SDimitry Andric AllTrivialInitializers(*this, D)) 37183b0f4066SDimitry Andric return; 37193b0f4066SDimitry Andric 37203b0f4066SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 37213b0f4066SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 3722f22ef01cSRoman Divacky // The constructor returns 'self'. 3723f22ef01cSRoman Divacky ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 3724f22ef01cSRoman Divacky D->getLocation(), 37256122f3e6SDimitry Andric D->getLocation(), 37266122f3e6SDimitry Andric cxxSelector, 372759d1ed5bSDimitry Andric getContext().getObjCIdType(), 372859d1ed5bSDimitry Andric nullptr, D, /*isInstance=*/true, 37296122f3e6SDimitry Andric /*isVariadic=*/false, 37303861d79fSDimitry Andric /*isPropertyAccessor=*/true, 37316122f3e6SDimitry Andric /*isImplicitlyDeclared=*/true, 37326122f3e6SDimitry Andric /*isDefined=*/false, 3733f22ef01cSRoman Divacky ObjCMethodDecl::Required); 3734f22ef01cSRoman Divacky D->addInstanceMethod(CTORMethod); 3735f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 37363861d79fSDimitry Andric D->setHasNonZeroConstructors(true); 3737f22ef01cSRoman Divacky } 3738f22ef01cSRoman Divacky 3739f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec. 3740f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 3741f22ef01cSRoman Divacky if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 3742f22ef01cSRoman Divacky LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 3743f22ef01cSRoman Divacky ErrorUnsupported(LSD, "linkage spec"); 3744f22ef01cSRoman Divacky return; 3745f22ef01cSRoman Divacky } 3746f22ef01cSRoman Divacky 374744290647SDimitry Andric EmitDeclContext(LSD); 374844290647SDimitry Andric } 374944290647SDimitry Andric 375044290647SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 375144290647SDimitry Andric for (auto *I : DC->decls()) { 375244290647SDimitry Andric // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 375344290647SDimitry Andric // are themselves considered "top-level", so EmitTopLevelDecl on an 375444290647SDimitry Andric // ObjCImplDecl does not recursively visit them. We need to do that in 375544290647SDimitry Andric // case they're nested inside another construct (LinkageSpecDecl / 375644290647SDimitry Andric // ExportDecl) that does stop them from being considered "top-level". 375759d1ed5bSDimitry Andric if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 375859d1ed5bSDimitry Andric for (auto *M : OID->methods()) 375959d1ed5bSDimitry Andric EmitTopLevelDecl(M); 37603861d79fSDimitry Andric } 376144290647SDimitry Andric 376259d1ed5bSDimitry Andric EmitTopLevelDecl(I); 3763f22ef01cSRoman Divacky } 37643861d79fSDimitry Andric } 3765f22ef01cSRoman Divacky 3766f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration. 3767f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) { 3768f22ef01cSRoman Divacky // Ignore dependent declarations. 3769f22ef01cSRoman Divacky if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 3770f22ef01cSRoman Divacky return; 3771f22ef01cSRoman Divacky 3772f22ef01cSRoman Divacky switch (D->getKind()) { 3773f22ef01cSRoman Divacky case Decl::CXXConversion: 3774f22ef01cSRoman Divacky case Decl::CXXMethod: 3775f22ef01cSRoman Divacky case Decl::Function: 3776f22ef01cSRoman Divacky // Skip function templates 37773b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 37783b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3779f22ef01cSRoman Divacky return; 3780f22ef01cSRoman Divacky 3781f22ef01cSRoman Divacky EmitGlobal(cast<FunctionDecl>(D)); 378239d628a0SDimitry Andric // Always provide some coverage mapping 378339d628a0SDimitry Andric // even for the functions that aren't emitted. 378439d628a0SDimitry Andric AddDeferredUnusedCoverageMapping(D); 3785f22ef01cSRoman Divacky break; 3786f22ef01cSRoman Divacky 37876bc11b14SDimitry Andric case Decl::CXXDeductionGuide: 37886bc11b14SDimitry Andric // Function-like, but does not result in code emission. 37896bc11b14SDimitry Andric break; 37906bc11b14SDimitry Andric 3791f22ef01cSRoman Divacky case Decl::Var: 379244290647SDimitry Andric case Decl::Decomposition: 3793f785676fSDimitry Andric // Skip variable templates 3794f785676fSDimitry Andric if (cast<VarDecl>(D)->getDescribedVarTemplate()) 3795f785676fSDimitry Andric return; 3796f785676fSDimitry Andric case Decl::VarTemplateSpecialization: 3797f22ef01cSRoman Divacky EmitGlobal(cast<VarDecl>(D)); 379844290647SDimitry Andric if (auto *DD = dyn_cast<DecompositionDecl>(D)) 379944290647SDimitry Andric for (auto *B : DD->bindings()) 380044290647SDimitry Andric if (auto *HD = B->getHoldingVar()) 380144290647SDimitry Andric EmitGlobal(HD); 3802f22ef01cSRoman Divacky break; 3803f22ef01cSRoman Divacky 38043b0f4066SDimitry Andric // Indirect fields from global anonymous structs and unions can be 38053b0f4066SDimitry Andric // ignored; only the actual variable requires IR gen support. 38063b0f4066SDimitry Andric case Decl::IndirectField: 38073b0f4066SDimitry Andric break; 38083b0f4066SDimitry Andric 3809f22ef01cSRoman Divacky // C++ Decls 3810f22ef01cSRoman Divacky case Decl::Namespace: 381144290647SDimitry Andric EmitDeclContext(cast<NamespaceDecl>(D)); 3812f22ef01cSRoman Divacky break; 3813e7145dcbSDimitry Andric case Decl::CXXRecord: 381420e90f04SDimitry Andric if (DebugInfo) { 381520e90f04SDimitry Andric if (auto *ES = D->getASTContext().getExternalSource()) 381620e90f04SDimitry Andric if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 381720e90f04SDimitry Andric DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D)); 381820e90f04SDimitry Andric } 3819e7145dcbSDimitry Andric // Emit any static data members, they may be definitions. 3820e7145dcbSDimitry Andric for (auto *I : cast<CXXRecordDecl>(D)->decls()) 3821e7145dcbSDimitry Andric if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 3822e7145dcbSDimitry Andric EmitTopLevelDecl(I); 3823e7145dcbSDimitry Andric break; 3824f22ef01cSRoman Divacky // No code generation needed. 3825f22ef01cSRoman Divacky case Decl::UsingShadow: 3826f22ef01cSRoman Divacky case Decl::ClassTemplate: 3827f785676fSDimitry Andric case Decl::VarTemplate: 3828f785676fSDimitry Andric case Decl::VarTemplatePartialSpecialization: 3829f22ef01cSRoman Divacky case Decl::FunctionTemplate: 3830bd5abe19SDimitry Andric case Decl::TypeAliasTemplate: 3831bd5abe19SDimitry Andric case Decl::Block: 3832139f7f9bSDimitry Andric case Decl::Empty: 3833f22ef01cSRoman Divacky break; 383459d1ed5bSDimitry Andric case Decl::Using: // using X; [C++] 383559d1ed5bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 383659d1ed5bSDimitry Andric DI->EmitUsingDecl(cast<UsingDecl>(*D)); 383759d1ed5bSDimitry Andric return; 3838f785676fSDimitry Andric case Decl::NamespaceAlias: 3839f785676fSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3840f785676fSDimitry Andric DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 3841f785676fSDimitry Andric return; 3842284c1978SDimitry Andric case Decl::UsingDirective: // using namespace X; [C++] 3843284c1978SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3844284c1978SDimitry Andric DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 3845284c1978SDimitry Andric return; 3846f22ef01cSRoman Divacky case Decl::CXXConstructor: 3847f22ef01cSRoman Divacky // Skip function templates 38483b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 38493b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3850f22ef01cSRoman Divacky return; 3851f22ef01cSRoman Divacky 3852f785676fSDimitry Andric getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 3853f22ef01cSRoman Divacky break; 3854f22ef01cSRoman Divacky case Decl::CXXDestructor: 38553b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 38563b0f4066SDimitry Andric return; 3857f785676fSDimitry Andric getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 3858f22ef01cSRoman Divacky break; 3859f22ef01cSRoman Divacky 3860f22ef01cSRoman Divacky case Decl::StaticAssert: 3861f22ef01cSRoman Divacky // Nothing to do. 3862f22ef01cSRoman Divacky break; 3863f22ef01cSRoman Divacky 3864f22ef01cSRoman Divacky // Objective-C Decls 3865f22ef01cSRoman Divacky 3866f22ef01cSRoman Divacky // Forward declarations, no (immediate) code generation. 3867f22ef01cSRoman Divacky case Decl::ObjCInterface: 38687ae0e2c9SDimitry Andric case Decl::ObjCCategory: 3869f22ef01cSRoman Divacky break; 3870f22ef01cSRoman Divacky 3871dff0c46cSDimitry Andric case Decl::ObjCProtocol: { 387259d1ed5bSDimitry Andric auto *Proto = cast<ObjCProtocolDecl>(D); 3873dff0c46cSDimitry Andric if (Proto->isThisDeclarationADefinition()) 3874dff0c46cSDimitry Andric ObjCRuntime->GenerateProtocol(Proto); 3875f22ef01cSRoman Divacky break; 3876dff0c46cSDimitry Andric } 3877f22ef01cSRoman Divacky 3878f22ef01cSRoman Divacky case Decl::ObjCCategoryImpl: 3879f22ef01cSRoman Divacky // Categories have properties but don't support synthesize so we 3880f22ef01cSRoman Divacky // can ignore them here. 38816122f3e6SDimitry Andric ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 3882f22ef01cSRoman Divacky break; 3883f22ef01cSRoman Divacky 3884f22ef01cSRoman Divacky case Decl::ObjCImplementation: { 388559d1ed5bSDimitry Andric auto *OMD = cast<ObjCImplementationDecl>(D); 3886f22ef01cSRoman Divacky EmitObjCPropertyImplementations(OMD); 3887f22ef01cSRoman Divacky EmitObjCIvarInitializations(OMD); 38886122f3e6SDimitry Andric ObjCRuntime->GenerateClass(OMD); 3889dff0c46cSDimitry Andric // Emit global variable debug information. 3890dff0c46cSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3891e7145dcbSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 3892139f7f9bSDimitry Andric DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 3893139f7f9bSDimitry Andric OMD->getClassInterface()), OMD->getLocation()); 3894f22ef01cSRoman Divacky break; 3895f22ef01cSRoman Divacky } 3896f22ef01cSRoman Divacky case Decl::ObjCMethod: { 389759d1ed5bSDimitry Andric auto *OMD = cast<ObjCMethodDecl>(D); 3898f22ef01cSRoman Divacky // If this is not a prototype, emit the body. 3899f22ef01cSRoman Divacky if (OMD->getBody()) 3900f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCMethod(OMD); 3901f22ef01cSRoman Divacky break; 3902f22ef01cSRoman Divacky } 3903f22ef01cSRoman Divacky case Decl::ObjCCompatibleAlias: 3904dff0c46cSDimitry Andric ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 3905f22ef01cSRoman Divacky break; 3906f22ef01cSRoman Divacky 3907e7145dcbSDimitry Andric case Decl::PragmaComment: { 3908e7145dcbSDimitry Andric const auto *PCD = cast<PragmaCommentDecl>(D); 3909e7145dcbSDimitry Andric switch (PCD->getCommentKind()) { 3910e7145dcbSDimitry Andric case PCK_Unknown: 3911e7145dcbSDimitry Andric llvm_unreachable("unexpected pragma comment kind"); 3912e7145dcbSDimitry Andric case PCK_Linker: 3913e7145dcbSDimitry Andric AppendLinkerOptions(PCD->getArg()); 3914e7145dcbSDimitry Andric break; 3915e7145dcbSDimitry Andric case PCK_Lib: 3916e7145dcbSDimitry Andric AddDependentLib(PCD->getArg()); 3917e7145dcbSDimitry Andric break; 3918e7145dcbSDimitry Andric case PCK_Compiler: 3919e7145dcbSDimitry Andric case PCK_ExeStr: 3920e7145dcbSDimitry Andric case PCK_User: 3921e7145dcbSDimitry Andric break; // We ignore all of these. 3922e7145dcbSDimitry Andric } 3923e7145dcbSDimitry Andric break; 3924e7145dcbSDimitry Andric } 3925e7145dcbSDimitry Andric 3926e7145dcbSDimitry Andric case Decl::PragmaDetectMismatch: { 3927e7145dcbSDimitry Andric const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 3928e7145dcbSDimitry Andric AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 3929e7145dcbSDimitry Andric break; 3930e7145dcbSDimitry Andric } 3931e7145dcbSDimitry Andric 3932f22ef01cSRoman Divacky case Decl::LinkageSpec: 3933f22ef01cSRoman Divacky EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 3934f22ef01cSRoman Divacky break; 3935f22ef01cSRoman Divacky 3936f22ef01cSRoman Divacky case Decl::FileScopeAsm: { 393733956c43SDimitry Andric // File-scope asm is ignored during device-side CUDA compilation. 393833956c43SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 393933956c43SDimitry Andric break; 3940ea942507SDimitry Andric // File-scope asm is ignored during device-side OpenMP compilation. 3941ea942507SDimitry Andric if (LangOpts.OpenMPIsDevice) 3942ea942507SDimitry Andric break; 394359d1ed5bSDimitry Andric auto *AD = cast<FileScopeAsmDecl>(D); 394433956c43SDimitry Andric getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 3945f22ef01cSRoman Divacky break; 3946f22ef01cSRoman Divacky } 3947f22ef01cSRoman Divacky 3948139f7f9bSDimitry Andric case Decl::Import: { 394959d1ed5bSDimitry Andric auto *Import = cast<ImportDecl>(D); 3950139f7f9bSDimitry Andric 395144290647SDimitry Andric // If we've already imported this module, we're done. 395244290647SDimitry Andric if (!ImportedModules.insert(Import->getImportedModule())) 3953139f7f9bSDimitry Andric break; 395444290647SDimitry Andric 395544290647SDimitry Andric // Emit debug information for direct imports. 395644290647SDimitry Andric if (!Import->getImportedOwningModule()) { 39573dac3a9bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 39583dac3a9bSDimitry Andric DI->EmitImportDecl(*Import); 395944290647SDimitry Andric } 3960139f7f9bSDimitry Andric 396144290647SDimitry Andric // Find all of the submodules and emit the module initializers. 396244290647SDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 396344290647SDimitry Andric SmallVector<clang::Module *, 16> Stack; 396444290647SDimitry Andric Visited.insert(Import->getImportedModule()); 396544290647SDimitry Andric Stack.push_back(Import->getImportedModule()); 396644290647SDimitry Andric 396744290647SDimitry Andric while (!Stack.empty()) { 396844290647SDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 396944290647SDimitry Andric if (!EmittedModuleInitializers.insert(Mod).second) 397044290647SDimitry Andric continue; 397144290647SDimitry Andric 397244290647SDimitry Andric for (auto *D : Context.getModuleInitializers(Mod)) 397344290647SDimitry Andric EmitTopLevelDecl(D); 397444290647SDimitry Andric 397544290647SDimitry Andric // Visit the submodules of this module. 397644290647SDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 397744290647SDimitry Andric SubEnd = Mod->submodule_end(); 397844290647SDimitry Andric Sub != SubEnd; ++Sub) { 397944290647SDimitry Andric // Skip explicit children; they need to be explicitly imported to emit 398044290647SDimitry Andric // the initializers. 398144290647SDimitry Andric if ((*Sub)->IsExplicit) 398244290647SDimitry Andric continue; 398344290647SDimitry Andric 398444290647SDimitry Andric if (Visited.insert(*Sub).second) 398544290647SDimitry Andric Stack.push_back(*Sub); 398644290647SDimitry Andric } 398744290647SDimitry Andric } 3988139f7f9bSDimitry Andric break; 3989139f7f9bSDimitry Andric } 3990139f7f9bSDimitry Andric 399144290647SDimitry Andric case Decl::Export: 399244290647SDimitry Andric EmitDeclContext(cast<ExportDecl>(D)); 399344290647SDimitry Andric break; 399444290647SDimitry Andric 399539d628a0SDimitry Andric case Decl::OMPThreadPrivate: 399639d628a0SDimitry Andric EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 399739d628a0SDimitry Andric break; 399839d628a0SDimitry Andric 399959d1ed5bSDimitry Andric case Decl::ClassTemplateSpecialization: { 400059d1ed5bSDimitry Andric const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 400159d1ed5bSDimitry Andric if (DebugInfo && 400239d628a0SDimitry Andric Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition && 400339d628a0SDimitry Andric Spec->hasDefinition()) 400459d1ed5bSDimitry Andric DebugInfo->completeTemplateDefinition(*Spec); 400539d628a0SDimitry Andric break; 400659d1ed5bSDimitry Andric } 400759d1ed5bSDimitry Andric 4008e7145dcbSDimitry Andric case Decl::OMPDeclareReduction: 4009e7145dcbSDimitry Andric EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 4010e7145dcbSDimitry Andric break; 4011e7145dcbSDimitry Andric 4012f22ef01cSRoman Divacky default: 4013f22ef01cSRoman Divacky // Make sure we handled everything we should, every other kind is a 4014f22ef01cSRoman Divacky // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 4015f22ef01cSRoman Divacky // function. Need to recode Decl::Kind to do that easily. 4016f22ef01cSRoman Divacky assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 401739d628a0SDimitry Andric break; 401839d628a0SDimitry Andric } 401939d628a0SDimitry Andric } 402039d628a0SDimitry Andric 402139d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 402239d628a0SDimitry Andric // Do we need to generate coverage mapping? 402339d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 402439d628a0SDimitry Andric return; 402539d628a0SDimitry Andric switch (D->getKind()) { 402639d628a0SDimitry Andric case Decl::CXXConversion: 402739d628a0SDimitry Andric case Decl::CXXMethod: 402839d628a0SDimitry Andric case Decl::Function: 402939d628a0SDimitry Andric case Decl::ObjCMethod: 403039d628a0SDimitry Andric case Decl::CXXConstructor: 403139d628a0SDimitry Andric case Decl::CXXDestructor: { 40320623d748SDimitry Andric if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 403339d628a0SDimitry Andric return; 403439d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 403539d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 403639d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = true; 403739d628a0SDimitry Andric break; 403839d628a0SDimitry Andric } 403939d628a0SDimitry Andric default: 404039d628a0SDimitry Andric break; 404139d628a0SDimitry Andric }; 404239d628a0SDimitry Andric } 404339d628a0SDimitry Andric 404439d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 404539d628a0SDimitry Andric // Do we need to generate coverage mapping? 404639d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 404739d628a0SDimitry Andric return; 404839d628a0SDimitry Andric if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 404939d628a0SDimitry Andric if (Fn->isTemplateInstantiation()) 405039d628a0SDimitry Andric ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 405139d628a0SDimitry Andric } 405239d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 405339d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 405439d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = false; 405539d628a0SDimitry Andric else 405639d628a0SDimitry Andric I->second = false; 405739d628a0SDimitry Andric } 405839d628a0SDimitry Andric 405939d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 406039d628a0SDimitry Andric std::vector<const Decl *> DeferredDecls; 406133956c43SDimitry Andric for (const auto &I : DeferredEmptyCoverageMappingDecls) { 406239d628a0SDimitry Andric if (!I.second) 406339d628a0SDimitry Andric continue; 406439d628a0SDimitry Andric DeferredDecls.push_back(I.first); 406539d628a0SDimitry Andric } 406639d628a0SDimitry Andric // Sort the declarations by their location to make sure that the tests get a 406739d628a0SDimitry Andric // predictable order for the coverage mapping for the unused declarations. 406839d628a0SDimitry Andric if (CodeGenOpts.DumpCoverageMapping) 406939d628a0SDimitry Andric std::sort(DeferredDecls.begin(), DeferredDecls.end(), 407039d628a0SDimitry Andric [] (const Decl *LHS, const Decl *RHS) { 407139d628a0SDimitry Andric return LHS->getLocStart() < RHS->getLocStart(); 407239d628a0SDimitry Andric }); 407339d628a0SDimitry Andric for (const auto *D : DeferredDecls) { 407439d628a0SDimitry Andric switch (D->getKind()) { 407539d628a0SDimitry Andric case Decl::CXXConversion: 407639d628a0SDimitry Andric case Decl::CXXMethod: 407739d628a0SDimitry Andric case Decl::Function: 407839d628a0SDimitry Andric case Decl::ObjCMethod: { 407939d628a0SDimitry Andric CodeGenPGO PGO(*this); 408039d628a0SDimitry Andric GlobalDecl GD(cast<FunctionDecl>(D)); 408139d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 408239d628a0SDimitry Andric getFunctionLinkage(GD)); 408339d628a0SDimitry Andric break; 408439d628a0SDimitry Andric } 408539d628a0SDimitry Andric case Decl::CXXConstructor: { 408639d628a0SDimitry Andric CodeGenPGO PGO(*this); 408739d628a0SDimitry Andric GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 408839d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 408939d628a0SDimitry Andric getFunctionLinkage(GD)); 409039d628a0SDimitry Andric break; 409139d628a0SDimitry Andric } 409239d628a0SDimitry Andric case Decl::CXXDestructor: { 409339d628a0SDimitry Andric CodeGenPGO PGO(*this); 409439d628a0SDimitry Andric GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 409539d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 409639d628a0SDimitry Andric getFunctionLinkage(GD)); 409739d628a0SDimitry Andric break; 409839d628a0SDimitry Andric } 409939d628a0SDimitry Andric default: 410039d628a0SDimitry Andric break; 410139d628a0SDimitry Andric }; 4102f22ef01cSRoman Divacky } 4103f22ef01cSRoman Divacky } 4104ffd1746dSEd Schouten 4105ffd1746dSEd Schouten /// Turns the given pointer into a constant. 4106ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 4107ffd1746dSEd Schouten const void *Ptr) { 4108ffd1746dSEd Schouten uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 41096122f3e6SDimitry Andric llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 4110ffd1746dSEd Schouten return llvm::ConstantInt::get(i64, PtrInt); 4111ffd1746dSEd Schouten } 4112ffd1746dSEd Schouten 4113ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 4114ffd1746dSEd Schouten llvm::NamedMDNode *&GlobalMetadata, 4115ffd1746dSEd Schouten GlobalDecl D, 4116ffd1746dSEd Schouten llvm::GlobalValue *Addr) { 4117ffd1746dSEd Schouten if (!GlobalMetadata) 4118ffd1746dSEd Schouten GlobalMetadata = 4119ffd1746dSEd Schouten CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 4120ffd1746dSEd Schouten 4121ffd1746dSEd Schouten // TODO: should we report variant information for ctors/dtors? 412239d628a0SDimitry Andric llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 412339d628a0SDimitry Andric llvm::ConstantAsMetadata::get(GetPointerConstant( 412439d628a0SDimitry Andric CGM.getLLVMContext(), D.getDecl()))}; 41253b0f4066SDimitry Andric GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 4126ffd1746dSEd Schouten } 4127ffd1746dSEd Schouten 4128284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked 4129284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled 4130284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer 4131284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the 4132284c1978SDimitry Andric /// same translation unit. 4133284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() { 4134e7145dcbSDimitry Andric // Don't do anything if we're generating CUDA device code -- the NVPTX 4135e7145dcbSDimitry Andric // assembly target doesn't support aliases. 4136e7145dcbSDimitry Andric if (Context.getTargetInfo().getTriple().isNVPTX()) 4137e7145dcbSDimitry Andric return; 41388f0fd8f6SDimitry Andric for (auto &I : StaticExternCValues) { 41398f0fd8f6SDimitry Andric IdentifierInfo *Name = I.first; 41408f0fd8f6SDimitry Andric llvm::GlobalValue *Val = I.second; 4141284c1978SDimitry Andric if (Val && !getModule().getNamedValue(Name->getName())) 414259d1ed5bSDimitry Andric addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 4143284c1978SDimitry Andric } 4144284c1978SDimitry Andric } 4145284c1978SDimitry Andric 414659d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 414759d1ed5bSDimitry Andric GlobalDecl &Result) const { 414859d1ed5bSDimitry Andric auto Res = Manglings.find(MangledName); 414959d1ed5bSDimitry Andric if (Res == Manglings.end()) 415059d1ed5bSDimitry Andric return false; 415159d1ed5bSDimitry Andric Result = Res->getValue(); 415259d1ed5bSDimitry Andric return true; 415359d1ed5bSDimitry Andric } 415459d1ed5bSDimitry Andric 4155ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the 4156ffd1746dSEd Schouten /// current module with the Decls they came from. This is useful for 4157ffd1746dSEd Schouten /// projects using IR gen as a subroutine. 4158ffd1746dSEd Schouten /// 4159ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly 4160ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata 4161ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'. 4162ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() { 416359d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 4164ffd1746dSEd Schouten 416559d1ed5bSDimitry Andric for (auto &I : MangledDeclNames) { 416659d1ed5bSDimitry Andric llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 41670623d748SDimitry Andric // Some mangled names don't necessarily have an associated GlobalValue 41680623d748SDimitry Andric // in this module, e.g. if we mangled it for DebugInfo. 41690623d748SDimitry Andric if (Addr) 417059d1ed5bSDimitry Andric EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 4171ffd1746dSEd Schouten } 4172ffd1746dSEd Schouten } 4173ffd1746dSEd Schouten 4174ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current 4175ffd1746dSEd Schouten /// function. 4176ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() { 4177ffd1746dSEd Schouten if (LocalDeclMap.empty()) return; 4178ffd1746dSEd Schouten 4179ffd1746dSEd Schouten llvm::LLVMContext &Context = getLLVMContext(); 4180ffd1746dSEd Schouten 4181ffd1746dSEd Schouten // Find the unique metadata ID for this name. 4182ffd1746dSEd Schouten unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 4183ffd1746dSEd Schouten 418459d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 4185ffd1746dSEd Schouten 418659d1ed5bSDimitry Andric for (auto &I : LocalDeclMap) { 418759d1ed5bSDimitry Andric const Decl *D = I.first; 41880623d748SDimitry Andric llvm::Value *Addr = I.second.getPointer(); 418959d1ed5bSDimitry Andric if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 4190ffd1746dSEd Schouten llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 419139d628a0SDimitry Andric Alloca->setMetadata( 419239d628a0SDimitry Andric DeclPtrKind, llvm::MDNode::get( 419339d628a0SDimitry Andric Context, llvm::ValueAsMetadata::getConstant(DAddr))); 419459d1ed5bSDimitry Andric } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 4195ffd1746dSEd Schouten GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 4196ffd1746dSEd Schouten EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 4197ffd1746dSEd Schouten } 4198ffd1746dSEd Schouten } 4199ffd1746dSEd Schouten } 4200e580952dSDimitry Andric 4201f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() { 4202f785676fSDimitry Andric llvm::NamedMDNode *IdentMetadata = 4203f785676fSDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.ident"); 4204f785676fSDimitry Andric std::string Version = getClangFullVersion(); 4205f785676fSDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 4206f785676fSDimitry Andric 420739d628a0SDimitry Andric llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 4208f785676fSDimitry Andric IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 4209f785676fSDimitry Andric } 4210f785676fSDimitry Andric 421159d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() { 421239d628a0SDimitry Andric // Warning, new MangledDeclNames may be appended within this loop. 421339d628a0SDimitry Andric // We rely on MapVector insertions adding new elements to the end 421439d628a0SDimitry Andric // of the container. 421539d628a0SDimitry Andric // FIXME: Move this loop into the one target that needs it, and only 421639d628a0SDimitry Andric // loop over those declarations for which we couldn't emit the target 421739d628a0SDimitry Andric // metadata when we emitted the declaration. 421839d628a0SDimitry Andric for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 421939d628a0SDimitry Andric auto Val = *(MangledDeclNames.begin() + I); 422039d628a0SDimitry Andric const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 422139d628a0SDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(Val.second); 422259d1ed5bSDimitry Andric getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 422359d1ed5bSDimitry Andric } 422459d1ed5bSDimitry Andric } 422559d1ed5bSDimitry Andric 4226bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() { 422744290647SDimitry Andric if (getCodeGenOpts().CoverageDataFile.empty() && 422844290647SDimitry Andric getCodeGenOpts().CoverageNotesFile.empty()) 422944290647SDimitry Andric return; 423044290647SDimitry Andric 423144290647SDimitry Andric llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 423244290647SDimitry Andric if (!CUNode) 423344290647SDimitry Andric return; 423444290647SDimitry Andric 4235bd5abe19SDimitry Andric llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 4236bd5abe19SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 423744290647SDimitry Andric auto *CoverageDataFile = 423844290647SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 423944290647SDimitry Andric auto *CoverageNotesFile = 424044290647SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 4241bd5abe19SDimitry Andric for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 4242bd5abe19SDimitry Andric llvm::MDNode *CU = CUNode->getOperand(i); 424344290647SDimitry Andric llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 424439d628a0SDimitry Andric GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 4245bd5abe19SDimitry Andric } 4246bd5abe19SDimitry Andric } 42473861d79fSDimitry Andric 424839d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { 42493861d79fSDimitry Andric // Sema has checked that all uuid strings are of the form 42503861d79fSDimitry Andric // "12345678-1234-1234-1234-1234567890ab". 42513861d79fSDimitry Andric assert(Uuid.size() == 36); 4252f785676fSDimitry Andric for (unsigned i = 0; i < 36; ++i) { 4253f785676fSDimitry Andric if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 4254f785676fSDimitry Andric else assert(isHexDigit(Uuid[i])); 42553861d79fSDimitry Andric } 42563861d79fSDimitry Andric 425739d628a0SDimitry Andric // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". 4258f785676fSDimitry Andric const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 42593861d79fSDimitry Andric 4260f785676fSDimitry Andric llvm::Constant *Field3[8]; 4261f785676fSDimitry Andric for (unsigned Idx = 0; Idx < 8; ++Idx) 4262f785676fSDimitry Andric Field3[Idx] = llvm::ConstantInt::get( 4263f785676fSDimitry Andric Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 42643861d79fSDimitry Andric 4265f785676fSDimitry Andric llvm::Constant *Fields[4] = { 4266f785676fSDimitry Andric llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 4267f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 4268f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 4269f785676fSDimitry Andric llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 4270f785676fSDimitry Andric }; 4271f785676fSDimitry Andric 4272f785676fSDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 42733861d79fSDimitry Andric } 427459d1ed5bSDimitry Andric 427559d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 427659d1ed5bSDimitry Andric bool ForEH) { 427759d1ed5bSDimitry Andric // Return a bogus pointer if RTTI is disabled, unless it's for EH. 427859d1ed5bSDimitry Andric // FIXME: should we even be calling this method if RTTI is disabled 427959d1ed5bSDimitry Andric // and it's not for EH? 428059d1ed5bSDimitry Andric if (!ForEH && !getLangOpts().RTTI) 428159d1ed5bSDimitry Andric return llvm::Constant::getNullValue(Int8PtrTy); 428259d1ed5bSDimitry Andric 428359d1ed5bSDimitry Andric if (ForEH && Ty->isObjCObjectPointerType() && 428459d1ed5bSDimitry Andric LangOpts.ObjCRuntime.isGNUFamily()) 428559d1ed5bSDimitry Andric return ObjCRuntime->GetEHType(Ty); 428659d1ed5bSDimitry Andric 428759d1ed5bSDimitry Andric return getCXXABI().getAddrOfRTTIDescriptor(Ty); 428859d1ed5bSDimitry Andric } 428959d1ed5bSDimitry Andric 429039d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 429139d628a0SDimitry Andric for (auto RefExpr : D->varlists()) { 429239d628a0SDimitry Andric auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 429339d628a0SDimitry Andric bool PerformInit = 429439d628a0SDimitry Andric VD->getAnyInitializer() && 429539d628a0SDimitry Andric !VD->getAnyInitializer()->isConstantInitializer(getContext(), 429639d628a0SDimitry Andric /*ForRef=*/false); 42970623d748SDimitry Andric 42980623d748SDimitry Andric Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 429933956c43SDimitry Andric if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 43000623d748SDimitry Andric VD, Addr, RefExpr->getLocStart(), PerformInit)) 430139d628a0SDimitry Andric CXXGlobalInits.push_back(InitFunction); 430239d628a0SDimitry Andric } 430339d628a0SDimitry Andric } 43048f0fd8f6SDimitry Andric 43050623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 43060623d748SDimitry Andric llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()]; 43070623d748SDimitry Andric if (InternalId) 43080623d748SDimitry Andric return InternalId; 43090623d748SDimitry Andric 43100623d748SDimitry Andric if (isExternallyVisible(T->getLinkage())) { 43118f0fd8f6SDimitry Andric std::string OutName; 43128f0fd8f6SDimitry Andric llvm::raw_string_ostream Out(OutName); 43130623d748SDimitry Andric getCXXABI().getMangleContext().mangleTypeName(T, Out); 43148f0fd8f6SDimitry Andric 43150623d748SDimitry Andric InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 43160623d748SDimitry Andric } else { 43170623d748SDimitry Andric InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 43180623d748SDimitry Andric llvm::ArrayRef<llvm::Metadata *>()); 43190623d748SDimitry Andric } 43200623d748SDimitry Andric 43210623d748SDimitry Andric return InternalId; 43220623d748SDimitry Andric } 43230623d748SDimitry Andric 4324e7145dcbSDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier. 4325e7145dcbSDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const { 4326e7145dcbSDimitry Andric // Returns true if at least one of vtable-based CFI checkers is enabled and 4327e7145dcbSDimitry Andric // is not in the trapping mode. 4328e7145dcbSDimitry Andric return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 4329e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 4330e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 4331e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 4332e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 4333e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 4334e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 4335e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 4336e7145dcbSDimitry Andric } 4337e7145dcbSDimitry Andric 4338e7145dcbSDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 43390623d748SDimitry Andric CharUnits Offset, 43400623d748SDimitry Andric const CXXRecordDecl *RD) { 43410623d748SDimitry Andric llvm::Metadata *MD = 43420623d748SDimitry Andric CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 4343e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 43440623d748SDimitry Andric 4345e7145dcbSDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 4346e7145dcbSDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 4347e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), 4348e7145dcbSDimitry Andric llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 4349e7145dcbSDimitry Andric 4350e7145dcbSDimitry Andric if (NeedAllVtablesTypeId()) { 4351e7145dcbSDimitry Andric llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 4352e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 43530623d748SDimitry Andric } 43540623d748SDimitry Andric } 43550623d748SDimitry Andric 43560623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the 43570623d748SDimitry Andric // passed in function. 43580623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 43590623d748SDimitry Andric const FunctionDecl *FD) { 43600623d748SDimitry Andric StringRef TargetCPU = Target.getTargetOpts().CPU; 43610623d748SDimitry Andric if (const auto *TD = FD->getAttr<TargetAttr>()) { 43620623d748SDimitry Andric // If we have a TargetAttr build up the feature map based on that. 43630623d748SDimitry Andric TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); 43640623d748SDimitry Andric 43650623d748SDimitry Andric // Make a copy of the features as passed on the command line into the 43660623d748SDimitry Andric // beginning of the additional features from the function to override. 43670623d748SDimitry Andric ParsedAttr.first.insert(ParsedAttr.first.begin(), 43680623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.begin(), 43690623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.end()); 43700623d748SDimitry Andric 43710623d748SDimitry Andric if (ParsedAttr.second != "") 43720623d748SDimitry Andric TargetCPU = ParsedAttr.second; 43730623d748SDimitry Andric 43740623d748SDimitry Andric // Now populate the feature map, first with the TargetCPU which is either 43750623d748SDimitry Andric // the default or a new one from the target attribute string. Then we'll use 43760623d748SDimitry Andric // the passed in features (FeaturesAsWritten) along with the new ones from 43770623d748SDimitry Andric // the attribute. 43780623d748SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first); 43790623d748SDimitry Andric } else { 43800623d748SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 43810623d748SDimitry Andric Target.getTargetOpts().Features); 43820623d748SDimitry Andric } 43838f0fd8f6SDimitry Andric } 4384e7145dcbSDimitry Andric 4385e7145dcbSDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 4386e7145dcbSDimitry Andric if (!SanStats) 4387e7145dcbSDimitry Andric SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule()); 4388e7145dcbSDimitry Andric 4389e7145dcbSDimitry Andric return *SanStats; 4390e7145dcbSDimitry Andric } 439144290647SDimitry Andric llvm::Value * 439244290647SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 439344290647SDimitry Andric CodeGenFunction &CGF) { 439444290647SDimitry Andric llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF); 439544290647SDimitry Andric auto SamplerT = getOpenCLRuntime().getSamplerType(); 439644290647SDimitry Andric auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 439744290647SDimitry Andric return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy, 439844290647SDimitry Andric "__translate_sampler_initializer"), 439944290647SDimitry Andric {C}); 440044290647SDimitry Andric } 4401