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" 48d8866befSDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h" 4959d1ed5bSDimitry Andric #include "llvm/IR/CallSite.h" 50139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h" 51139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h" 52139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h" 53139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h" 54139f7f9bSDimitry Andric #include "llvm/IR/Module.h" 5559d1ed5bSDimitry Andric #include "llvm/ProfileData/InstrProfReader.h" 56139f7f9bSDimitry Andric #include "llvm/Support/ConvertUTF.h" 57f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h" 580623d748SDimitry Andric #include "llvm/Support/MD5.h" 59139f7f9bSDimitry Andric 60f22ef01cSRoman Divacky using namespace clang; 61f22ef01cSRoman Divacky using namespace CodeGen; 62f22ef01cSRoman Divacky 636122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata"; 646122f3e6SDimitry Andric 6559d1ed5bSDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 66284c1978SDimitry Andric switch (CGM.getTarget().getCXXABI().getKind()) { 67139f7f9bSDimitry Andric case TargetCXXABI::GenericAArch64: 68139f7f9bSDimitry Andric case TargetCXXABI::GenericARM: 69139f7f9bSDimitry Andric case TargetCXXABI::iOS: 7059d1ed5bSDimitry Andric case TargetCXXABI::iOS64: 710623d748SDimitry Andric case TargetCXXABI::WatchOS: 72ef6fa9e2SDimitry Andric case TargetCXXABI::GenericMIPS: 73139f7f9bSDimitry Andric case TargetCXXABI::GenericItanium: 740623d748SDimitry Andric case TargetCXXABI::WebAssembly: 7559d1ed5bSDimitry Andric return CreateItaniumCXXABI(CGM); 76139f7f9bSDimitry Andric case TargetCXXABI::Microsoft: 7759d1ed5bSDimitry Andric return CreateMicrosoftCXXABI(CGM); 78e580952dSDimitry Andric } 79e580952dSDimitry Andric 80e580952dSDimitry Andric llvm_unreachable("invalid C++ ABI kind"); 81e580952dSDimitry Andric } 82e580952dSDimitry Andric 833dac3a9bSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO, 843dac3a9bSDimitry Andric const PreprocessorOptions &PPO, 853dac3a9bSDimitry Andric const CodeGenOptions &CGO, llvm::Module &M, 8639d628a0SDimitry Andric DiagnosticsEngine &diags, 8739d628a0SDimitry Andric CoverageSourceInfo *CoverageInfo) 883dac3a9bSDimitry Andric : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO), 893dac3a9bSDimitry Andric PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), 900623d748SDimitry Andric Target(C.getTargetInfo()), ABI(createCXXABI(*this)), 91e7145dcbSDimitry Andric VMContext(M.getContext()), Types(*this), VTables(*this), 92e7145dcbSDimitry Andric SanitizerMD(new SanitizerMetadata(*this)) { 93dff0c46cSDimitry Andric 94dff0c46cSDimitry Andric // Initialize the type cache. 95dff0c46cSDimitry Andric llvm::LLVMContext &LLVMContext = M.getContext(); 96dff0c46cSDimitry Andric VoidTy = llvm::Type::getVoidTy(LLVMContext); 97dff0c46cSDimitry Andric Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 98dff0c46cSDimitry Andric Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 99dff0c46cSDimitry Andric Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 100dff0c46cSDimitry Andric Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 101dff0c46cSDimitry Andric FloatTy = llvm::Type::getFloatTy(LLVMContext); 102dff0c46cSDimitry Andric DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 103dff0c46cSDimitry Andric PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 104dff0c46cSDimitry Andric PointerAlignInBytes = 105dff0c46cSDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 10644290647SDimitry Andric SizeSizeInBytes = 10744290647SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); 1080623d748SDimitry Andric IntAlignInBytes = 1090623d748SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 110dff0c46cSDimitry Andric IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 11144290647SDimitry Andric IntPtrTy = llvm::IntegerType::get(LLVMContext, 11244290647SDimitry Andric C.getTargetInfo().getMaxPointerWidth()); 113dff0c46cSDimitry Andric Int8PtrTy = Int8Ty->getPointerTo(0); 114dff0c46cSDimitry Andric Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 1156bc11b14SDimitry Andric AllocaInt8PtrTy = Int8Ty->getPointerTo( 1166bc11b14SDimitry Andric M.getDataLayout().getAllocaAddrSpace()); 117d8866befSDimitry Andric ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); 118dff0c46cSDimitry Andric 119139f7f9bSDimitry Andric RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 12039d628a0SDimitry Andric BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC(); 121139f7f9bSDimitry Andric 122dff0c46cSDimitry Andric if (LangOpts.ObjC1) 1233b0f4066SDimitry Andric createObjCRuntime(); 124dff0c46cSDimitry Andric if (LangOpts.OpenCL) 1256122f3e6SDimitry Andric createOpenCLRuntime(); 12659d1ed5bSDimitry Andric if (LangOpts.OpenMP) 12759d1ed5bSDimitry Andric createOpenMPRuntime(); 128dff0c46cSDimitry Andric if (LangOpts.CUDA) 1296122f3e6SDimitry Andric createCUDARuntime(); 130f22ef01cSRoman Divacky 1317ae0e2c9SDimitry Andric // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 13239d628a0SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 1337ae0e2c9SDimitry Andric (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 134e7145dcbSDimitry Andric TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(), 135e7145dcbSDimitry Andric getCXXABI().getMangleContext())); 1362754fe60SDimitry Andric 1373b0f4066SDimitry Andric // If debug info or coverage generation is enabled, create the CGDebugInfo 1383b0f4066SDimitry Andric // object. 139e7145dcbSDimitry Andric if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo || 140e7145dcbSDimitry Andric CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) 141e7145dcbSDimitry Andric DebugInfo.reset(new CGDebugInfo(*this)); 1422754fe60SDimitry Andric 1432754fe60SDimitry Andric Block.GlobalUniqueCount = 0; 1442754fe60SDimitry Andric 1450623d748SDimitry Andric if (C.getLangOpts().ObjC1) 146e7145dcbSDimitry Andric ObjCData.reset(new ObjCEntrypoints()); 14759d1ed5bSDimitry Andric 148e7145dcbSDimitry Andric if (CodeGenOpts.hasProfileClangUse()) { 149e7145dcbSDimitry Andric auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 150e7145dcbSDimitry Andric CodeGenOpts.ProfileInstrumentUsePath); 151e7145dcbSDimitry Andric if (auto E = ReaderOrErr.takeError()) { 15259d1ed5bSDimitry Andric unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 1533dac3a9bSDimitry Andric "Could not read profile %0: %1"); 154e7145dcbSDimitry Andric llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { 155e7145dcbSDimitry Andric getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath 156e7145dcbSDimitry Andric << EI.message(); 157e7145dcbSDimitry Andric }); 15833956c43SDimitry Andric } else 15933956c43SDimitry Andric PGOReader = std::move(ReaderOrErr.get()); 16059d1ed5bSDimitry Andric } 16139d628a0SDimitry Andric 16239d628a0SDimitry Andric // If coverage mapping generation is enabled, create the 16339d628a0SDimitry Andric // CoverageMappingModuleGen object. 16439d628a0SDimitry Andric if (CodeGenOpts.CoverageMapping) 16539d628a0SDimitry Andric CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 166f22ef01cSRoman Divacky } 167f22ef01cSRoman Divacky 168e7145dcbSDimitry Andric CodeGenModule::~CodeGenModule() {} 169f22ef01cSRoman Divacky 170f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() { 1717ae0e2c9SDimitry Andric // This is just isGNUFamily(), but we want to force implementors of 1727ae0e2c9SDimitry Andric // new ABIs to decide how best to do this. 1737ae0e2c9SDimitry Andric switch (LangOpts.ObjCRuntime.getKind()) { 1747ae0e2c9SDimitry Andric case ObjCRuntime::GNUstep: 1757ae0e2c9SDimitry Andric case ObjCRuntime::GCC: 1767ae0e2c9SDimitry Andric case ObjCRuntime::ObjFW: 177e7145dcbSDimitry Andric ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 1787ae0e2c9SDimitry Andric return; 1797ae0e2c9SDimitry Andric 1807ae0e2c9SDimitry Andric case ObjCRuntime::FragileMacOSX: 1817ae0e2c9SDimitry Andric case ObjCRuntime::MacOSX: 1827ae0e2c9SDimitry Andric case ObjCRuntime::iOS: 1830623d748SDimitry Andric case ObjCRuntime::WatchOS: 184e7145dcbSDimitry Andric ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 1857ae0e2c9SDimitry Andric return; 1867ae0e2c9SDimitry Andric } 1877ae0e2c9SDimitry Andric llvm_unreachable("bad runtime kind"); 1886122f3e6SDimitry Andric } 1896122f3e6SDimitry Andric 1906122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() { 191e7145dcbSDimitry Andric OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 1926122f3e6SDimitry Andric } 1936122f3e6SDimitry Andric 19459d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() { 195e7145dcbSDimitry Andric // Select a specialized code generation class based on the target, if any. 196e7145dcbSDimitry Andric // If it does not exist use the default implementation. 19744290647SDimitry Andric switch (getTriple().getArch()) { 198e7145dcbSDimitry Andric case llvm::Triple::nvptx: 199e7145dcbSDimitry Andric case llvm::Triple::nvptx64: 200e7145dcbSDimitry Andric assert(getLangOpts().OpenMPIsDevice && 201e7145dcbSDimitry Andric "OpenMP NVPTX is only prepared to deal with device code."); 202e7145dcbSDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this)); 203e7145dcbSDimitry Andric break; 204e7145dcbSDimitry Andric default: 205e7145dcbSDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 206e7145dcbSDimitry Andric break; 207e7145dcbSDimitry Andric } 20859d1ed5bSDimitry Andric } 20959d1ed5bSDimitry Andric 2106122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() { 211e7145dcbSDimitry Andric CUDARuntime.reset(CreateNVCUDARuntime(*this)); 212f22ef01cSRoman Divacky } 213f22ef01cSRoman Divacky 21439d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 21539d628a0SDimitry Andric Replacements[Name] = C; 21639d628a0SDimitry Andric } 21739d628a0SDimitry Andric 218f785676fSDimitry Andric void CodeGenModule::applyReplacements() { 2198f0fd8f6SDimitry Andric for (auto &I : Replacements) { 2208f0fd8f6SDimitry Andric StringRef MangledName = I.first(); 2218f0fd8f6SDimitry Andric llvm::Constant *Replacement = I.second; 222f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 223f785676fSDimitry Andric if (!Entry) 224f785676fSDimitry Andric continue; 22559d1ed5bSDimitry Andric auto *OldF = cast<llvm::Function>(Entry); 22659d1ed5bSDimitry Andric auto *NewF = dyn_cast<llvm::Function>(Replacement); 227f785676fSDimitry Andric if (!NewF) { 22859d1ed5bSDimitry Andric if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 22959d1ed5bSDimitry Andric NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 23059d1ed5bSDimitry Andric } else { 23159d1ed5bSDimitry Andric auto *CE = cast<llvm::ConstantExpr>(Replacement); 232f785676fSDimitry Andric assert(CE->getOpcode() == llvm::Instruction::BitCast || 233f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::GetElementPtr); 234f785676fSDimitry Andric NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 235f785676fSDimitry Andric } 23659d1ed5bSDimitry Andric } 237f785676fSDimitry Andric 238f785676fSDimitry Andric // Replace old with new, but keep the old order. 239f785676fSDimitry Andric OldF->replaceAllUsesWith(Replacement); 240f785676fSDimitry Andric if (NewF) { 241f785676fSDimitry Andric NewF->removeFromParent(); 2420623d748SDimitry Andric OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 2430623d748SDimitry Andric NewF); 244f785676fSDimitry Andric } 245f785676fSDimitry Andric OldF->eraseFromParent(); 246f785676fSDimitry Andric } 247f785676fSDimitry Andric } 248f785676fSDimitry Andric 2490623d748SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 2500623d748SDimitry Andric GlobalValReplacements.push_back(std::make_pair(GV, C)); 2510623d748SDimitry Andric } 2520623d748SDimitry Andric 2530623d748SDimitry Andric void CodeGenModule::applyGlobalValReplacements() { 2540623d748SDimitry Andric for (auto &I : GlobalValReplacements) { 2550623d748SDimitry Andric llvm::GlobalValue *GV = I.first; 2560623d748SDimitry Andric llvm::Constant *C = I.second; 2570623d748SDimitry Andric 2580623d748SDimitry Andric GV->replaceAllUsesWith(C); 2590623d748SDimitry Andric GV->eraseFromParent(); 2600623d748SDimitry Andric } 2610623d748SDimitry Andric } 2620623d748SDimitry Andric 26359d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a 26459d1ed5bSDimitry Andric // linear structure. 265e7145dcbSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal( 266e7145dcbSDimitry Andric const llvm::GlobalIndirectSymbol &GIS) { 267e7145dcbSDimitry Andric llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited; 268e7145dcbSDimitry Andric const llvm::Constant *C = &GIS; 26959d1ed5bSDimitry Andric for (;;) { 27059d1ed5bSDimitry Andric C = C->stripPointerCasts(); 27159d1ed5bSDimitry Andric if (auto *GO = dyn_cast<llvm::GlobalObject>(C)) 27259d1ed5bSDimitry Andric return GO; 27359d1ed5bSDimitry Andric // stripPointerCasts will not walk over weak aliases. 274e7145dcbSDimitry Andric auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C); 275e7145dcbSDimitry Andric if (!GIS2) 27659d1ed5bSDimitry Andric return nullptr; 277e7145dcbSDimitry Andric if (!Visited.insert(GIS2).second) 27859d1ed5bSDimitry Andric return nullptr; 279e7145dcbSDimitry Andric C = GIS2->getIndirectSymbol(); 28059d1ed5bSDimitry Andric } 28159d1ed5bSDimitry Andric } 28259d1ed5bSDimitry Andric 283f785676fSDimitry Andric void CodeGenModule::checkAliases() { 28459d1ed5bSDimitry Andric // Check if the constructed aliases are well formed. It is really unfortunate 28559d1ed5bSDimitry Andric // that we have to do this in CodeGen, but we only construct mangled names 28659d1ed5bSDimitry Andric // and aliases during codegen. 287f785676fSDimitry Andric bool Error = false; 28859d1ed5bSDimitry Andric DiagnosticsEngine &Diags = getDiags(); 2898f0fd8f6SDimitry Andric for (const GlobalDecl &GD : Aliases) { 29059d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 291e7145dcbSDimitry Andric SourceLocation Location; 292e7145dcbSDimitry Andric bool IsIFunc = D->hasAttr<IFuncAttr>(); 293e7145dcbSDimitry Andric if (const Attr *A = D->getDefiningAttr()) 294e7145dcbSDimitry Andric Location = A->getLocation(); 295e7145dcbSDimitry Andric else 296e7145dcbSDimitry Andric llvm_unreachable("Not an alias or ifunc?"); 297f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 298f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 299e7145dcbSDimitry Andric auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry); 30059d1ed5bSDimitry Andric const llvm::GlobalValue *GV = getAliasedGlobal(*Alias); 30159d1ed5bSDimitry Andric if (!GV) { 302f785676fSDimitry Andric Error = true; 303e7145dcbSDimitry Andric Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 30459d1ed5bSDimitry Andric } else if (GV->isDeclaration()) { 305f785676fSDimitry Andric Error = true; 306e7145dcbSDimitry Andric Diags.Report(Location, diag::err_alias_to_undefined) 307e7145dcbSDimitry Andric << IsIFunc << IsIFunc; 308e7145dcbSDimitry Andric } else if (IsIFunc) { 309e7145dcbSDimitry Andric // Check resolver function type. 310e7145dcbSDimitry Andric llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>( 311e7145dcbSDimitry Andric GV->getType()->getPointerElementType()); 312e7145dcbSDimitry Andric assert(FTy); 313e7145dcbSDimitry Andric if (!FTy->getReturnType()->isPointerTy()) 314e7145dcbSDimitry Andric Diags.Report(Location, diag::err_ifunc_resolver_return); 315e7145dcbSDimitry Andric if (FTy->getNumParams()) 316e7145dcbSDimitry Andric Diags.Report(Location, diag::err_ifunc_resolver_params); 31759d1ed5bSDimitry Andric } 31859d1ed5bSDimitry Andric 319e7145dcbSDimitry Andric llvm::Constant *Aliasee = Alias->getIndirectSymbol(); 32059d1ed5bSDimitry Andric llvm::GlobalValue *AliaseeGV; 32159d1ed5bSDimitry Andric if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 32259d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 32359d1ed5bSDimitry Andric else 32459d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 32559d1ed5bSDimitry Andric 32659d1ed5bSDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 32759d1ed5bSDimitry Andric StringRef AliasSection = SA->getName(); 32859d1ed5bSDimitry Andric if (AliasSection != AliaseeGV->getSection()) 32959d1ed5bSDimitry Andric Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 330e7145dcbSDimitry Andric << AliasSection << IsIFunc << IsIFunc; 33159d1ed5bSDimitry Andric } 33259d1ed5bSDimitry Andric 33359d1ed5bSDimitry Andric // We have to handle alias to weak aliases in here. LLVM itself disallows 33459d1ed5bSDimitry Andric // this since the object semantics would not match the IL one. For 33559d1ed5bSDimitry Andric // compatibility with gcc we implement it by just pointing the alias 33659d1ed5bSDimitry Andric // to its aliasee's aliasee. We also warn, since the user is probably 33759d1ed5bSDimitry Andric // expecting the link to be weak. 338e7145dcbSDimitry Andric if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) { 339e7145dcbSDimitry Andric if (GA->isInterposable()) { 340e7145dcbSDimitry Andric Diags.Report(Location, diag::warn_alias_to_weak_alias) 341e7145dcbSDimitry Andric << GV->getName() << GA->getName() << IsIFunc; 34259d1ed5bSDimitry Andric Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 343e7145dcbSDimitry Andric GA->getIndirectSymbol(), Alias->getType()); 344e7145dcbSDimitry Andric Alias->setIndirectSymbol(Aliasee); 34559d1ed5bSDimitry Andric } 346f785676fSDimitry Andric } 347f785676fSDimitry Andric } 348f785676fSDimitry Andric if (!Error) 349f785676fSDimitry Andric return; 350f785676fSDimitry Andric 3518f0fd8f6SDimitry Andric for (const GlobalDecl &GD : Aliases) { 352f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 353f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 354e7145dcbSDimitry Andric auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry); 355f785676fSDimitry Andric Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 356f785676fSDimitry Andric Alias->eraseFromParent(); 357f785676fSDimitry Andric } 358f785676fSDimitry Andric } 359f785676fSDimitry Andric 36059d1ed5bSDimitry Andric void CodeGenModule::clear() { 36159d1ed5bSDimitry Andric DeferredDeclsToEmit.clear(); 36233956c43SDimitry Andric if (OpenMPRuntime) 36333956c43SDimitry Andric OpenMPRuntime->clear(); 36459d1ed5bSDimitry Andric } 36559d1ed5bSDimitry Andric 36659d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 36759d1ed5bSDimitry Andric StringRef MainFile) { 36859d1ed5bSDimitry Andric if (!hasDiagnostics()) 36959d1ed5bSDimitry Andric return; 37059d1ed5bSDimitry Andric if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 37159d1ed5bSDimitry Andric if (MainFile.empty()) 37259d1ed5bSDimitry Andric MainFile = "<stdin>"; 37359d1ed5bSDimitry Andric Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 374f37b6182SDimitry Andric } else { 375f37b6182SDimitry Andric if (Mismatched > 0) 376f37b6182SDimitry Andric Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; 377f37b6182SDimitry Andric 378f37b6182SDimitry Andric if (Missing > 0) 379f37b6182SDimitry Andric Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; 380f37b6182SDimitry Andric } 38159d1ed5bSDimitry Andric } 38259d1ed5bSDimitry Andric 383f22ef01cSRoman Divacky void CodeGenModule::Release() { 384f22ef01cSRoman Divacky EmitDeferred(); 3850623d748SDimitry Andric applyGlobalValReplacements(); 386f785676fSDimitry Andric applyReplacements(); 387f785676fSDimitry Andric checkAliases(); 388f22ef01cSRoman Divacky EmitCXXGlobalInitFunc(); 389f22ef01cSRoman Divacky EmitCXXGlobalDtorFunc(); 390284c1978SDimitry Andric EmitCXXThreadLocalInitFunc(); 3916122f3e6SDimitry Andric if (ObjCRuntime) 3926122f3e6SDimitry Andric if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 393f22ef01cSRoman Divacky AddGlobalCtor(ObjCInitFunction); 39433956c43SDimitry Andric if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice && 39533956c43SDimitry Andric CUDARuntime) { 39633956c43SDimitry Andric if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction()) 39733956c43SDimitry Andric AddGlobalCtor(CudaCtorFunction); 39833956c43SDimitry Andric if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction()) 39933956c43SDimitry Andric AddGlobalDtor(CudaDtorFunction); 40033956c43SDimitry Andric } 401ea942507SDimitry Andric if (OpenMPRuntime) 402ea942507SDimitry Andric if (llvm::Function *OpenMPRegistrationFunction = 403ea942507SDimitry Andric OpenMPRuntime->emitRegistrationFunction()) 404ea942507SDimitry Andric AddGlobalCtor(OpenMPRegistrationFunction, 0); 4050623d748SDimitry Andric if (PGOReader) { 406e7145dcbSDimitry Andric getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext)); 4070623d748SDimitry Andric if (PGOStats.hasDiagnostics()) 40859d1ed5bSDimitry Andric PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 4090623d748SDimitry Andric } 410f22ef01cSRoman Divacky EmitCtorList(GlobalCtors, "llvm.global_ctors"); 411f22ef01cSRoman Divacky EmitCtorList(GlobalDtors, "llvm.global_dtors"); 4126122f3e6SDimitry Andric EmitGlobalAnnotations(); 413284c1978SDimitry Andric EmitStaticExternCAliases(); 41439d628a0SDimitry Andric EmitDeferredUnusedCoverageMappings(); 41539d628a0SDimitry Andric if (CoverageMapping) 41639d628a0SDimitry Andric CoverageMapping->emit(); 41720e90f04SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 418e7145dcbSDimitry Andric CodeGenFunction(*this).EmitCfiCheckFail(); 41920e90f04SDimitry Andric CodeGenFunction(*this).EmitCfiCheckStub(); 42020e90f04SDimitry Andric } 42120e90f04SDimitry Andric emitAtAvailableLinkGuard(); 42259d1ed5bSDimitry Andric emitLLVMUsed(); 423e7145dcbSDimitry Andric if (SanStats) 424e7145dcbSDimitry Andric SanStats->finish(); 425ffd1746dSEd Schouten 426f785676fSDimitry Andric if (CodeGenOpts.Autolink && 427f785676fSDimitry Andric (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 428139f7f9bSDimitry Andric EmitModuleLinkOptions(); 429139f7f9bSDimitry Andric } 43020e90f04SDimitry Andric 43120e90f04SDimitry Andric // Record mregparm value now so it is visible through rest of codegen. 43220e90f04SDimitry Andric if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 43320e90f04SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", 43420e90f04SDimitry Andric CodeGenOpts.NumRegisterParameters); 43520e90f04SDimitry Andric 4360623d748SDimitry Andric if (CodeGenOpts.DwarfVersion) { 437f785676fSDimitry Andric // We actually want the latest version when there are conflicts. 438f785676fSDimitry Andric // We can change from Warning to Latest if such mode is supported. 439f785676fSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 440f785676fSDimitry Andric CodeGenOpts.DwarfVersion); 4410623d748SDimitry Andric } 4420623d748SDimitry Andric if (CodeGenOpts.EmitCodeView) { 4430623d748SDimitry Andric // Indicate that we want CodeView in the metadata. 4440623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 4450623d748SDimitry Andric } 4460623d748SDimitry Andric if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 4470623d748SDimitry Andric // We don't support LTO with 2 with different StrictVTablePointers 4480623d748SDimitry Andric // FIXME: we could support it by stripping all the information introduced 4490623d748SDimitry Andric // by StrictVTablePointers. 4500623d748SDimitry Andric 4510623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 4520623d748SDimitry Andric 4530623d748SDimitry Andric llvm::Metadata *Ops[2] = { 4540623d748SDimitry Andric llvm::MDString::get(VMContext, "StrictVTablePointers"), 4550623d748SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 4560623d748SDimitry Andric llvm::Type::getInt32Ty(VMContext), 1))}; 4570623d748SDimitry Andric 4580623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Require, 4590623d748SDimitry Andric "StrictVTablePointersRequirement", 4600623d748SDimitry Andric llvm::MDNode::get(VMContext, Ops)); 4610623d748SDimitry Andric } 462f785676fSDimitry Andric if (DebugInfo) 46359d1ed5bSDimitry Andric // We support a single version in the linked module. The LLVM 46459d1ed5bSDimitry Andric // parser will drop debug info with a different version number 46559d1ed5bSDimitry Andric // (and warn about it, too). 46659d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 467f785676fSDimitry Andric llvm::DEBUG_METADATA_VERSION); 468139f7f9bSDimitry Andric 469d8866befSDimitry Andric // Width of wchar_t in bytes 470d8866befSDimitry Andric uint64_t WCharWidth = 471d8866befSDimitry Andric Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 472d8866befSDimitry Andric assert(LangOpts.ShortWChar || 473d8866befSDimitry Andric llvm::TargetLibraryInfoImpl::getTargetWCharSize(Target.getTriple()) == 474d8866befSDimitry Andric Target.getWCharWidth() / 8 && 475d8866befSDimitry Andric "LLVM wchar_t size out of sync"); 476d8866befSDimitry Andric 47759d1ed5bSDimitry Andric // We need to record the widths of enums and wchar_t, so that we can generate 478d8866befSDimitry Andric // the correct build attributes in the ARM backend. wchar_size is also used by 479d8866befSDimitry Andric // TargetLibraryInfo. 480d8866befSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 481d8866befSDimitry Andric 48259d1ed5bSDimitry Andric llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 48359d1ed5bSDimitry Andric if ( Arch == llvm::Triple::arm 48459d1ed5bSDimitry Andric || Arch == llvm::Triple::armeb 48559d1ed5bSDimitry Andric || Arch == llvm::Triple::thumb 48659d1ed5bSDimitry Andric || Arch == llvm::Triple::thumbeb) { 48759d1ed5bSDimitry Andric // The minimum width of an enum in bytes 48859d1ed5bSDimitry Andric uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 48959d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 49059d1ed5bSDimitry Andric } 49159d1ed5bSDimitry Andric 4920623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 4930623d748SDimitry Andric // Indicate that we want cross-DSO control flow integrity checks. 4940623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 4950623d748SDimitry Andric } 4960623d748SDimitry Andric 49744290647SDimitry Andric if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { 498e7145dcbSDimitry Andric // Indicate whether __nvvm_reflect should be configured to flush denormal 499e7145dcbSDimitry Andric // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 500e7145dcbSDimitry Andric // property.) 501e7145dcbSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 502e7145dcbSDimitry Andric LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0); 50339d628a0SDimitry Andric } 50439d628a0SDimitry Andric 505e7145dcbSDimitry Andric if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 506e7145dcbSDimitry Andric assert(PLevel < 3 && "Invalid PIC Level"); 507e7145dcbSDimitry Andric getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 508e7145dcbSDimitry Andric if (Context.getLangOpts().PIE) 509e7145dcbSDimitry Andric getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 51039d628a0SDimitry Andric } 51139d628a0SDimitry Andric 5122754fe60SDimitry Andric SimplifyPersonality(); 5132754fe60SDimitry Andric 514ffd1746dSEd Schouten if (getCodeGenOpts().EmitDeclMetadata) 515ffd1746dSEd Schouten EmitDeclMetadata(); 516bd5abe19SDimitry Andric 517bd5abe19SDimitry Andric if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 518bd5abe19SDimitry Andric EmitCoverageFile(); 5196122f3e6SDimitry Andric 5206122f3e6SDimitry Andric if (DebugInfo) 5216122f3e6SDimitry Andric DebugInfo->finalize(); 522f785676fSDimitry Andric 523f785676fSDimitry Andric EmitVersionIdentMetadata(); 52459d1ed5bSDimitry Andric 52559d1ed5bSDimitry Andric EmitTargetMetadata(); 526f22ef01cSRoman Divacky } 527f22ef01cSRoman Divacky 5283b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 5293b0f4066SDimitry Andric // Make sure that this type is translated. 5303b0f4066SDimitry Andric Types.UpdateCompletedType(TD); 5313b0f4066SDimitry Andric } 5323b0f4066SDimitry Andric 533e7145dcbSDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 534e7145dcbSDimitry Andric // Make sure that this type is translated. 535e7145dcbSDimitry Andric Types.RefreshTypeCacheForClass(RD); 536e7145dcbSDimitry Andric } 537e7145dcbSDimitry Andric 5382754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 5392754fe60SDimitry Andric if (!TBAA) 54059d1ed5bSDimitry Andric return nullptr; 5412754fe60SDimitry Andric return TBAA->getTBAAInfo(QTy); 5422754fe60SDimitry Andric } 5432754fe60SDimitry Andric 544dff0c46cSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 545dff0c46cSDimitry Andric if (!TBAA) 54659d1ed5bSDimitry Andric return nullptr; 547dff0c46cSDimitry Andric return TBAA->getTBAAInfoForVTablePtr(); 548dff0c46cSDimitry Andric } 549dff0c46cSDimitry Andric 5503861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 5513861d79fSDimitry Andric if (!TBAA) 55259d1ed5bSDimitry Andric return nullptr; 5533861d79fSDimitry Andric return TBAA->getTBAAStructInfo(QTy); 5543861d79fSDimitry Andric } 5553861d79fSDimitry Andric 556139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy, 557139f7f9bSDimitry Andric llvm::MDNode *AccessN, 558139f7f9bSDimitry Andric uint64_t O) { 559139f7f9bSDimitry Andric if (!TBAA) 56059d1ed5bSDimitry Andric return nullptr; 561139f7f9bSDimitry Andric return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O); 562139f7f9bSDimitry Andric } 563139f7f9bSDimitry Andric 564f785676fSDimitry Andric /// Decorate the instruction with a TBAA tag. For both scalar TBAA 565f785676fSDimitry Andric /// and struct-path aware TBAA, the tag has the same format: 566f785676fSDimitry Andric /// base type, access type and offset. 567284c1978SDimitry Andric /// When ConvertTypeToTag is true, we create a tag based on the scalar type. 5680623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 569284c1978SDimitry Andric llvm::MDNode *TBAAInfo, 570284c1978SDimitry Andric bool ConvertTypeToTag) { 571f785676fSDimitry Andric if (ConvertTypeToTag && TBAA) 572284c1978SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, 573284c1978SDimitry Andric TBAA->getTBAAScalarTagInfo(TBAAInfo)); 574284c1978SDimitry Andric else 5752754fe60SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 5762754fe60SDimitry Andric } 5772754fe60SDimitry Andric 5780623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup( 5790623d748SDimitry Andric llvm::Instruction *I, const CXXRecordDecl *RD) { 58051690af2SDimitry Andric I->setMetadata(llvm::LLVMContext::MD_invariant_group, 58151690af2SDimitry Andric llvm::MDNode::get(getLLVMContext(), {})); 5820623d748SDimitry Andric } 5830623d748SDimitry Andric 58459d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) { 58559d1ed5bSDimitry Andric unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 58659d1ed5bSDimitry Andric getDiags().Report(Context.getFullLoc(loc), diagID) << message; 587f22ef01cSRoman Divacky } 588f22ef01cSRoman Divacky 589f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 590f22ef01cSRoman Divacky /// specified stmt yet. 591f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 5926122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 593f22ef01cSRoman Divacky "cannot compile this %0 yet"); 594f22ef01cSRoman Divacky std::string Msg = Type; 595f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 596f22ef01cSRoman Divacky << Msg << S->getSourceRange(); 597f22ef01cSRoman Divacky } 598f22ef01cSRoman Divacky 599f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 600f22ef01cSRoman Divacky /// specified decl yet. 601f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 6026122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 603f22ef01cSRoman Divacky "cannot compile this %0 yet"); 604f22ef01cSRoman Divacky std::string Msg = Type; 605f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 606f22ef01cSRoman Divacky } 607f22ef01cSRoman Divacky 60817a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 60917a519f9SDimitry Andric return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 61017a519f9SDimitry Andric } 61117a519f9SDimitry Andric 612f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 6132754fe60SDimitry Andric const NamedDecl *D) const { 614f22ef01cSRoman Divacky // Internal definitions always have default visibility. 615f22ef01cSRoman Divacky if (GV->hasLocalLinkage()) { 616f22ef01cSRoman Divacky GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 617f22ef01cSRoman Divacky return; 618f22ef01cSRoman Divacky } 619f22ef01cSRoman Divacky 6202754fe60SDimitry Andric // Set visibility for definitions. 621139f7f9bSDimitry Andric LinkageInfo LV = D->getLinkageAndVisibility(); 622139f7f9bSDimitry Andric if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 623139f7f9bSDimitry Andric GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 624f22ef01cSRoman Divacky } 625f22ef01cSRoman Divacky 6267ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 6277ae0e2c9SDimitry Andric return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 6287ae0e2c9SDimitry Andric .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 6297ae0e2c9SDimitry Andric .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 6307ae0e2c9SDimitry Andric .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 6317ae0e2c9SDimitry Andric .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 6327ae0e2c9SDimitry Andric } 6337ae0e2c9SDimitry Andric 6347ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 6357ae0e2c9SDimitry Andric CodeGenOptions::TLSModel M) { 6367ae0e2c9SDimitry Andric switch (M) { 6377ae0e2c9SDimitry Andric case CodeGenOptions::GeneralDynamicTLSModel: 6387ae0e2c9SDimitry Andric return llvm::GlobalVariable::GeneralDynamicTLSModel; 6397ae0e2c9SDimitry Andric case CodeGenOptions::LocalDynamicTLSModel: 6407ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalDynamicTLSModel; 6417ae0e2c9SDimitry Andric case CodeGenOptions::InitialExecTLSModel: 6427ae0e2c9SDimitry Andric return llvm::GlobalVariable::InitialExecTLSModel; 6437ae0e2c9SDimitry Andric case CodeGenOptions::LocalExecTLSModel: 6447ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalExecTLSModel; 6457ae0e2c9SDimitry Andric } 6467ae0e2c9SDimitry Andric llvm_unreachable("Invalid TLS model!"); 6477ae0e2c9SDimitry Andric } 6487ae0e2c9SDimitry Andric 64939d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 650284c1978SDimitry Andric assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 6517ae0e2c9SDimitry Andric 65239d628a0SDimitry Andric llvm::GlobalValue::ThreadLocalMode TLM; 6533861d79fSDimitry Andric TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 6547ae0e2c9SDimitry Andric 6557ae0e2c9SDimitry Andric // Override the TLS model if it is explicitly specified. 65659d1ed5bSDimitry Andric if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 6577ae0e2c9SDimitry Andric TLM = GetLLVMTLSModel(Attr->getModel()); 6587ae0e2c9SDimitry Andric } 6597ae0e2c9SDimitry Andric 6607ae0e2c9SDimitry Andric GV->setThreadLocalMode(TLM); 6617ae0e2c9SDimitry Andric } 6627ae0e2c9SDimitry Andric 6636122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 664444ed5c5SDimitry Andric GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 665444ed5c5SDimitry Andric 666444ed5c5SDimitry Andric // Some ABIs don't have constructor variants. Make sure that base and 667444ed5c5SDimitry Andric // complete constructors get mangled the same. 668444ed5c5SDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 669444ed5c5SDimitry Andric if (!getTarget().getCXXABI().hasConstructorVariants()) { 670444ed5c5SDimitry Andric CXXCtorType OrigCtorType = GD.getCtorType(); 671444ed5c5SDimitry Andric assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 672444ed5c5SDimitry Andric if (OrigCtorType == Ctor_Base) 673444ed5c5SDimitry Andric CanonicalGD = GlobalDecl(CD, Ctor_Complete); 674444ed5c5SDimitry Andric } 675444ed5c5SDimitry Andric } 676444ed5c5SDimitry Andric 677444ed5c5SDimitry Andric StringRef &FoundStr = MangledDeclNames[CanonicalGD]; 67859d1ed5bSDimitry Andric if (!FoundStr.empty()) 67959d1ed5bSDimitry Andric return FoundStr; 680f22ef01cSRoman Divacky 68159d1ed5bSDimitry Andric const auto *ND = cast<NamedDecl>(GD.getDecl()); 682dff0c46cSDimitry Andric SmallString<256> Buffer; 68359d1ed5bSDimitry Andric StringRef Str; 68459d1ed5bSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 6852754fe60SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 68659d1ed5bSDimitry Andric if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) 6872754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 68859d1ed5bSDimitry Andric else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) 6892754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 690ffd1746dSEd Schouten else 6912754fe60SDimitry Andric getCXXABI().getMangleContext().mangleName(ND, Out); 69259d1ed5bSDimitry Andric Str = Out.str(); 69359d1ed5bSDimitry Andric } else { 69459d1ed5bSDimitry Andric IdentifierInfo *II = ND->getIdentifier(); 69559d1ed5bSDimitry Andric assert(II && "Attempt to mangle unnamed decl."); 69644290647SDimitry Andric const auto *FD = dyn_cast<FunctionDecl>(ND); 69744290647SDimitry Andric 69844290647SDimitry Andric if (FD && 69944290647SDimitry Andric FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 70044290647SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 70144290647SDimitry Andric Out << "__regcall3__" << II->getName(); 70244290647SDimitry Andric Str = Out.str(); 70344290647SDimitry Andric } else { 70459d1ed5bSDimitry Andric Str = II->getName(); 705ffd1746dSEd Schouten } 70644290647SDimitry Andric } 707ffd1746dSEd Schouten 70839d628a0SDimitry Andric // Keep the first result in the case of a mangling collision. 70939d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Str, GD)); 71039d628a0SDimitry Andric return FoundStr = Result.first->first(); 71159d1ed5bSDimitry Andric } 71259d1ed5bSDimitry Andric 71359d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 714ffd1746dSEd Schouten const BlockDecl *BD) { 7152754fe60SDimitry Andric MangleContext &MangleCtx = getCXXABI().getMangleContext(); 7162754fe60SDimitry Andric const Decl *D = GD.getDecl(); 71759d1ed5bSDimitry Andric 71859d1ed5bSDimitry Andric SmallString<256> Buffer; 71959d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(Buffer); 72059d1ed5bSDimitry Andric if (!D) 7217ae0e2c9SDimitry Andric MangleCtx.mangleGlobalBlock(BD, 7227ae0e2c9SDimitry Andric dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 72359d1ed5bSDimitry Andric else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 7242754fe60SDimitry Andric MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 72559d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 7262754fe60SDimitry Andric MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 7272754fe60SDimitry Andric else 7282754fe60SDimitry Andric MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 72959d1ed5bSDimitry Andric 73039d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 73139d628a0SDimitry Andric return Result.first->first(); 732f22ef01cSRoman Divacky } 733f22ef01cSRoman Divacky 7346122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 735f22ef01cSRoman Divacky return getModule().getNamedValue(Name); 736f22ef01cSRoman Divacky } 737f22ef01cSRoman Divacky 738f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before 739f22ef01cSRoman Divacky /// main() runs. 74059d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 74159d1ed5bSDimitry Andric llvm::Constant *AssociatedData) { 742f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 74359d1ed5bSDimitry Andric GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 744f22ef01cSRoman Divacky } 745f22ef01cSRoman Divacky 746f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called 747f22ef01cSRoman Divacky /// when the module is unloaded. 748f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) { 749f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 75059d1ed5bSDimitry Andric GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 751f22ef01cSRoman Divacky } 752f22ef01cSRoman Divacky 75344290647SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 75444290647SDimitry Andric if (Fns.empty()) return; 75544290647SDimitry Andric 756f22ef01cSRoman Divacky // Ctor function type is void()*. 757bd5abe19SDimitry Andric llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 758f22ef01cSRoman Divacky llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 759f22ef01cSRoman Divacky 76059d1ed5bSDimitry Andric // Get the type of a ctor entry, { i32, void ()*, i8* }. 76159d1ed5bSDimitry Andric llvm::StructType *CtorStructTy = llvm::StructType::get( 7625517e702SDimitry Andric Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy); 763f22ef01cSRoman Divacky 764f22ef01cSRoman Divacky // Construct the constructor and destructor arrays. 76544290647SDimitry Andric ConstantInitBuilder builder(*this); 76644290647SDimitry Andric auto ctors = builder.beginArray(CtorStructTy); 7678f0fd8f6SDimitry Andric for (const auto &I : Fns) { 76844290647SDimitry Andric auto ctor = ctors.beginStruct(CtorStructTy); 76944290647SDimitry Andric ctor.addInt(Int32Ty, I.Priority); 77044290647SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); 77144290647SDimitry Andric if (I.AssociatedData) 77244290647SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); 77344290647SDimitry Andric else 77444290647SDimitry Andric ctor.addNullPointer(VoidPtrTy); 77544290647SDimitry Andric ctor.finishAndAddTo(ctors); 776f22ef01cSRoman Divacky } 777f22ef01cSRoman Divacky 77844290647SDimitry Andric auto list = 77944290647SDimitry Andric ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 78044290647SDimitry Andric /*constant*/ false, 78144290647SDimitry Andric llvm::GlobalValue::AppendingLinkage); 78244290647SDimitry Andric 78344290647SDimitry Andric // The LTO linker doesn't seem to like it when we set an alignment 78444290647SDimitry Andric // on appending variables. Take it off as a workaround. 78544290647SDimitry Andric list->setAlignment(0); 78644290647SDimitry Andric 78744290647SDimitry Andric Fns.clear(); 788f22ef01cSRoman Divacky } 789f22ef01cSRoman Divacky 790f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes 791f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 79259d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 793f785676fSDimitry Andric 794e580952dSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 795f22ef01cSRoman Divacky 79659d1ed5bSDimitry Andric if (isa<CXXDestructorDecl>(D) && 79759d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 79859d1ed5bSDimitry Andric GD.getDtorType())) { 79959d1ed5bSDimitry Andric // Destructor variants in the Microsoft C++ ABI are always internal or 80059d1ed5bSDimitry Andric // linkonce_odr thunks emitted on an as-needed basis. 80159d1ed5bSDimitry Andric return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage 80259d1ed5bSDimitry Andric : llvm::GlobalValue::LinkOnceODRLinkage; 803f22ef01cSRoman Divacky } 804f22ef01cSRoman Divacky 805e7145dcbSDimitry Andric if (isa<CXXConstructorDecl>(D) && 806e7145dcbSDimitry Andric cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 807e7145dcbSDimitry Andric Context.getTargetInfo().getCXXABI().isMicrosoft()) { 808e7145dcbSDimitry Andric // Our approach to inheriting constructors is fundamentally different from 809e7145dcbSDimitry Andric // that used by the MS ABI, so keep our inheriting constructor thunks 810e7145dcbSDimitry Andric // internal rather than trying to pick an unambiguous mangling for them. 811e7145dcbSDimitry Andric return llvm::GlobalValue::InternalLinkage; 812e7145dcbSDimitry Andric } 813e7145dcbSDimitry Andric 81459d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false); 81559d1ed5bSDimitry Andric } 816f22ef01cSRoman Divacky 81797bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) { 81897bc6c73SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 81997bc6c73SDimitry Andric 82097bc6c73SDimitry Andric if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) { 82197bc6c73SDimitry Andric if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) { 82297bc6c73SDimitry Andric // Don't dllexport/import destructor thunks. 82397bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 82497bc6c73SDimitry Andric return; 82597bc6c73SDimitry Andric } 82697bc6c73SDimitry Andric } 82797bc6c73SDimitry Andric 82897bc6c73SDimitry Andric if (FD->hasAttr<DLLImportAttr>()) 82997bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 83097bc6c73SDimitry Andric else if (FD->hasAttr<DLLExportAttr>()) 83197bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 83297bc6c73SDimitry Andric else 83397bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 83497bc6c73SDimitry Andric } 83597bc6c73SDimitry Andric 836e7145dcbSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 8370623d748SDimitry Andric llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 8380623d748SDimitry Andric if (!MDS) return nullptr; 8390623d748SDimitry Andric 84044290647SDimitry Andric return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 8410623d748SDimitry Andric } 8420623d748SDimitry Andric 84359d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D, 84459d1ed5bSDimitry Andric llvm::Function *F) { 84559d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 846f22ef01cSRoman Divacky } 847f22ef01cSRoman Divacky 848f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 849f22ef01cSRoman Divacky const CGFunctionInfo &Info, 850f22ef01cSRoman Divacky llvm::Function *F) { 851f22ef01cSRoman Divacky unsigned CallingConv; 8526bc11b14SDimitry Andric llvm::AttributeList PAL; 8536bc11b14SDimitry Andric ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false); 8546bc11b14SDimitry Andric F->setAttributes(PAL); 855f22ef01cSRoman Divacky F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 856f22ef01cSRoman Divacky } 857f22ef01cSRoman Divacky 8586122f3e6SDimitry Andric /// Determines whether the language options require us to model 8596122f3e6SDimitry Andric /// unwind exceptions. We treat -fexceptions as mandating this 8606122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions 8616122f3e6SDimitry Andric /// enabled. This means, for example, that C with -fexceptions 8626122f3e6SDimitry Andric /// enables this. 863dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) { 8646122f3e6SDimitry Andric // If exceptions are completely disabled, obviously this is false. 865dff0c46cSDimitry Andric if (!LangOpts.Exceptions) return false; 8666122f3e6SDimitry Andric 8676122f3e6SDimitry Andric // If C++ exceptions are enabled, this is true. 868dff0c46cSDimitry Andric if (LangOpts.CXXExceptions) return true; 8696122f3e6SDimitry Andric 8706122f3e6SDimitry Andric // If ObjC exceptions are enabled, this depends on the ABI. 871dff0c46cSDimitry Andric if (LangOpts.ObjCExceptions) { 8727ae0e2c9SDimitry Andric return LangOpts.ObjCRuntime.hasUnwindExceptions(); 8736122f3e6SDimitry Andric } 8746122f3e6SDimitry Andric 8756122f3e6SDimitry Andric return true; 8766122f3e6SDimitry Andric } 8776122f3e6SDimitry Andric 878f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 879f22ef01cSRoman Divacky llvm::Function *F) { 880f785676fSDimitry Andric llvm::AttrBuilder B; 881f785676fSDimitry Andric 882bd5abe19SDimitry Andric if (CodeGenOpts.UnwindTables) 883f785676fSDimitry Andric B.addAttribute(llvm::Attribute::UWTable); 884bd5abe19SDimitry Andric 885dff0c46cSDimitry Andric if (!hasUnwindExceptions(LangOpts)) 886f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoUnwind); 887f22ef01cSRoman Divacky 8880623d748SDimitry Andric if (LangOpts.getStackProtector() == LangOptions::SSPOn) 8890623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtect); 8900623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 8910623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 8920623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 8930623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectReq); 8940623d748SDimitry Andric 8950623d748SDimitry Andric if (!D) { 89644290647SDimitry Andric // If we don't have a declaration to control inlining, the function isn't 89744290647SDimitry Andric // explicitly marked as alwaysinline for semantic reasons, and inlining is 89844290647SDimitry Andric // disabled, mark the function as noinline. 89944290647SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 90044290647SDimitry Andric CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 90144290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 90244290647SDimitry Andric 903f37b6182SDimitry Andric F->addAttributes(llvm::AttributeList::FunctionIndex, B); 9040623d748SDimitry Andric return; 9050623d748SDimitry Andric } 9060623d748SDimitry Andric 90744290647SDimitry Andric if (D->hasAttr<OptimizeNoneAttr>()) { 90844290647SDimitry Andric B.addAttribute(llvm::Attribute::OptimizeNone); 90944290647SDimitry Andric 91044290647SDimitry Andric // OptimizeNone implies noinline; we should not be inlining such functions. 91144290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 91244290647SDimitry Andric assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 91344290647SDimitry Andric "OptimizeNone and AlwaysInline on same function!"); 91444290647SDimitry Andric 91544290647SDimitry Andric // We still need to handle naked functions even though optnone subsumes 91644290647SDimitry Andric // much of their semantics. 91744290647SDimitry Andric if (D->hasAttr<NakedAttr>()) 91844290647SDimitry Andric B.addAttribute(llvm::Attribute::Naked); 91944290647SDimitry Andric 92044290647SDimitry Andric // OptimizeNone wins over OptimizeForSize and MinSize. 92144290647SDimitry Andric F->removeFnAttr(llvm::Attribute::OptimizeForSize); 92244290647SDimitry Andric F->removeFnAttr(llvm::Attribute::MinSize); 92344290647SDimitry Andric } else if (D->hasAttr<NakedAttr>()) { 9246122f3e6SDimitry Andric // Naked implies noinline: we should not be inlining such functions. 925f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Naked); 926f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 92759d1ed5bSDimitry Andric } else if (D->hasAttr<NoDuplicateAttr>()) { 92859d1ed5bSDimitry Andric B.addAttribute(llvm::Attribute::NoDuplicate); 929f785676fSDimitry Andric } else if (D->hasAttr<NoInlineAttr>()) { 930f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 93159d1ed5bSDimitry Andric } else if (D->hasAttr<AlwaysInlineAttr>() && 93244290647SDimitry Andric !F->hasFnAttribute(llvm::Attribute::NoInline)) { 933f785676fSDimitry Andric // (noinline wins over always_inline, and we can't specify both in IR) 934f785676fSDimitry Andric B.addAttribute(llvm::Attribute::AlwaysInline); 93544290647SDimitry Andric } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 93644290647SDimitry Andric // If we're not inlining, then force everything that isn't always_inline to 93744290647SDimitry Andric // carry an explicit noinline attribute. 93844290647SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 93944290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 94044290647SDimitry Andric } else { 94144290647SDimitry Andric // Otherwise, propagate the inline hint attribute and potentially use its 94244290647SDimitry Andric // absence to mark things as noinline. 94344290647SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) { 94444290647SDimitry Andric if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) { 94544290647SDimitry Andric return Redecl->isInlineSpecified(); 94644290647SDimitry Andric })) { 94744290647SDimitry Andric B.addAttribute(llvm::Attribute::InlineHint); 94844290647SDimitry Andric } else if (CodeGenOpts.getInlining() == 94944290647SDimitry Andric CodeGenOptions::OnlyHintInlining && 95044290647SDimitry Andric !FD->isInlined() && 95144290647SDimitry Andric !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 95244290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 95344290647SDimitry Andric } 95444290647SDimitry Andric } 9556122f3e6SDimitry Andric } 9562754fe60SDimitry Andric 95744290647SDimitry Andric // Add other optimization related attributes if we are optimizing this 95844290647SDimitry Andric // function. 95944290647SDimitry Andric if (!D->hasAttr<OptimizeNoneAttr>()) { 960f785676fSDimitry Andric if (D->hasAttr<ColdAttr>()) { 961f785676fSDimitry Andric B.addAttribute(llvm::Attribute::OptimizeForSize); 962f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Cold); 963f785676fSDimitry Andric } 9643861d79fSDimitry Andric 9653861d79fSDimitry Andric if (D->hasAttr<MinSizeAttr>()) 966f785676fSDimitry Andric B.addAttribute(llvm::Attribute::MinSize); 96744290647SDimitry Andric } 968f22ef01cSRoman Divacky 969f37b6182SDimitry Andric F->addAttributes(llvm::AttributeList::FunctionIndex, B); 970f785676fSDimitry Andric 971e580952dSDimitry Andric unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 972e580952dSDimitry Andric if (alignment) 973e580952dSDimitry Andric F->setAlignment(alignment); 974e580952dSDimitry Andric 9750623d748SDimitry Andric // Some C++ ABIs require 2-byte alignment for member functions, in order to 9760623d748SDimitry Andric // reserve a bit for differentiating between virtual and non-virtual member 9770623d748SDimitry Andric // functions. If the current target's C++ ABI requires this and this is a 9780623d748SDimitry Andric // member function, set its alignment accordingly. 9790623d748SDimitry Andric if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 980f22ef01cSRoman Divacky if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 981f22ef01cSRoman Divacky F->setAlignment(2); 982f22ef01cSRoman Divacky } 98344290647SDimitry Andric 98444290647SDimitry Andric // In the cross-dso CFI mode, we want !type attributes on definitions only. 98544290647SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 98644290647SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) 98744290647SDimitry Andric CreateFunctionTypeMetadata(FD, F); 9880623d748SDimitry Andric } 989f22ef01cSRoman Divacky 990f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D, 991f22ef01cSRoman Divacky llvm::GlobalValue *GV) { 9920623d748SDimitry Andric if (const auto *ND = dyn_cast_or_null<NamedDecl>(D)) 9932754fe60SDimitry Andric setGlobalVisibility(GV, ND); 9942754fe60SDimitry Andric else 9952754fe60SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 996f22ef01cSRoman Divacky 9970623d748SDimitry Andric if (D && D->hasAttr<UsedAttr>()) 99859d1ed5bSDimitry Andric addUsedGlobal(GV); 99959d1ed5bSDimitry Andric } 100059d1ed5bSDimitry Andric 100139d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D, 100239d628a0SDimitry Andric llvm::GlobalValue *GV) { 100339d628a0SDimitry Andric SetCommonAttributes(D, GV); 100439d628a0SDimitry Andric 100539d628a0SDimitry Andric // Process the dllexport attribute based on whether the original definition 100639d628a0SDimitry Andric // (not necessarily the aliasee) was exported. 100739d628a0SDimitry Andric if (D->hasAttr<DLLExportAttr>()) 100839d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 100939d628a0SDimitry Andric } 101039d628a0SDimitry Andric 101159d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D, 101259d1ed5bSDimitry Andric llvm::GlobalObject *GO) { 101359d1ed5bSDimitry Andric SetCommonAttributes(D, GO); 1014f22ef01cSRoman Divacky 10150623d748SDimitry Andric if (D) 1016f22ef01cSRoman Divacky if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 101759d1ed5bSDimitry Andric GO->setSection(SA->getName()); 1018f22ef01cSRoman Divacky 101997bc6c73SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 1020f22ef01cSRoman Divacky } 1021f22ef01cSRoman Divacky 1022f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 1023f22ef01cSRoman Divacky llvm::Function *F, 1024f22ef01cSRoman Divacky const CGFunctionInfo &FI) { 1025f22ef01cSRoman Divacky SetLLVMFunctionAttributes(D, FI, F); 1026f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, F); 1027f22ef01cSRoman Divacky 1028f22ef01cSRoman Divacky F->setLinkage(llvm::Function::InternalLinkage); 1029f22ef01cSRoman Divacky 103059d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 103159d1ed5bSDimitry Andric } 103259d1ed5bSDimitry Andric 103359d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, 103459d1ed5bSDimitry Andric const NamedDecl *ND) { 103559d1ed5bSDimitry Andric // Set linkage and visibility in case we never see a definition. 103659d1ed5bSDimitry Andric LinkageInfo LV = ND->getLinkageAndVisibility(); 103759d1ed5bSDimitry Andric if (LV.getLinkage() != ExternalLinkage) { 103859d1ed5bSDimitry Andric // Don't set internal linkage on declarations. 103959d1ed5bSDimitry Andric } else { 104059d1ed5bSDimitry Andric if (ND->hasAttr<DLLImportAttr>()) { 104159d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 104259d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 104359d1ed5bSDimitry Andric } else if (ND->hasAttr<DLLExportAttr>()) { 104459d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 104559d1ed5bSDimitry Andric } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 104659d1ed5bSDimitry Andric // "extern_weak" is overloaded in LLVM; we probably should have 104759d1ed5bSDimitry Andric // separate linkage types for this. 104859d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 104959d1ed5bSDimitry Andric } 105059d1ed5bSDimitry Andric 105159d1ed5bSDimitry Andric // Set visibility on a declaration only if it's explicit. 105259d1ed5bSDimitry Andric if (LV.isVisibilityExplicit()) 105359d1ed5bSDimitry Andric GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility())); 105459d1ed5bSDimitry Andric } 1055f22ef01cSRoman Divacky } 1056f22ef01cSRoman Divacky 1057e7145dcbSDimitry Andric void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD, 10580623d748SDimitry Andric llvm::Function *F) { 10590623d748SDimitry Andric // Only if we are checking indirect calls. 10600623d748SDimitry Andric if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 10610623d748SDimitry Andric return; 10620623d748SDimitry Andric 10630623d748SDimitry Andric // Non-static class methods are handled via vtable pointer checks elsewhere. 10640623d748SDimitry Andric if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 10650623d748SDimitry Andric return; 10660623d748SDimitry Andric 10670623d748SDimitry Andric // Additionally, if building with cross-DSO support... 10680623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 10690623d748SDimitry Andric // Skip available_externally functions. They won't be codegen'ed in the 10700623d748SDimitry Andric // current module anyway. 10710623d748SDimitry Andric if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally) 10720623d748SDimitry Andric return; 10730623d748SDimitry Andric } 10740623d748SDimitry Andric 10750623d748SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 1076e7145dcbSDimitry Andric F->addTypeMetadata(0, MD); 10770623d748SDimitry Andric 10780623d748SDimitry Andric // Emit a hash-based bit set entry for cross-DSO calls. 1079e7145dcbSDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 1080e7145dcbSDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 1081e7145dcbSDimitry Andric F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 10820623d748SDimitry Andric } 10830623d748SDimitry Andric 108439d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 108539d628a0SDimitry Andric bool IsIncompleteFunction, 108639d628a0SDimitry Andric bool IsThunk) { 108733956c43SDimitry Andric if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 10883b0f4066SDimitry Andric // If this is an intrinsic function, set the function's attributes 10893b0f4066SDimitry Andric // to the intrinsic's attributes. 109033956c43SDimitry Andric F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 10913b0f4066SDimitry Andric return; 10923b0f4066SDimitry Andric } 10933b0f4066SDimitry Andric 109459d1ed5bSDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1095f22ef01cSRoman Divacky 1096f22ef01cSRoman Divacky if (!IsIncompleteFunction) 1097dff0c46cSDimitry Andric SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 1098f22ef01cSRoman Divacky 109959d1ed5bSDimitry Andric // Add the Returned attribute for "this", except for iOS 5 and earlier 110059d1ed5bSDimitry Andric // where substantial code, including the libstdc++ dylib, was compiled with 110159d1ed5bSDimitry Andric // GCC and does not actually return "this". 110239d628a0SDimitry Andric if (!IsThunk && getCXXABI().HasThisReturn(GD) && 110344290647SDimitry Andric !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 1104f785676fSDimitry Andric assert(!F->arg_empty() && 1105f785676fSDimitry Andric F->arg_begin()->getType() 1106f785676fSDimitry Andric ->canLosslesslyBitCastTo(F->getReturnType()) && 1107f785676fSDimitry Andric "unexpected this return"); 1108f785676fSDimitry Andric F->addAttribute(1, llvm::Attribute::Returned); 1109f785676fSDimitry Andric } 1110f785676fSDimitry Andric 1111f22ef01cSRoman Divacky // Only a few attributes are set on declarations; these may later be 1112f22ef01cSRoman Divacky // overridden by a definition. 1113f22ef01cSRoman Divacky 111459d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(F, FD); 11152754fe60SDimitry Andric 1116f22ef01cSRoman Divacky if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 1117f22ef01cSRoman Divacky F->setSection(SA->getName()); 1118f785676fSDimitry Andric 1119e7145dcbSDimitry Andric if (FD->isReplaceableGlobalAllocationFunction()) { 1120f785676fSDimitry Andric // A replaceable global allocation function does not act like a builtin by 1121f785676fSDimitry Andric // default, only if it is invoked by a new-expression or delete-expression. 112220e90f04SDimitry Andric F->addAttribute(llvm::AttributeList::FunctionIndex, 1123f785676fSDimitry Andric llvm::Attribute::NoBuiltin); 11240623d748SDimitry Andric 1125e7145dcbSDimitry Andric // A sane operator new returns a non-aliasing pointer. 1126e7145dcbSDimitry Andric // FIXME: Also add NonNull attribute to the return value 1127e7145dcbSDimitry Andric // for the non-nothrow forms? 1128e7145dcbSDimitry Andric auto Kind = FD->getDeclName().getCXXOverloadedOperator(); 1129e7145dcbSDimitry Andric if (getCodeGenOpts().AssumeSaneOperatorNew && 1130e7145dcbSDimitry Andric (Kind == OO_New || Kind == OO_Array_New)) 113120e90f04SDimitry Andric F->addAttribute(llvm::AttributeList::ReturnIndex, 1132e7145dcbSDimitry Andric llvm::Attribute::NoAlias); 1133e7145dcbSDimitry Andric } 1134e7145dcbSDimitry Andric 1135e7145dcbSDimitry Andric if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 1136e7145dcbSDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1137e7145dcbSDimitry Andric else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 1138e7145dcbSDimitry Andric if (MD->isVirtual()) 1139e7145dcbSDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1140e7145dcbSDimitry Andric 114144290647SDimitry Andric // Don't emit entries for function declarations in the cross-DSO mode. This 114244290647SDimitry Andric // is handled with better precision by the receiving DSO. 114344290647SDimitry Andric if (!CodeGenOpts.SanitizeCfiCrossDso) 1144e7145dcbSDimitry Andric CreateFunctionTypeMetadata(FD, F); 1145f22ef01cSRoman Divacky } 1146f22ef01cSRoman Divacky 114759d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 1148f22ef01cSRoman Divacky assert(!GV->isDeclaration() && 1149f22ef01cSRoman Divacky "Only globals with definition can force usage."); 115097bc6c73SDimitry Andric LLVMUsed.emplace_back(GV); 1151f22ef01cSRoman Divacky } 1152f22ef01cSRoman Divacky 115359d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 115459d1ed5bSDimitry Andric assert(!GV->isDeclaration() && 115559d1ed5bSDimitry Andric "Only globals with definition can force usage."); 115697bc6c73SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 115759d1ed5bSDimitry Andric } 115859d1ed5bSDimitry Andric 115959d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name, 1160f37b6182SDimitry Andric std::vector<llvm::WeakTrackingVH> &List) { 1161f22ef01cSRoman Divacky // Don't create llvm.used if there is no need. 116259d1ed5bSDimitry Andric if (List.empty()) 1163f22ef01cSRoman Divacky return; 1164f22ef01cSRoman Divacky 116559d1ed5bSDimitry Andric // Convert List to what ConstantArray needs. 1166dff0c46cSDimitry Andric SmallVector<llvm::Constant*, 8> UsedArray; 116759d1ed5bSDimitry Andric UsedArray.resize(List.size()); 116859d1ed5bSDimitry Andric for (unsigned i = 0, e = List.size(); i != e; ++i) { 1169f22ef01cSRoman Divacky UsedArray[i] = 117044f7b0dcSDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 117144f7b0dcSDimitry Andric cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 1172f22ef01cSRoman Divacky } 1173f22ef01cSRoman Divacky 1174f22ef01cSRoman Divacky if (UsedArray.empty()) 1175f22ef01cSRoman Divacky return; 117659d1ed5bSDimitry Andric llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 1177f22ef01cSRoman Divacky 117859d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 117959d1ed5bSDimitry Andric CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 118059d1ed5bSDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), Name); 1181f22ef01cSRoman Divacky 1182f22ef01cSRoman Divacky GV->setSection("llvm.metadata"); 1183f22ef01cSRoman Divacky } 1184f22ef01cSRoman Divacky 118559d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() { 118659d1ed5bSDimitry Andric emitUsed(*this, "llvm.used", LLVMUsed); 118759d1ed5bSDimitry Andric emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 118859d1ed5bSDimitry Andric } 118959d1ed5bSDimitry Andric 1190f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 119139d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 1192f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1193f785676fSDimitry Andric } 1194f785676fSDimitry Andric 1195f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 1196f785676fSDimitry Andric llvm::SmallString<32> Opt; 1197f785676fSDimitry Andric getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 119839d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1199f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1200f785676fSDimitry Andric } 1201f785676fSDimitry Andric 1202f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) { 1203f785676fSDimitry Andric llvm::SmallString<24> Opt; 1204f785676fSDimitry Andric getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 120539d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1206f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1207f785676fSDimitry Andric } 1208f785676fSDimitry Andric 1209139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules 1210139f7f9bSDimitry Andric /// it depends on, using a postorder walk. 121139d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 121239d628a0SDimitry Andric SmallVectorImpl<llvm::Metadata *> &Metadata, 1213139f7f9bSDimitry Andric llvm::SmallPtrSet<Module *, 16> &Visited) { 1214139f7f9bSDimitry Andric // Import this module's parent. 121539d628a0SDimitry Andric if (Mod->Parent && Visited.insert(Mod->Parent).second) { 1216f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 1217139f7f9bSDimitry Andric } 1218139f7f9bSDimitry Andric 1219139f7f9bSDimitry Andric // Import this module's dependencies. 1220139f7f9bSDimitry Andric for (unsigned I = Mod->Imports.size(); I > 0; --I) { 122139d628a0SDimitry Andric if (Visited.insert(Mod->Imports[I - 1]).second) 1222f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 1223139f7f9bSDimitry Andric } 1224139f7f9bSDimitry Andric 1225139f7f9bSDimitry Andric // Add linker options to link against the libraries/frameworks 1226139f7f9bSDimitry Andric // described by this module. 1227f785676fSDimitry Andric llvm::LLVMContext &Context = CGM.getLLVMContext(); 1228139f7f9bSDimitry Andric for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 1229f785676fSDimitry Andric // Link against a framework. Frameworks are currently Darwin only, so we 1230f785676fSDimitry Andric // don't to ask TargetCodeGenInfo for the spelling of the linker option. 1231139f7f9bSDimitry Andric if (Mod->LinkLibraries[I-1].IsFramework) { 123239d628a0SDimitry Andric llvm::Metadata *Args[2] = { 1233139f7f9bSDimitry Andric llvm::MDString::get(Context, "-framework"), 123439d628a0SDimitry Andric llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 1235139f7f9bSDimitry Andric 1236139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 1237139f7f9bSDimitry Andric continue; 1238139f7f9bSDimitry Andric } 1239139f7f9bSDimitry Andric 1240139f7f9bSDimitry Andric // Link against a library. 1241f785676fSDimitry Andric llvm::SmallString<24> Opt; 1242f785676fSDimitry Andric CGM.getTargetCodeGenInfo().getDependentLibraryOption( 1243f785676fSDimitry Andric Mod->LinkLibraries[I-1].Library, Opt); 124439d628a0SDimitry Andric auto *OptString = llvm::MDString::get(Context, Opt); 1245139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, OptString)); 1246139f7f9bSDimitry Andric } 1247139f7f9bSDimitry Andric } 1248139f7f9bSDimitry Andric 1249139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() { 1250139f7f9bSDimitry Andric // Collect the set of all of the modules we want to visit to emit link 1251139f7f9bSDimitry Andric // options, which is essentially the imported modules and all of their 1252139f7f9bSDimitry Andric // non-explicit child modules. 1253139f7f9bSDimitry Andric llvm::SetVector<clang::Module *> LinkModules; 1254139f7f9bSDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 1255139f7f9bSDimitry Andric SmallVector<clang::Module *, 16> Stack; 1256139f7f9bSDimitry Andric 1257139f7f9bSDimitry Andric // Seed the stack with imported modules. 1258f1a29dd3SDimitry Andric for (Module *M : ImportedModules) { 1259f1a29dd3SDimitry Andric // Do not add any link flags when an implementation TU of a module imports 1260f1a29dd3SDimitry Andric // a header of that same module. 1261f1a29dd3SDimitry Andric if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 1262f1a29dd3SDimitry Andric !getLangOpts().isCompilingModule()) 1263f1a29dd3SDimitry Andric continue; 12648f0fd8f6SDimitry Andric if (Visited.insert(M).second) 12658f0fd8f6SDimitry Andric Stack.push_back(M); 1266f1a29dd3SDimitry Andric } 1267139f7f9bSDimitry Andric 1268139f7f9bSDimitry Andric // Find all of the modules to import, making a little effort to prune 1269139f7f9bSDimitry Andric // non-leaf modules. 1270139f7f9bSDimitry Andric while (!Stack.empty()) { 1271f785676fSDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 1272139f7f9bSDimitry Andric 1273139f7f9bSDimitry Andric bool AnyChildren = false; 1274139f7f9bSDimitry Andric 1275139f7f9bSDimitry Andric // Visit the submodules of this module. 1276139f7f9bSDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 1277139f7f9bSDimitry Andric SubEnd = Mod->submodule_end(); 1278139f7f9bSDimitry Andric Sub != SubEnd; ++Sub) { 1279139f7f9bSDimitry Andric // Skip explicit children; they need to be explicitly imported to be 1280139f7f9bSDimitry Andric // linked against. 1281139f7f9bSDimitry Andric if ((*Sub)->IsExplicit) 1282139f7f9bSDimitry Andric continue; 1283139f7f9bSDimitry Andric 128439d628a0SDimitry Andric if (Visited.insert(*Sub).second) { 1285139f7f9bSDimitry Andric Stack.push_back(*Sub); 1286139f7f9bSDimitry Andric AnyChildren = true; 1287139f7f9bSDimitry Andric } 1288139f7f9bSDimitry Andric } 1289139f7f9bSDimitry Andric 1290139f7f9bSDimitry Andric // We didn't find any children, so add this module to the list of 1291139f7f9bSDimitry Andric // modules to link against. 1292139f7f9bSDimitry Andric if (!AnyChildren) { 1293139f7f9bSDimitry Andric LinkModules.insert(Mod); 1294139f7f9bSDimitry Andric } 1295139f7f9bSDimitry Andric } 1296139f7f9bSDimitry Andric 1297139f7f9bSDimitry Andric // Add link options for all of the imported modules in reverse topological 1298f785676fSDimitry Andric // order. We don't do anything to try to order import link flags with respect 1299f785676fSDimitry Andric // to linker options inserted by things like #pragma comment(). 130039d628a0SDimitry Andric SmallVector<llvm::Metadata *, 16> MetadataArgs; 1301139f7f9bSDimitry Andric Visited.clear(); 13028f0fd8f6SDimitry Andric for (Module *M : LinkModules) 13038f0fd8f6SDimitry Andric if (Visited.insert(M).second) 13048f0fd8f6SDimitry Andric addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 1305139f7f9bSDimitry Andric std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 1306f785676fSDimitry Andric LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 1307139f7f9bSDimitry Andric 1308139f7f9bSDimitry Andric // Add the linker options metadata flag. 1309139f7f9bSDimitry Andric getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options", 1310f785676fSDimitry Andric llvm::MDNode::get(getLLVMContext(), 1311f785676fSDimitry Andric LinkerOptionsMetadata)); 1312139f7f9bSDimitry Andric } 1313139f7f9bSDimitry Andric 1314f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() { 1315f22ef01cSRoman Divacky // Emit code for any potentially referenced deferred decls. Since a 1316f22ef01cSRoman Divacky // previously unused static decl may become used during the generation of code 1317f22ef01cSRoman Divacky // for a static function, iterate until no changes are made. 1318f22ef01cSRoman Divacky 1319f22ef01cSRoman Divacky if (!DeferredVTables.empty()) { 1320139f7f9bSDimitry Andric EmitDeferredVTables(); 1321139f7f9bSDimitry Andric 1322e7145dcbSDimitry Andric // Emitting a vtable doesn't directly cause more vtables to 1323139f7f9bSDimitry Andric // become deferred, although it can cause functions to be 1324e7145dcbSDimitry Andric // emitted that then need those vtables. 1325139f7f9bSDimitry Andric assert(DeferredVTables.empty()); 1326f22ef01cSRoman Divacky } 1327f22ef01cSRoman Divacky 1328e7145dcbSDimitry Andric // Stop if we're out of both deferred vtables and deferred declarations. 132933956c43SDimitry Andric if (DeferredDeclsToEmit.empty()) 133033956c43SDimitry Andric return; 1331139f7f9bSDimitry Andric 133233956c43SDimitry Andric // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 133333956c43SDimitry Andric // work, it will not interfere with this. 1334f37b6182SDimitry Andric std::vector<GlobalDecl> CurDeclsToEmit; 133533956c43SDimitry Andric CurDeclsToEmit.swap(DeferredDeclsToEmit); 133633956c43SDimitry Andric 1337f37b6182SDimitry Andric for (GlobalDecl &D : CurDeclsToEmit) { 13380623d748SDimitry Andric // We should call GetAddrOfGlobal with IsForDefinition set to true in order 13390623d748SDimitry Andric // to get GlobalValue with exactly the type we need, not something that 13400623d748SDimitry Andric // might had been created for another decl with the same mangled name but 13410623d748SDimitry Andric // different type. 1342e7145dcbSDimitry Andric llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 134344290647SDimitry Andric GetAddrOfGlobal(D, ForDefinition)); 1344e7145dcbSDimitry Andric 1345e7145dcbSDimitry Andric // In case of different address spaces, we may still get a cast, even with 1346e7145dcbSDimitry Andric // IsForDefinition equal to true. Query mangled names table to get 1347e7145dcbSDimitry Andric // GlobalValue. 134839d628a0SDimitry Andric if (!GV) 134939d628a0SDimitry Andric GV = GetGlobalValue(getMangledName(D)); 135039d628a0SDimitry Andric 1351e7145dcbSDimitry Andric // Make sure GetGlobalValue returned non-null. 1352e7145dcbSDimitry Andric assert(GV); 1353e7145dcbSDimitry Andric 1354f22ef01cSRoman Divacky // Check to see if we've already emitted this. This is necessary 1355f22ef01cSRoman Divacky // for a couple of reasons: first, decls can end up in the 1356f22ef01cSRoman Divacky // deferred-decls queue multiple times, and second, decls can end 1357f22ef01cSRoman Divacky // up with definitions in unusual ways (e.g. by an extern inline 1358f22ef01cSRoman Divacky // function acquiring a strong function redefinition). Just 1359f22ef01cSRoman Divacky // ignore these cases. 1360e7145dcbSDimitry Andric if (!GV->isDeclaration()) 1361f22ef01cSRoman Divacky continue; 1362f22ef01cSRoman Divacky 1363f22ef01cSRoman Divacky // Otherwise, emit the definition and move on to the next one. 136459d1ed5bSDimitry Andric EmitGlobalDefinition(D, GV); 136533956c43SDimitry Andric 136633956c43SDimitry Andric // If we found out that we need to emit more decls, do that recursively. 136733956c43SDimitry Andric // This has the advantage that the decls are emitted in a DFS and related 136833956c43SDimitry Andric // ones are close together, which is convenient for testing. 136933956c43SDimitry Andric if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 137033956c43SDimitry Andric EmitDeferred(); 137133956c43SDimitry Andric assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 137233956c43SDimitry Andric } 1373f22ef01cSRoman Divacky } 1374f22ef01cSRoman Divacky } 1375f22ef01cSRoman Divacky 13766122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() { 13776122f3e6SDimitry Andric if (Annotations.empty()) 13786122f3e6SDimitry Andric return; 13796122f3e6SDimitry Andric 13806122f3e6SDimitry Andric // Create a new global variable for the ConstantStruct in the Module. 13816122f3e6SDimitry Andric llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 13826122f3e6SDimitry Andric Annotations[0]->getType(), Annotations.size()), Annotations); 138359d1ed5bSDimitry Andric auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 138459d1ed5bSDimitry Andric llvm::GlobalValue::AppendingLinkage, 138559d1ed5bSDimitry Andric Array, "llvm.global.annotations"); 13866122f3e6SDimitry Andric gv->setSection(AnnotationSection); 13876122f3e6SDimitry Andric } 13886122f3e6SDimitry Andric 1389139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1390f785676fSDimitry Andric llvm::Constant *&AStr = AnnotationStrings[Str]; 1391f785676fSDimitry Andric if (AStr) 1392f785676fSDimitry Andric return AStr; 13936122f3e6SDimitry Andric 13946122f3e6SDimitry Andric // Not found yet, create a new global. 1395dff0c46cSDimitry Andric llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 139659d1ed5bSDimitry Andric auto *gv = 139759d1ed5bSDimitry Andric new llvm::GlobalVariable(getModule(), s->getType(), true, 139859d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, s, ".str"); 13996122f3e6SDimitry Andric gv->setSection(AnnotationSection); 1400e7145dcbSDimitry Andric gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1401f785676fSDimitry Andric AStr = gv; 14026122f3e6SDimitry Andric return gv; 14036122f3e6SDimitry Andric } 14046122f3e6SDimitry Andric 14056122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 14066122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 14076122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(Loc); 14086122f3e6SDimitry Andric if (PLoc.isValid()) 14096122f3e6SDimitry Andric return EmitAnnotationString(PLoc.getFilename()); 14106122f3e6SDimitry Andric return EmitAnnotationString(SM.getBufferName(Loc)); 14116122f3e6SDimitry Andric } 14126122f3e6SDimitry Andric 14136122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 14146122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 14156122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(L); 14166122f3e6SDimitry Andric unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 14176122f3e6SDimitry Andric SM.getExpansionLineNumber(L); 14186122f3e6SDimitry Andric return llvm::ConstantInt::get(Int32Ty, LineNo); 14196122f3e6SDimitry Andric } 14206122f3e6SDimitry Andric 1421f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1422f22ef01cSRoman Divacky const AnnotateAttr *AA, 14236122f3e6SDimitry Andric SourceLocation L) { 14246122f3e6SDimitry Andric // Get the globals for file name, annotation, and the line number. 14256122f3e6SDimitry Andric llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 14266122f3e6SDimitry Andric *UnitGV = EmitAnnotationUnit(L), 14276122f3e6SDimitry Andric *LineNoCst = EmitAnnotationLineNo(L); 1428f22ef01cSRoman Divacky 1429f22ef01cSRoman Divacky // Create the ConstantStruct for the global annotation. 1430f22ef01cSRoman Divacky llvm::Constant *Fields[4] = { 14316122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 14326122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 14336122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 14346122f3e6SDimitry Andric LineNoCst 1435f22ef01cSRoman Divacky }; 143617a519f9SDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 1437f22ef01cSRoman Divacky } 1438f22ef01cSRoman Divacky 14396122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 14406122f3e6SDimitry Andric llvm::GlobalValue *GV) { 14416122f3e6SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 14426122f3e6SDimitry Andric // Get the struct elements for these annotations. 144359d1ed5bSDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 144459d1ed5bSDimitry Andric Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 14456122f3e6SDimitry Andric } 14466122f3e6SDimitry Andric 144739d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn, 144839d628a0SDimitry Andric SourceLocation Loc) const { 144939d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 145039d628a0SDimitry Andric // Blacklist by function name. 145139d628a0SDimitry Andric if (SanitizerBL.isBlacklistedFunction(Fn->getName())) 145239d628a0SDimitry Andric return true; 145339d628a0SDimitry Andric // Blacklist by location. 14540623d748SDimitry Andric if (Loc.isValid()) 145539d628a0SDimitry Andric return SanitizerBL.isBlacklistedLocation(Loc); 145639d628a0SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 145739d628a0SDimitry Andric // it's located in the main file. 145839d628a0SDimitry Andric auto &SM = Context.getSourceManager(); 145939d628a0SDimitry Andric if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 146039d628a0SDimitry Andric return SanitizerBL.isBlacklistedFile(MainFile->getName()); 146139d628a0SDimitry Andric } 146239d628a0SDimitry Andric return false; 146339d628a0SDimitry Andric } 146439d628a0SDimitry Andric 146539d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 146639d628a0SDimitry Andric SourceLocation Loc, QualType Ty, 146739d628a0SDimitry Andric StringRef Category) const { 14688f0fd8f6SDimitry Andric // For now globals can be blacklisted only in ASan and KASan. 14698f0fd8f6SDimitry Andric if (!LangOpts.Sanitize.hasOneOf( 14708f0fd8f6SDimitry Andric SanitizerKind::Address | SanitizerKind::KernelAddress)) 147139d628a0SDimitry Andric return false; 147239d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 147339d628a0SDimitry Andric if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category)) 147439d628a0SDimitry Andric return true; 147539d628a0SDimitry Andric if (SanitizerBL.isBlacklistedLocation(Loc, Category)) 147639d628a0SDimitry Andric return true; 147739d628a0SDimitry Andric // Check global type. 147839d628a0SDimitry Andric if (!Ty.isNull()) { 147939d628a0SDimitry Andric // Drill down the array types: if global variable of a fixed type is 148039d628a0SDimitry Andric // blacklisted, we also don't instrument arrays of them. 148139d628a0SDimitry Andric while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 148239d628a0SDimitry Andric Ty = AT->getElementType(); 148339d628a0SDimitry Andric Ty = Ty.getCanonicalType().getUnqualifiedType(); 148439d628a0SDimitry Andric // We allow to blacklist only record types (classes, structs etc.) 148539d628a0SDimitry Andric if (Ty->isRecordType()) { 148639d628a0SDimitry Andric std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 148739d628a0SDimitry Andric if (SanitizerBL.isBlacklistedType(TypeStr, Category)) 148839d628a0SDimitry Andric return true; 148939d628a0SDimitry Andric } 149039d628a0SDimitry Andric } 149139d628a0SDimitry Andric return false; 149239d628a0SDimitry Andric } 149339d628a0SDimitry Andric 149420e90f04SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 149520e90f04SDimitry Andric StringRef Category) const { 149620e90f04SDimitry Andric if (!LangOpts.XRayInstrument) 149720e90f04SDimitry Andric return false; 149820e90f04SDimitry Andric const auto &XRayFilter = getContext().getXRayFilter(); 149920e90f04SDimitry Andric using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 150020e90f04SDimitry Andric auto Attr = XRayFunctionFilter::ImbueAttribute::NONE; 150120e90f04SDimitry Andric if (Loc.isValid()) 150220e90f04SDimitry Andric Attr = XRayFilter.shouldImbueLocation(Loc, Category); 150320e90f04SDimitry Andric if (Attr == ImbueAttr::NONE) 150420e90f04SDimitry Andric Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 150520e90f04SDimitry Andric switch (Attr) { 150620e90f04SDimitry Andric case ImbueAttr::NONE: 150720e90f04SDimitry Andric return false; 150820e90f04SDimitry Andric case ImbueAttr::ALWAYS: 150920e90f04SDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 151020e90f04SDimitry Andric break; 151120e90f04SDimitry Andric case ImbueAttr::NEVER: 151220e90f04SDimitry Andric Fn->addFnAttr("function-instrument", "xray-never"); 151320e90f04SDimitry Andric break; 151420e90f04SDimitry Andric } 151520e90f04SDimitry Andric return true; 151620e90f04SDimitry Andric } 151720e90f04SDimitry Andric 151839d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 1519e580952dSDimitry Andric // Never defer when EmitAllDecls is specified. 1520dff0c46cSDimitry Andric if (LangOpts.EmitAllDecls) 152139d628a0SDimitry Andric return true; 152239d628a0SDimitry Andric 152339d628a0SDimitry Andric return getContext().DeclMustBeEmitted(Global); 152439d628a0SDimitry Andric } 152539d628a0SDimitry Andric 152639d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 152739d628a0SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) 152839d628a0SDimitry Andric if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 152939d628a0SDimitry Andric // Implicit template instantiations may change linkage if they are later 153039d628a0SDimitry Andric // explicitly instantiated, so they should not be emitted eagerly. 1531f22ef01cSRoman Divacky return false; 1532e7145dcbSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(Global)) 1533e7145dcbSDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 1534e7145dcbSDimitry Andric ASTContext::InlineVariableDefinitionKind::WeakUnknown) 1535e7145dcbSDimitry Andric // A definition of an inline constexpr static data member may change 1536e7145dcbSDimitry Andric // linkage later if it's redeclared outside the class. 1537e7145dcbSDimitry Andric return false; 1538875ed548SDimitry Andric // If OpenMP is enabled and threadprivates must be generated like TLS, delay 1539875ed548SDimitry Andric // codegen for global variables, because they may be marked as threadprivate. 1540875ed548SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 1541875ed548SDimitry Andric getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global)) 1542875ed548SDimitry Andric return false; 1543f22ef01cSRoman Divacky 154439d628a0SDimitry Andric return true; 1545f22ef01cSRoman Divacky } 1546f22ef01cSRoman Divacky 15470623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor( 15483861d79fSDimitry Andric const CXXUuidofExpr* E) { 15493861d79fSDimitry Andric // Sema has verified that IIDSource has a __declspec(uuid()), and that its 15503861d79fSDimitry Andric // well-formed. 1551e7145dcbSDimitry Andric StringRef Uuid = E->getUuidStr(); 1552f785676fSDimitry Andric std::string Name = "_GUID_" + Uuid.lower(); 1553f785676fSDimitry Andric std::replace(Name.begin(), Name.end(), '-', '_'); 15543861d79fSDimitry Andric 1555e7145dcbSDimitry Andric // The UUID descriptor should be pointer aligned. 1556e7145dcbSDimitry Andric CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 15570623d748SDimitry Andric 15583861d79fSDimitry Andric // Look for an existing global. 15593861d79fSDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 15600623d748SDimitry Andric return ConstantAddress(GV, Alignment); 15613861d79fSDimitry Andric 156239d628a0SDimitry Andric llvm::Constant *Init = EmitUuidofInitializer(Uuid); 15633861d79fSDimitry Andric assert(Init && "failed to initialize as constant"); 15643861d79fSDimitry Andric 156559d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 1566f785676fSDimitry Andric getModule(), Init->getType(), 1567f785676fSDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 156833956c43SDimitry Andric if (supportsCOMDAT()) 156933956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 15700623d748SDimitry Andric return ConstantAddress(GV, Alignment); 15713861d79fSDimitry Andric } 15723861d79fSDimitry Andric 15730623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1574f22ef01cSRoman Divacky const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1575f22ef01cSRoman Divacky assert(AA && "No alias?"); 1576f22ef01cSRoman Divacky 15770623d748SDimitry Andric CharUnits Alignment = getContext().getDeclAlign(VD); 15786122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1579f22ef01cSRoman Divacky 1580f22ef01cSRoman Divacky // See if there is already something with the target's name in the module. 1581f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 15823861d79fSDimitry Andric if (Entry) { 15833861d79fSDimitry Andric unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 15840623d748SDimitry Andric auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 15850623d748SDimitry Andric return ConstantAddress(Ptr, Alignment); 15863861d79fSDimitry Andric } 1587f22ef01cSRoman Divacky 1588f22ef01cSRoman Divacky llvm::Constant *Aliasee; 1589f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 15903861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 15913861d79fSDimitry Andric GlobalDecl(cast<FunctionDecl>(VD)), 15922754fe60SDimitry Andric /*ForVTable=*/false); 1593f22ef01cSRoman Divacky else 1594f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 159559d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 159659d1ed5bSDimitry Andric nullptr); 15973861d79fSDimitry Andric 159859d1ed5bSDimitry Andric auto *F = cast<llvm::GlobalValue>(Aliasee); 1599f22ef01cSRoman Divacky F->setLinkage(llvm::Function::ExternalWeakLinkage); 1600f22ef01cSRoman Divacky WeakRefReferences.insert(F); 1601f22ef01cSRoman Divacky 16020623d748SDimitry Andric return ConstantAddress(Aliasee, Alignment); 1603f22ef01cSRoman Divacky } 1604f22ef01cSRoman Divacky 1605f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) { 160659d1ed5bSDimitry Andric const auto *Global = cast<ValueDecl>(GD.getDecl()); 1607f22ef01cSRoman Divacky 1608f22ef01cSRoman Divacky // Weak references don't produce any output by themselves. 1609f22ef01cSRoman Divacky if (Global->hasAttr<WeakRefAttr>()) 1610f22ef01cSRoman Divacky return; 1611f22ef01cSRoman Divacky 1612f22ef01cSRoman Divacky // If this is an alias definition (which otherwise looks like a declaration) 1613f22ef01cSRoman Divacky // emit it now. 1614f22ef01cSRoman Divacky if (Global->hasAttr<AliasAttr>()) 1615f22ef01cSRoman Divacky return EmitAliasDefinition(GD); 1616f22ef01cSRoman Divacky 1617e7145dcbSDimitry Andric // IFunc like an alias whose value is resolved at runtime by calling resolver. 1618e7145dcbSDimitry Andric if (Global->hasAttr<IFuncAttr>()) 1619e7145dcbSDimitry Andric return emitIFuncDefinition(GD); 1620e7145dcbSDimitry Andric 16216122f3e6SDimitry Andric // If this is CUDA, be selective about which declarations we emit. 1622dff0c46cSDimitry Andric if (LangOpts.CUDA) { 162333956c43SDimitry Andric if (LangOpts.CUDAIsDevice) { 16246122f3e6SDimitry Andric if (!Global->hasAttr<CUDADeviceAttr>() && 16256122f3e6SDimitry Andric !Global->hasAttr<CUDAGlobalAttr>() && 16266122f3e6SDimitry Andric !Global->hasAttr<CUDAConstantAttr>() && 16276122f3e6SDimitry Andric !Global->hasAttr<CUDASharedAttr>()) 16286122f3e6SDimitry Andric return; 16296122f3e6SDimitry Andric } else { 1630e7145dcbSDimitry Andric // We need to emit host-side 'shadows' for all global 1631e7145dcbSDimitry Andric // device-side variables because the CUDA runtime needs their 1632e7145dcbSDimitry Andric // size and host-side address in order to provide access to 1633e7145dcbSDimitry Andric // their device-side incarnations. 1634e7145dcbSDimitry Andric 1635e7145dcbSDimitry Andric // So device-only functions are the only things we skip. 1636e7145dcbSDimitry Andric if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 1637e7145dcbSDimitry Andric Global->hasAttr<CUDADeviceAttr>()) 16386122f3e6SDimitry Andric return; 1639e7145dcbSDimitry Andric 1640e7145dcbSDimitry Andric assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 1641e7145dcbSDimitry Andric "Expected Variable or Function"); 1642e580952dSDimitry Andric } 1643e580952dSDimitry Andric } 1644e580952dSDimitry Andric 1645e7145dcbSDimitry Andric if (LangOpts.OpenMP) { 1646ea942507SDimitry Andric // If this is OpenMP device, check if it is legal to emit this global 1647ea942507SDimitry Andric // normally. 1648ea942507SDimitry Andric if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 1649ea942507SDimitry Andric return; 1650e7145dcbSDimitry Andric if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 1651e7145dcbSDimitry Andric if (MustBeEmitted(Global)) 1652e7145dcbSDimitry Andric EmitOMPDeclareReduction(DRD); 1653e7145dcbSDimitry Andric return; 1654e7145dcbSDimitry Andric } 1655e7145dcbSDimitry Andric } 1656ea942507SDimitry Andric 16576122f3e6SDimitry Andric // Ignore declarations, they will be emitted on their first use. 165859d1ed5bSDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 1659f22ef01cSRoman Divacky // Forward declarations are emitted lazily on first use. 16606122f3e6SDimitry Andric if (!FD->doesThisDeclarationHaveABody()) { 16616122f3e6SDimitry Andric if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1662f22ef01cSRoman Divacky return; 16636122f3e6SDimitry Andric 16646122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 166559d1ed5bSDimitry Andric 166659d1ed5bSDimitry Andric // Compute the function info and LLVM type. 166759d1ed5bSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 166859d1ed5bSDimitry Andric llvm::Type *Ty = getTypes().GetFunctionType(FI); 166959d1ed5bSDimitry Andric 167059d1ed5bSDimitry Andric GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 167159d1ed5bSDimitry Andric /*DontDefer=*/false); 16726122f3e6SDimitry Andric return; 16736122f3e6SDimitry Andric } 1674f22ef01cSRoman Divacky } else { 167559d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(Global); 1676f22ef01cSRoman Divacky assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1677e7145dcbSDimitry Andric // We need to emit device-side global CUDA variables even if a 1678e7145dcbSDimitry Andric // variable does not have a definition -- we still need to define 1679e7145dcbSDimitry Andric // host-side shadow for it. 1680e7145dcbSDimitry Andric bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice && 1681e7145dcbSDimitry Andric !VD->hasDefinition() && 1682e7145dcbSDimitry Andric (VD->hasAttr<CUDAConstantAttr>() || 1683e7145dcbSDimitry Andric VD->hasAttr<CUDADeviceAttr>()); 1684e7145dcbSDimitry Andric if (!MustEmitForCuda && 1685e7145dcbSDimitry Andric VD->isThisDeclarationADefinition() != VarDecl::Definition && 1686e7145dcbSDimitry Andric !Context.isMSStaticDataMemberInlineDefinition(VD)) { 1687e7145dcbSDimitry Andric // If this declaration may have caused an inline variable definition to 1688e7145dcbSDimitry Andric // change linkage, make sure that it's emitted. 1689e7145dcbSDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 1690e7145dcbSDimitry Andric ASTContext::InlineVariableDefinitionKind::Strong) 1691e7145dcbSDimitry Andric GetAddrOfGlobalVar(VD); 1692f22ef01cSRoman Divacky return; 1693f22ef01cSRoman Divacky } 1694e7145dcbSDimitry Andric } 1695f22ef01cSRoman Divacky 169639d628a0SDimitry Andric // Defer code generation to first use when possible, e.g. if this is an inline 169739d628a0SDimitry Andric // function. If the global must always be emitted, do it eagerly if possible 169839d628a0SDimitry Andric // to benefit from cache locality. 169939d628a0SDimitry Andric if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 1700f22ef01cSRoman Divacky // Emit the definition if it can't be deferred. 1701f22ef01cSRoman Divacky EmitGlobalDefinition(GD); 1702f22ef01cSRoman Divacky return; 1703f22ef01cSRoman Divacky } 1704f22ef01cSRoman Divacky 1705e580952dSDimitry Andric // If we're deferring emission of a C++ variable with an 1706e580952dSDimitry Andric // initializer, remember the order in which it appeared in the file. 1707dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1708e580952dSDimitry Andric cast<VarDecl>(Global)->hasInit()) { 1709e580952dSDimitry Andric DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 171059d1ed5bSDimitry Andric CXXGlobalInits.push_back(nullptr); 1711e580952dSDimitry Andric } 1712e580952dSDimitry Andric 17136122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 1714f37b6182SDimitry Andric if (GetGlobalValue(MangledName) != nullptr) { 171539d628a0SDimitry Andric // The value has already been used and should therefore be emitted. 1716f37b6182SDimitry Andric addDeferredDeclToEmit(GD); 171739d628a0SDimitry Andric } else if (MustBeEmitted(Global)) { 171839d628a0SDimitry Andric // The value must be emitted, but cannot be emitted eagerly. 171939d628a0SDimitry Andric assert(!MayBeEmittedEagerly(Global)); 1720f37b6182SDimitry Andric addDeferredDeclToEmit(GD); 172139d628a0SDimitry Andric } else { 1722f22ef01cSRoman Divacky // Otherwise, remember that we saw a deferred decl with this name. The 1723f22ef01cSRoman Divacky // first use of the mangled name will cause it to move into 1724f22ef01cSRoman Divacky // DeferredDeclsToEmit. 1725f22ef01cSRoman Divacky DeferredDecls[MangledName] = GD; 1726f22ef01cSRoman Divacky } 1727f22ef01cSRoman Divacky } 1728f22ef01cSRoman Divacky 172920e90f04SDimitry Andric // Check if T is a class type with a destructor that's not dllimport. 173020e90f04SDimitry Andric static bool HasNonDllImportDtor(QualType T) { 173120e90f04SDimitry Andric if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 173220e90f04SDimitry Andric if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 173320e90f04SDimitry Andric if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 173420e90f04SDimitry Andric return true; 173520e90f04SDimitry Andric 173620e90f04SDimitry Andric return false; 173720e90f04SDimitry Andric } 173820e90f04SDimitry Andric 1739f8254f43SDimitry Andric namespace { 1740f8254f43SDimitry Andric struct FunctionIsDirectlyRecursive : 1741f8254f43SDimitry Andric public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1742f8254f43SDimitry Andric const StringRef Name; 1743dff0c46cSDimitry Andric const Builtin::Context &BI; 1744f8254f43SDimitry Andric bool Result; 1745dff0c46cSDimitry Andric FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1746dff0c46cSDimitry Andric Name(N), BI(C), Result(false) { 1747f8254f43SDimitry Andric } 1748f8254f43SDimitry Andric typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1749f8254f43SDimitry Andric 1750f8254f43SDimitry Andric bool TraverseCallExpr(CallExpr *E) { 1751dff0c46cSDimitry Andric const FunctionDecl *FD = E->getDirectCallee(); 1752dff0c46cSDimitry Andric if (!FD) 1753f8254f43SDimitry Andric return true; 1754dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1755dff0c46cSDimitry Andric if (Attr && Name == Attr->getLabel()) { 1756dff0c46cSDimitry Andric Result = true; 1757dff0c46cSDimitry Andric return false; 1758dff0c46cSDimitry Andric } 1759dff0c46cSDimitry Andric unsigned BuiltinID = FD->getBuiltinID(); 17603dac3a9bSDimitry Andric if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 1761f8254f43SDimitry Andric return true; 17620623d748SDimitry Andric StringRef BuiltinName = BI.getName(BuiltinID); 1763dff0c46cSDimitry Andric if (BuiltinName.startswith("__builtin_") && 1764dff0c46cSDimitry Andric Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1765f8254f43SDimitry Andric Result = true; 1766f8254f43SDimitry Andric return false; 1767f8254f43SDimitry Andric } 1768f8254f43SDimitry Andric return true; 1769f8254f43SDimitry Andric } 1770f8254f43SDimitry Andric }; 17710623d748SDimitry Andric 177220e90f04SDimitry Andric // Make sure we're not referencing non-imported vars or functions. 17730623d748SDimitry Andric struct DLLImportFunctionVisitor 17740623d748SDimitry Andric : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 17750623d748SDimitry Andric bool SafeToInline = true; 17760623d748SDimitry Andric 177744290647SDimitry Andric bool shouldVisitImplicitCode() const { return true; } 177844290647SDimitry Andric 17790623d748SDimitry Andric bool VisitVarDecl(VarDecl *VD) { 178020e90f04SDimitry Andric if (VD->getTLSKind()) { 17810623d748SDimitry Andric // A thread-local variable cannot be imported. 178220e90f04SDimitry Andric SafeToInline = false; 17830623d748SDimitry Andric return SafeToInline; 17840623d748SDimitry Andric } 17850623d748SDimitry Andric 178620e90f04SDimitry Andric // A variable definition might imply a destructor call. 178720e90f04SDimitry Andric if (VD->isThisDeclarationADefinition()) 178820e90f04SDimitry Andric SafeToInline = !HasNonDllImportDtor(VD->getType()); 178920e90f04SDimitry Andric 179020e90f04SDimitry Andric return SafeToInline; 179120e90f04SDimitry Andric } 179220e90f04SDimitry Andric 179320e90f04SDimitry Andric bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 179420e90f04SDimitry Andric if (const auto *D = E->getTemporary()->getDestructor()) 179520e90f04SDimitry Andric SafeToInline = D->hasAttr<DLLImportAttr>(); 179620e90f04SDimitry Andric return SafeToInline; 179720e90f04SDimitry Andric } 179820e90f04SDimitry Andric 17990623d748SDimitry Andric bool VisitDeclRefExpr(DeclRefExpr *E) { 18000623d748SDimitry Andric ValueDecl *VD = E->getDecl(); 18010623d748SDimitry Andric if (isa<FunctionDecl>(VD)) 18020623d748SDimitry Andric SafeToInline = VD->hasAttr<DLLImportAttr>(); 18030623d748SDimitry Andric else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 18040623d748SDimitry Andric SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 18050623d748SDimitry Andric return SafeToInline; 18060623d748SDimitry Andric } 180720e90f04SDimitry Andric 180844290647SDimitry Andric bool VisitCXXConstructExpr(CXXConstructExpr *E) { 180944290647SDimitry Andric SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 181044290647SDimitry Andric return SafeToInline; 181144290647SDimitry Andric } 181220e90f04SDimitry Andric 181320e90f04SDimitry Andric bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 181420e90f04SDimitry Andric CXXMethodDecl *M = E->getMethodDecl(); 181520e90f04SDimitry Andric if (!M) { 181620e90f04SDimitry Andric // Call through a pointer to member function. This is safe to inline. 181720e90f04SDimitry Andric SafeToInline = true; 181820e90f04SDimitry Andric } else { 181920e90f04SDimitry Andric SafeToInline = M->hasAttr<DLLImportAttr>(); 182020e90f04SDimitry Andric } 182120e90f04SDimitry Andric return SafeToInline; 182220e90f04SDimitry Andric } 182320e90f04SDimitry Andric 18240623d748SDimitry Andric bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 18250623d748SDimitry Andric SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 18260623d748SDimitry Andric return SafeToInline; 18270623d748SDimitry Andric } 182820e90f04SDimitry Andric 18290623d748SDimitry Andric bool VisitCXXNewExpr(CXXNewExpr *E) { 18300623d748SDimitry Andric SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 18310623d748SDimitry Andric return SafeToInline; 18320623d748SDimitry Andric } 18330623d748SDimitry Andric }; 1834f8254f43SDimitry Andric } 1835f8254f43SDimitry Andric 1836dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another 1837dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin, 1838dff0c46cSDimitry Andric // ends up pointing to itself. 1839f8254f43SDimitry Andric bool 1840dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1841dff0c46cSDimitry Andric StringRef Name; 1842dff0c46cSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1843dff0c46cSDimitry Andric // asm labels are a special kind of mangling we have to support. 1844dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1845dff0c46cSDimitry Andric if (!Attr) 1846f8254f43SDimitry Andric return false; 1847dff0c46cSDimitry Andric Name = Attr->getLabel(); 1848dff0c46cSDimitry Andric } else { 1849dff0c46cSDimitry Andric Name = FD->getName(); 1850dff0c46cSDimitry Andric } 1851f8254f43SDimitry Andric 1852dff0c46cSDimitry Andric FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1853dff0c46cSDimitry Andric Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1854f8254f43SDimitry Andric return Walker.Result; 1855f8254f43SDimitry Andric } 1856f8254f43SDimitry Andric 185744290647SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1858f785676fSDimitry Andric if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1859f8254f43SDimitry Andric return true; 186059d1ed5bSDimitry Andric const auto *F = cast<FunctionDecl>(GD.getDecl()); 186159d1ed5bSDimitry Andric if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1862f8254f43SDimitry Andric return false; 18630623d748SDimitry Andric 18640623d748SDimitry Andric if (F->hasAttr<DLLImportAttr>()) { 18650623d748SDimitry Andric // Check whether it would be safe to inline this dllimport function. 18660623d748SDimitry Andric DLLImportFunctionVisitor Visitor; 18670623d748SDimitry Andric Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 18680623d748SDimitry Andric if (!Visitor.SafeToInline) 18690623d748SDimitry Andric return false; 187044290647SDimitry Andric 187144290647SDimitry Andric if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 187244290647SDimitry Andric // Implicit destructor invocations aren't captured in the AST, so the 187344290647SDimitry Andric // check above can't see them. Check for them manually here. 187444290647SDimitry Andric for (const Decl *Member : Dtor->getParent()->decls()) 187544290647SDimitry Andric if (isa<FieldDecl>(Member)) 187644290647SDimitry Andric if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 187744290647SDimitry Andric return false; 187844290647SDimitry Andric for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 187944290647SDimitry Andric if (HasNonDllImportDtor(B.getType())) 188044290647SDimitry Andric return false; 188144290647SDimitry Andric } 18820623d748SDimitry Andric } 18830623d748SDimitry Andric 1884f8254f43SDimitry Andric // PR9614. Avoid cases where the source code is lying to us. An available 1885f8254f43SDimitry Andric // externally function should have an equivalent function somewhere else, 1886f8254f43SDimitry Andric // but a function that calls itself is clearly not equivalent to the real 1887f8254f43SDimitry Andric // implementation. 1888f8254f43SDimitry Andric // This happens in glibc's btowc and in some configure checks. 1889dff0c46cSDimitry Andric return !isTriviallyRecursive(F); 1890f8254f43SDimitry Andric } 1891f8254f43SDimitry Andric 189259d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 189359d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 1894f22ef01cSRoman Divacky 1895f22ef01cSRoman Divacky PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1896f22ef01cSRoman Divacky Context.getSourceManager(), 1897f22ef01cSRoman Divacky "Generating code for declaration"); 1898f22ef01cSRoman Divacky 1899f785676fSDimitry Andric if (isa<FunctionDecl>(D)) { 1900ffd1746dSEd Schouten // At -O0, don't generate IR for functions with available_externally 1901ffd1746dSEd Schouten // linkage. 1902f785676fSDimitry Andric if (!shouldEmitFunction(GD)) 1903ffd1746dSEd Schouten return; 1904ffd1746dSEd Schouten 190559d1ed5bSDimitry Andric if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 1906bd5abe19SDimitry Andric // Make sure to emit the definition(s) before we emit the thunks. 1907bd5abe19SDimitry Andric // This is necessary for the generation of certain thunks. 190859d1ed5bSDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 190939d628a0SDimitry Andric ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); 191059d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 191139d628a0SDimitry Andric ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); 1912bd5abe19SDimitry Andric else 191359d1ed5bSDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 1914bd5abe19SDimitry Andric 1915f22ef01cSRoman Divacky if (Method->isVirtual()) 1916f22ef01cSRoman Divacky getVTables().EmitThunks(GD); 1917f22ef01cSRoman Divacky 1918bd5abe19SDimitry Andric return; 1919ffd1746dSEd Schouten } 1920f22ef01cSRoman Divacky 192159d1ed5bSDimitry Andric return EmitGlobalFunctionDefinition(GD, GV); 1922ffd1746dSEd Schouten } 1923f22ef01cSRoman Divacky 192459d1ed5bSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 1925e7145dcbSDimitry Andric return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 1926f22ef01cSRoman Divacky 19276122f3e6SDimitry Andric llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1928f22ef01cSRoman Divacky } 1929f22ef01cSRoman Divacky 19300623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 19310623d748SDimitry Andric llvm::Function *NewFn); 19320623d748SDimitry Andric 1933f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1934f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there 1935f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 1936f22ef01cSRoman Divacky /// bitcasted to the right type. 1937f22ef01cSRoman Divacky /// 1938f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 1939f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created. 194020e90f04SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 194120e90f04SDimitry Andric StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 194220e90f04SDimitry Andric bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 194344290647SDimitry Andric ForDefinition_t IsForDefinition) { 1944f785676fSDimitry Andric const Decl *D = GD.getDecl(); 1945f785676fSDimitry Andric 1946f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 1947f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1948f22ef01cSRoman Divacky if (Entry) { 19493861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 1950f785676fSDimitry Andric const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 1951f22ef01cSRoman Divacky if (FD && !FD->hasAttr<WeakAttr>()) 1952f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 1953f22ef01cSRoman Divacky } 1954f22ef01cSRoman Divacky 195539d628a0SDimitry Andric // Handle dropped DLL attributes. 195639d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 195739d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 195839d628a0SDimitry Andric 19590623d748SDimitry Andric // If there are two attempts to define the same mangled name, issue an 19600623d748SDimitry Andric // error. 19610623d748SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 19620623d748SDimitry Andric GlobalDecl OtherGD; 1963e7145dcbSDimitry Andric // Check that GD is not yet in DiagnosedConflictingDefinitions is required 1964e7145dcbSDimitry Andric // to make sure that we issue an error only once. 19650623d748SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 19660623d748SDimitry Andric (GD.getCanonicalDecl().getDecl() != 19670623d748SDimitry Andric OtherGD.getCanonicalDecl().getDecl()) && 19680623d748SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 19690623d748SDimitry Andric getDiags().Report(D->getLocation(), 19700623d748SDimitry Andric diag::err_duplicate_mangled_name); 19710623d748SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 19720623d748SDimitry Andric diag::note_previous_definition); 19730623d748SDimitry Andric } 19740623d748SDimitry Andric } 19750623d748SDimitry Andric 19760623d748SDimitry Andric if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 19770623d748SDimitry Andric (Entry->getType()->getElementType() == Ty)) { 1978f22ef01cSRoman Divacky return Entry; 19790623d748SDimitry Andric } 1980f22ef01cSRoman Divacky 1981f22ef01cSRoman Divacky // Make sure the result is of the correct type. 19820623d748SDimitry Andric // (If function is requested for a definition, we always need to create a new 19830623d748SDimitry Andric // function, not just return a bitcast.) 19840623d748SDimitry Andric if (!IsForDefinition) 198517a519f9SDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1986f22ef01cSRoman Divacky } 1987f22ef01cSRoman Divacky 1988f22ef01cSRoman Divacky // This function doesn't have a complete type (for example, the return 1989f22ef01cSRoman Divacky // type is an incomplete struct). Use a fake type instead, and make 1990f22ef01cSRoman Divacky // sure not to try to set attributes. 1991f22ef01cSRoman Divacky bool IsIncompleteFunction = false; 1992f22ef01cSRoman Divacky 19936122f3e6SDimitry Andric llvm::FunctionType *FTy; 1994f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(Ty)) { 1995f22ef01cSRoman Divacky FTy = cast<llvm::FunctionType>(Ty); 1996f22ef01cSRoman Divacky } else { 1997bd5abe19SDimitry Andric FTy = llvm::FunctionType::get(VoidTy, false); 1998f22ef01cSRoman Divacky IsIncompleteFunction = true; 1999f22ef01cSRoman Divacky } 2000ffd1746dSEd Schouten 20010623d748SDimitry Andric llvm::Function *F = 20020623d748SDimitry Andric llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 20030623d748SDimitry Andric Entry ? StringRef() : MangledName, &getModule()); 20040623d748SDimitry Andric 20050623d748SDimitry Andric // If we already created a function with the same mangled name (but different 20060623d748SDimitry Andric // type) before, take its name and add it to the list of functions to be 20070623d748SDimitry Andric // replaced with F at the end of CodeGen. 20080623d748SDimitry Andric // 20090623d748SDimitry Andric // This happens if there is a prototype for a function (e.g. "int f()") and 20100623d748SDimitry Andric // then a definition of a different type (e.g. "int f(int x)"). 20110623d748SDimitry Andric if (Entry) { 20120623d748SDimitry Andric F->takeName(Entry); 20130623d748SDimitry Andric 20140623d748SDimitry Andric // This might be an implementation of a function without a prototype, in 20150623d748SDimitry Andric // which case, try to do special replacement of calls which match the new 20160623d748SDimitry Andric // prototype. The really key thing here is that we also potentially drop 20170623d748SDimitry Andric // arguments from the call site so as to make a direct call, which makes the 20180623d748SDimitry Andric // inliner happier and suppresses a number of optimizer warnings (!) about 20190623d748SDimitry Andric // dropping arguments. 20200623d748SDimitry Andric if (!Entry->use_empty()) { 20210623d748SDimitry Andric ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 20220623d748SDimitry Andric Entry->removeDeadConstantUsers(); 20230623d748SDimitry Andric } 20240623d748SDimitry Andric 20250623d748SDimitry Andric llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 20260623d748SDimitry Andric F, Entry->getType()->getElementType()->getPointerTo()); 20270623d748SDimitry Andric addGlobalValReplacement(Entry, BC); 20280623d748SDimitry Andric } 20290623d748SDimitry Andric 2030f22ef01cSRoman Divacky assert(F->getName() == MangledName && "name was uniqued!"); 2031f785676fSDimitry Andric if (D) 203239d628a0SDimitry Andric SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 203320e90f04SDimitry Andric if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) { 203420e90f04SDimitry Andric llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex); 2035f37b6182SDimitry Andric F->addAttributes(llvm::AttributeList::FunctionIndex, B); 2036139f7f9bSDimitry Andric } 2037f22ef01cSRoman Divacky 203859d1ed5bSDimitry Andric if (!DontDefer) { 203959d1ed5bSDimitry Andric // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 204059d1ed5bSDimitry Andric // each other bottoming out with the base dtor. Therefore we emit non-base 204159d1ed5bSDimitry Andric // dtors on usage, even if there is no dtor definition in the TU. 204259d1ed5bSDimitry Andric if (D && isa<CXXDestructorDecl>(D) && 204359d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 204459d1ed5bSDimitry Andric GD.getDtorType())) 2045f37b6182SDimitry Andric addDeferredDeclToEmit(GD); 204659d1ed5bSDimitry Andric 2047f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 2048f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 2049f22ef01cSRoman Divacky // of the file. 205059d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 2051f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 205259d1ed5bSDimitry Andric // Move the potentially referenced deferred decl to the 205359d1ed5bSDimitry Andric // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 205459d1ed5bSDimitry Andric // don't need it anymore). 2055f37b6182SDimitry Andric addDeferredDeclToEmit(DDI->second); 2056f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 20572754fe60SDimitry Andric 20582754fe60SDimitry Andric // Otherwise, there are cases we have to worry about where we're 20592754fe60SDimitry Andric // using a declaration for which we must emit a definition but where 20602754fe60SDimitry Andric // we might not find a top-level definition: 20612754fe60SDimitry Andric // - member functions defined inline in their classes 20622754fe60SDimitry Andric // - friend functions defined inline in some class 20632754fe60SDimitry Andric // - special member functions with implicit definitions 20642754fe60SDimitry Andric // If we ever change our AST traversal to walk into class methods, 20652754fe60SDimitry Andric // this will be unnecessary. 20662754fe60SDimitry Andric // 206759d1ed5bSDimitry Andric // We also don't emit a definition for a function if it's going to be an 206839d628a0SDimitry Andric // entry in a vtable, unless it's already marked as used. 2069f785676fSDimitry Andric } else if (getLangOpts().CPlusPlus && D) { 20702754fe60SDimitry Andric // Look for a declaration that's lexically in a record. 207139d628a0SDimitry Andric for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 207239d628a0SDimitry Andric FD = FD->getPreviousDecl()) { 20732754fe60SDimitry Andric if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 207439d628a0SDimitry Andric if (FD->doesThisDeclarationHaveABody()) { 2075f37b6182SDimitry Andric addDeferredDeclToEmit(GD.getWithDecl(FD)); 20762754fe60SDimitry Andric break; 2077f22ef01cSRoman Divacky } 2078f22ef01cSRoman Divacky } 207939d628a0SDimitry Andric } 2080f22ef01cSRoman Divacky } 208159d1ed5bSDimitry Andric } 2082f22ef01cSRoman Divacky 2083f22ef01cSRoman Divacky // Make sure the result is of the requested type. 2084f22ef01cSRoman Divacky if (!IsIncompleteFunction) { 2085f22ef01cSRoman Divacky assert(F->getType()->getElementType() == Ty); 2086f22ef01cSRoman Divacky return F; 2087f22ef01cSRoman Divacky } 2088f22ef01cSRoman Divacky 208917a519f9SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2090f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(F, PTy); 2091f22ef01cSRoman Divacky } 2092f22ef01cSRoman Divacky 2093f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function. If Ty is 2094f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to 2095f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function). 2096f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 20976122f3e6SDimitry Andric llvm::Type *Ty, 209859d1ed5bSDimitry Andric bool ForVTable, 20990623d748SDimitry Andric bool DontDefer, 210044290647SDimitry Andric ForDefinition_t IsForDefinition) { 2101f22ef01cSRoman Divacky // If there was no specific requested type, just convert it now. 21020623d748SDimitry Andric if (!Ty) { 21030623d748SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 21040623d748SDimitry Andric auto CanonTy = Context.getCanonicalType(FD->getType()); 21050623d748SDimitry Andric Ty = getTypes().ConvertFunctionType(CanonTy, FD); 21060623d748SDimitry Andric } 2107ffd1746dSEd Schouten 21086122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 21090623d748SDimitry Andric return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 211020e90f04SDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), 21110623d748SDimitry Andric IsForDefinition); 2112f22ef01cSRoman Divacky } 2113f22ef01cSRoman Divacky 211444290647SDimitry Andric static const FunctionDecl * 211544290647SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 211644290647SDimitry Andric TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 211744290647SDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 211844290647SDimitry Andric 211944290647SDimitry Andric IdentifierInfo &CII = C.Idents.get(Name); 212044290647SDimitry Andric for (const auto &Result : DC->lookup(&CII)) 212144290647SDimitry Andric if (const auto FD = dyn_cast<FunctionDecl>(Result)) 212244290647SDimitry Andric return FD; 212344290647SDimitry Andric 212444290647SDimitry Andric if (!C.getLangOpts().CPlusPlus) 212544290647SDimitry Andric return nullptr; 212644290647SDimitry Andric 212744290647SDimitry Andric // Demangle the premangled name from getTerminateFn() 212844290647SDimitry Andric IdentifierInfo &CXXII = 212944290647SDimitry Andric (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ") 213044290647SDimitry Andric ? C.Idents.get("terminate") 213144290647SDimitry Andric : C.Idents.get(Name); 213244290647SDimitry Andric 213344290647SDimitry Andric for (const auto &N : {"__cxxabiv1", "std"}) { 213444290647SDimitry Andric IdentifierInfo &NS = C.Idents.get(N); 213544290647SDimitry Andric for (const auto &Result : DC->lookup(&NS)) { 213644290647SDimitry Andric NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 213744290647SDimitry Andric if (auto LSD = dyn_cast<LinkageSpecDecl>(Result)) 213844290647SDimitry Andric for (const auto &Result : LSD->lookup(&NS)) 213944290647SDimitry Andric if ((ND = dyn_cast<NamespaceDecl>(Result))) 214044290647SDimitry Andric break; 214144290647SDimitry Andric 214244290647SDimitry Andric if (ND) 214344290647SDimitry Andric for (const auto &Result : ND->lookup(&CXXII)) 214444290647SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 214544290647SDimitry Andric return FD; 214644290647SDimitry Andric } 214744290647SDimitry Andric } 214844290647SDimitry Andric 214944290647SDimitry Andric return nullptr; 215044290647SDimitry Andric } 215144290647SDimitry Andric 2152f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified 2153f22ef01cSRoman Divacky /// type and name. 2154f22ef01cSRoman Divacky llvm::Constant * 215544290647SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 215620e90f04SDimitry Andric llvm::AttributeList ExtraAttrs, 215744290647SDimitry Andric bool Local) { 215859d1ed5bSDimitry Andric llvm::Constant *C = 215959d1ed5bSDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 216044290647SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, 216144290647SDimitry Andric ExtraAttrs); 216244290647SDimitry Andric 216344290647SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) { 216444290647SDimitry Andric if (F->empty()) { 2165139f7f9bSDimitry Andric F->setCallingConv(getRuntimeCC()); 216644290647SDimitry Andric 216744290647SDimitry Andric if (!Local && getTriple().isOSBinFormatCOFF() && 216844290647SDimitry Andric !getCodeGenOpts().LTOVisibilityPublicStd) { 216944290647SDimitry Andric const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 217044290647SDimitry Andric if (!FD || FD->hasAttr<DLLImportAttr>()) { 217144290647SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 217244290647SDimitry Andric F->setLinkage(llvm::GlobalValue::ExternalLinkage); 217344290647SDimitry Andric } 217444290647SDimitry Andric } 217544290647SDimitry Andric } 217644290647SDimitry Andric } 217744290647SDimitry Andric 2178139f7f9bSDimitry Andric return C; 2179f22ef01cSRoman Divacky } 2180f22ef01cSRoman Divacky 218139d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified 218239d628a0SDimitry Andric /// type and name. 218339d628a0SDimitry Andric llvm::Constant * 218420e90f04SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name, 218520e90f04SDimitry Andric llvm::AttributeList ExtraAttrs) { 218639d628a0SDimitry Andric llvm::Constant *C = 218739d628a0SDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 218839d628a0SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 218939d628a0SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) 219039d628a0SDimitry Andric if (F->empty()) 219139d628a0SDimitry Andric F->setCallingConv(getBuiltinCC()); 219239d628a0SDimitry Andric return C; 219339d628a0SDimitry Andric } 219439d628a0SDimitry Andric 2195dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted 2196dff0c46cSDimitry Andric /// as a constant. 2197dff0c46cSDimitry Andric /// 2198dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs 2199dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is 2200dff0c46cSDimitry Andric /// not written to during its construction. 2201dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 2202dff0c46cSDimitry Andric if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 2203f22ef01cSRoman Divacky return false; 2204bd5abe19SDimitry Andric 2205dff0c46cSDimitry Andric if (Context.getLangOpts().CPlusPlus) { 2206dff0c46cSDimitry Andric if (const CXXRecordDecl *Record 2207dff0c46cSDimitry Andric = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 2208dff0c46cSDimitry Andric return ExcludeCtor && !Record->hasMutableFields() && 2209dff0c46cSDimitry Andric Record->hasTrivialDestructor(); 2210f22ef01cSRoman Divacky } 2211bd5abe19SDimitry Andric 2212f22ef01cSRoman Divacky return true; 2213f22ef01cSRoman Divacky } 2214f22ef01cSRoman Divacky 2215f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 2216f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type. If there 2217f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 2218f22ef01cSRoman Divacky /// bitcasted to the right type. 2219f22ef01cSRoman Divacky /// 2220f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 2221f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created. 2222e7145dcbSDimitry Andric /// 2223e7145dcbSDimitry Andric /// If IsForDefinition is true, it is guranteed that an actual global with 2224e7145dcbSDimitry Andric /// type Ty will be returned, not conversion of a variable with the same 2225e7145dcbSDimitry Andric /// mangled name but some other type. 2226f22ef01cSRoman Divacky llvm::Constant * 22276122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 22286122f3e6SDimitry Andric llvm::PointerType *Ty, 2229e7145dcbSDimitry Andric const VarDecl *D, 223044290647SDimitry Andric ForDefinition_t IsForDefinition) { 2231f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 2232f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2233f22ef01cSRoman Divacky if (Entry) { 22343861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 2235f22ef01cSRoman Divacky if (D && !D->hasAttr<WeakAttr>()) 2236f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 2237f22ef01cSRoman Divacky } 2238f22ef01cSRoman Divacky 223939d628a0SDimitry Andric // Handle dropped DLL attributes. 224039d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 224139d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 224239d628a0SDimitry Andric 2243f22ef01cSRoman Divacky if (Entry->getType() == Ty) 2244f22ef01cSRoman Divacky return Entry; 2245f22ef01cSRoman Divacky 2246e7145dcbSDimitry Andric // If there are two attempts to define the same mangled name, issue an 2247e7145dcbSDimitry Andric // error. 2248e7145dcbSDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 2249e7145dcbSDimitry Andric GlobalDecl OtherGD; 2250e7145dcbSDimitry Andric const VarDecl *OtherD; 2251e7145dcbSDimitry Andric 2252e7145dcbSDimitry Andric // Check that D is not yet in DiagnosedConflictingDefinitions is required 2253e7145dcbSDimitry Andric // to make sure that we issue an error only once. 2254e7145dcbSDimitry Andric if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 2255e7145dcbSDimitry Andric (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 2256e7145dcbSDimitry Andric (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 2257e7145dcbSDimitry Andric OtherD->hasInit() && 2258e7145dcbSDimitry Andric DiagnosedConflictingDefinitions.insert(D).second) { 2259e7145dcbSDimitry Andric getDiags().Report(D->getLocation(), 2260e7145dcbSDimitry Andric diag::err_duplicate_mangled_name); 2261e7145dcbSDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 2262e7145dcbSDimitry Andric diag::note_previous_definition); 2263e7145dcbSDimitry Andric } 2264e7145dcbSDimitry Andric } 2265e7145dcbSDimitry Andric 2266f22ef01cSRoman Divacky // Make sure the result is of the correct type. 2267f785676fSDimitry Andric if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 2268f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 2269f785676fSDimitry Andric 2270e7145dcbSDimitry Andric // (If global is requested for a definition, we always need to create a new 2271e7145dcbSDimitry Andric // global, not just return a bitcast.) 2272e7145dcbSDimitry Andric if (!IsForDefinition) 2273f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(Entry, Ty); 2274f22ef01cSRoman Divacky } 2275f22ef01cSRoman Divacky 227659d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 227759d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 227859d1ed5bSDimitry Andric getModule(), Ty->getElementType(), false, 227959d1ed5bSDimitry Andric llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 228059d1ed5bSDimitry Andric llvm::GlobalVariable::NotThreadLocal, AddrSpace); 228159d1ed5bSDimitry Andric 2282e7145dcbSDimitry Andric // If we already created a global with the same mangled name (but different 2283e7145dcbSDimitry Andric // type) before, take its name and remove it from its parent. 2284e7145dcbSDimitry Andric if (Entry) { 2285e7145dcbSDimitry Andric GV->takeName(Entry); 2286e7145dcbSDimitry Andric 2287e7145dcbSDimitry Andric if (!Entry->use_empty()) { 2288e7145dcbSDimitry Andric llvm::Constant *NewPtrForOldDecl = 2289e7145dcbSDimitry Andric llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2290e7145dcbSDimitry Andric Entry->replaceAllUsesWith(NewPtrForOldDecl); 2291e7145dcbSDimitry Andric } 2292e7145dcbSDimitry Andric 2293e7145dcbSDimitry Andric Entry->eraseFromParent(); 2294e7145dcbSDimitry Andric } 2295e7145dcbSDimitry Andric 2296f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 2297f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 2298f22ef01cSRoman Divacky // of the file. 229959d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 2300f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 2301f22ef01cSRoman Divacky // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 2302f22ef01cSRoman Divacky // list, and remove it from DeferredDecls (since we don't need it anymore). 2303f37b6182SDimitry Andric addDeferredDeclToEmit(DDI->second); 2304f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 2305f22ef01cSRoman Divacky } 2306f22ef01cSRoman Divacky 2307f22ef01cSRoman Divacky // Handle things which are present even on external declarations. 2308f22ef01cSRoman Divacky if (D) { 2309f22ef01cSRoman Divacky // FIXME: This code is overly simple and should be merged with other global 2310f22ef01cSRoman Divacky // handling. 2311dff0c46cSDimitry Andric GV->setConstant(isTypeConstant(D->getType(), false)); 2312f22ef01cSRoman Divacky 231333956c43SDimitry Andric GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 231433956c43SDimitry Andric 231559d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(GV, D); 23162754fe60SDimitry Andric 2317284c1978SDimitry Andric if (D->getTLSKind()) { 2318284c1978SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 23190623d748SDimitry Andric CXXThreadLocals.push_back(D); 23207ae0e2c9SDimitry Andric setTLSMode(GV, *D); 2321f22ef01cSRoman Divacky } 2322f785676fSDimitry Andric 2323f785676fSDimitry Andric // If required by the ABI, treat declarations of static data members with 2324f785676fSDimitry Andric // inline initializers as definitions. 232559d1ed5bSDimitry Andric if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 2326f785676fSDimitry Andric EmitGlobalVarDefinition(D); 2327284c1978SDimitry Andric } 2328f22ef01cSRoman Divacky 232959d1ed5bSDimitry Andric // Handle XCore specific ABI requirements. 233044290647SDimitry Andric if (getTriple().getArch() == llvm::Triple::xcore && 233159d1ed5bSDimitry Andric D->getLanguageLinkage() == CLanguageLinkage && 233259d1ed5bSDimitry Andric D->getType().isConstant(Context) && 233359d1ed5bSDimitry Andric isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 233459d1ed5bSDimitry Andric GV->setSection(".cp.rodata"); 233559d1ed5bSDimitry Andric } 233659d1ed5bSDimitry Andric 23377ae0e2c9SDimitry Andric if (AddrSpace != Ty->getAddressSpace()) 2338f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty); 2339f785676fSDimitry Andric 2340f22ef01cSRoman Divacky return GV; 2341f22ef01cSRoman Divacky } 2342f22ef01cSRoman Divacky 23430623d748SDimitry Andric llvm::Constant * 23440623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, 234544290647SDimitry Andric ForDefinition_t IsForDefinition) { 234644290647SDimitry Andric const Decl *D = GD.getDecl(); 234744290647SDimitry Andric if (isa<CXXConstructorDecl>(D)) 234844290647SDimitry Andric return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D), 23490623d748SDimitry Andric getFromCtorType(GD.getCtorType()), 23500623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 23510623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 235244290647SDimitry Andric else if (isa<CXXDestructorDecl>(D)) 235344290647SDimitry Andric return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D), 23540623d748SDimitry Andric getFromDtorType(GD.getDtorType()), 23550623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 23560623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 235744290647SDimitry Andric else if (isa<CXXMethodDecl>(D)) { 23580623d748SDimitry Andric auto FInfo = &getTypes().arrangeCXXMethodDeclaration( 235944290647SDimitry Andric cast<CXXMethodDecl>(D)); 23600623d748SDimitry Andric auto Ty = getTypes().GetFunctionType(*FInfo); 23610623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 23620623d748SDimitry Andric IsForDefinition); 236344290647SDimitry Andric } else if (isa<FunctionDecl>(D)) { 23640623d748SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 23650623d748SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 23660623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 23670623d748SDimitry Andric IsForDefinition); 23680623d748SDimitry Andric } else 236944290647SDimitry Andric return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, 2370e7145dcbSDimitry Andric IsForDefinition); 23710623d748SDimitry Andric } 2372f22ef01cSRoman Divacky 23732754fe60SDimitry Andric llvm::GlobalVariable * 23746122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 23756122f3e6SDimitry Andric llvm::Type *Ty, 23762754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage) { 23772754fe60SDimitry Andric llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 237859d1ed5bSDimitry Andric llvm::GlobalVariable *OldGV = nullptr; 23792754fe60SDimitry Andric 23802754fe60SDimitry Andric if (GV) { 23812754fe60SDimitry Andric // Check if the variable has the right type. 23822754fe60SDimitry Andric if (GV->getType()->getElementType() == Ty) 23832754fe60SDimitry Andric return GV; 23842754fe60SDimitry Andric 23852754fe60SDimitry Andric // Because C++ name mangling, the only way we can end up with an already 23862754fe60SDimitry Andric // existing global with the same name is if it has been declared extern "C". 23872754fe60SDimitry Andric assert(GV->isDeclaration() && "Declaration has wrong type!"); 23882754fe60SDimitry Andric OldGV = GV; 23892754fe60SDimitry Andric } 23902754fe60SDimitry Andric 23912754fe60SDimitry Andric // Create a new variable. 23922754fe60SDimitry Andric GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 239359d1ed5bSDimitry Andric Linkage, nullptr, Name); 23942754fe60SDimitry Andric 23952754fe60SDimitry Andric if (OldGV) { 23962754fe60SDimitry Andric // Replace occurrences of the old variable if needed. 23972754fe60SDimitry Andric GV->takeName(OldGV); 23982754fe60SDimitry Andric 23992754fe60SDimitry Andric if (!OldGV->use_empty()) { 24002754fe60SDimitry Andric llvm::Constant *NewPtrForOldDecl = 24012754fe60SDimitry Andric llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 24022754fe60SDimitry Andric OldGV->replaceAllUsesWith(NewPtrForOldDecl); 24032754fe60SDimitry Andric } 24042754fe60SDimitry Andric 24052754fe60SDimitry Andric OldGV->eraseFromParent(); 24062754fe60SDimitry Andric } 24072754fe60SDimitry Andric 240833956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker() && 240933956c43SDimitry Andric !GV->hasAvailableExternallyLinkage()) 241033956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 241133956c43SDimitry Andric 24122754fe60SDimitry Andric return GV; 24132754fe60SDimitry Andric } 24142754fe60SDimitry Andric 2415f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 2416f22ef01cSRoman Divacky /// given global variable. If Ty is non-null and if the global doesn't exist, 2417cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the 2418e7145dcbSDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guranteed 2419e7145dcbSDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a 2420e7145dcbSDimitry Andric /// variable with the same mangled name but some other type. 2421f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 2422e7145dcbSDimitry Andric llvm::Type *Ty, 242344290647SDimitry Andric ForDefinition_t IsForDefinition) { 2424f22ef01cSRoman Divacky assert(D->hasGlobalStorage() && "Not a global variable"); 2425f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 242659d1ed5bSDimitry Andric if (!Ty) 2427f22ef01cSRoman Divacky Ty = getTypes().ConvertTypeForMem(ASTTy); 2428f22ef01cSRoman Divacky 24296122f3e6SDimitry Andric llvm::PointerType *PTy = 24303b0f4066SDimitry Andric llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 2431f22ef01cSRoman Divacky 24326122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2433e7145dcbSDimitry Andric return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition); 2434f22ef01cSRoman Divacky } 2435f22ef01cSRoman Divacky 2436f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the 2437f22ef01cSRoman Divacky /// specified type and name. 2438f22ef01cSRoman Divacky llvm::Constant * 24396122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 24406122f3e6SDimitry Andric StringRef Name) { 244159d1ed5bSDimitry Andric return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr); 2442f22ef01cSRoman Divacky } 2443f22ef01cSRoman Divacky 2444f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 2445f22ef01cSRoman Divacky assert(!D->getInit() && "Cannot emit definite definitions here!"); 2446f22ef01cSRoman Divacky 24476122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2448e7145dcbSDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(MangledName); 2449e7145dcbSDimitry Andric 2450e7145dcbSDimitry Andric // We already have a definition, not declaration, with the same mangled name. 2451e7145dcbSDimitry Andric // Emitting of declaration is not required (and actually overwrites emitted 2452e7145dcbSDimitry Andric // definition). 2453e7145dcbSDimitry Andric if (GV && !GV->isDeclaration()) 2454e7145dcbSDimitry Andric return; 2455e7145dcbSDimitry Andric 2456e7145dcbSDimitry Andric // If we have not seen a reference to this variable yet, place it into the 2457e7145dcbSDimitry Andric // deferred declarations table to be emitted if needed later. 2458e7145dcbSDimitry Andric if (!MustBeEmitted(D) && !GV) { 2459f22ef01cSRoman Divacky DeferredDecls[MangledName] = D; 2460f22ef01cSRoman Divacky return; 2461f22ef01cSRoman Divacky } 2462f22ef01cSRoman Divacky 2463f22ef01cSRoman Divacky // The tentative definition is the only definition. 2464f22ef01cSRoman Divacky EmitGlobalVarDefinition(D); 2465f22ef01cSRoman Divacky } 2466f22ef01cSRoman Divacky 24676122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 24682754fe60SDimitry Andric return Context.toCharUnitsFromBits( 24690623d748SDimitry Andric getDataLayout().getTypeStoreSizeInBits(Ty)); 2470f22ef01cSRoman Divacky } 2471f22ef01cSRoman Divacky 24727ae0e2c9SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 24737ae0e2c9SDimitry Andric unsigned AddrSpace) { 2474e7145dcbSDimitry Andric if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) { 24757ae0e2c9SDimitry Andric if (D->hasAttr<CUDAConstantAttr>()) 24767ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 24777ae0e2c9SDimitry Andric else if (D->hasAttr<CUDASharedAttr>()) 24787ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 24797ae0e2c9SDimitry Andric else 24807ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 24817ae0e2c9SDimitry Andric } 24827ae0e2c9SDimitry Andric 24837ae0e2c9SDimitry Andric return AddrSpace; 24847ae0e2c9SDimitry Andric } 24857ae0e2c9SDimitry Andric 2486284c1978SDimitry Andric template<typename SomeDecl> 2487284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 2488284c1978SDimitry Andric llvm::GlobalValue *GV) { 2489284c1978SDimitry Andric if (!getLangOpts().CPlusPlus) 2490284c1978SDimitry Andric return; 2491284c1978SDimitry Andric 2492284c1978SDimitry Andric // Must have 'used' attribute, or else inline assembly can't rely on 2493284c1978SDimitry Andric // the name existing. 2494284c1978SDimitry Andric if (!D->template hasAttr<UsedAttr>()) 2495284c1978SDimitry Andric return; 2496284c1978SDimitry Andric 2497284c1978SDimitry Andric // Must have internal linkage and an ordinary name. 2498f785676fSDimitry Andric if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 2499284c1978SDimitry Andric return; 2500284c1978SDimitry Andric 2501284c1978SDimitry Andric // Must be in an extern "C" context. Entities declared directly within 2502284c1978SDimitry Andric // a record are not extern "C" even if the record is in such a context. 2503f785676fSDimitry Andric const SomeDecl *First = D->getFirstDecl(); 2504284c1978SDimitry Andric if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 2505284c1978SDimitry Andric return; 2506284c1978SDimitry Andric 2507284c1978SDimitry Andric // OK, this is an internal linkage entity inside an extern "C" linkage 2508284c1978SDimitry Andric // specification. Make a note of that so we can give it the "expected" 2509284c1978SDimitry Andric // mangled name if nothing else is using that name. 2510284c1978SDimitry Andric std::pair<StaticExternCMap::iterator, bool> R = 2511284c1978SDimitry Andric StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 2512284c1978SDimitry Andric 2513284c1978SDimitry Andric // If we have multiple internal linkage entities with the same name 2514284c1978SDimitry Andric // in extern "C" regions, none of them gets that name. 2515284c1978SDimitry Andric if (!R.second) 251659d1ed5bSDimitry Andric R.first->second = nullptr; 2517284c1978SDimitry Andric } 2518284c1978SDimitry Andric 251933956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 252033956c43SDimitry Andric if (!CGM.supportsCOMDAT()) 252133956c43SDimitry Andric return false; 252233956c43SDimitry Andric 252333956c43SDimitry Andric if (D.hasAttr<SelectAnyAttr>()) 252433956c43SDimitry Andric return true; 252533956c43SDimitry Andric 252633956c43SDimitry Andric GVALinkage Linkage; 252733956c43SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(&D)) 252833956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 252933956c43SDimitry Andric else 253033956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 253133956c43SDimitry Andric 253233956c43SDimitry Andric switch (Linkage) { 253333956c43SDimitry Andric case GVA_Internal: 253433956c43SDimitry Andric case GVA_AvailableExternally: 253533956c43SDimitry Andric case GVA_StrongExternal: 253633956c43SDimitry Andric return false; 253733956c43SDimitry Andric case GVA_DiscardableODR: 253833956c43SDimitry Andric case GVA_StrongODR: 253933956c43SDimitry Andric return true; 254033956c43SDimitry Andric } 254133956c43SDimitry Andric llvm_unreachable("No such linkage"); 254233956c43SDimitry Andric } 254333956c43SDimitry Andric 254433956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 254533956c43SDimitry Andric llvm::GlobalObject &GO) { 254633956c43SDimitry Andric if (!shouldBeInCOMDAT(*this, D)) 254733956c43SDimitry Andric return; 254833956c43SDimitry Andric GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 254933956c43SDimitry Andric } 255033956c43SDimitry Andric 2551e7145dcbSDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition. 2552e7145dcbSDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 2553e7145dcbSDimitry Andric bool IsTentative) { 255444290647SDimitry Andric // OpenCL global variables of sampler type are translated to function calls, 255544290647SDimitry Andric // therefore no need to be translated. 2556f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 255744290647SDimitry Andric if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 255844290647SDimitry Andric return; 255944290647SDimitry Andric 256044290647SDimitry Andric llvm::Constant *Init = nullptr; 2561dff0c46cSDimitry Andric CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2562dff0c46cSDimitry Andric bool NeedsGlobalCtor = false; 2563dff0c46cSDimitry Andric bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 2564f22ef01cSRoman Divacky 2565dff0c46cSDimitry Andric const VarDecl *InitDecl; 2566dff0c46cSDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 2567f22ef01cSRoman Divacky 2568e7145dcbSDimitry Andric // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 2569e7145dcbSDimitry Andric // as part of their declaration." Sema has already checked for 2570e7145dcbSDimitry Andric // error cases, so we just need to set Init to UndefValue. 2571e7145dcbSDimitry Andric if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 2572e7145dcbSDimitry Andric D->hasAttr<CUDASharedAttr>()) 25730623d748SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 2574e7145dcbSDimitry Andric else if (!InitExpr) { 2575f22ef01cSRoman Divacky // This is a tentative definition; tentative definitions are 2576f22ef01cSRoman Divacky // implicitly initialized with { 0 }. 2577f22ef01cSRoman Divacky // 2578f22ef01cSRoman Divacky // Note that tentative definitions are only emitted at the end of 2579f22ef01cSRoman Divacky // a translation unit, so they should never have incomplete 2580f22ef01cSRoman Divacky // type. In addition, EmitTentativeDefinition makes sure that we 2581f22ef01cSRoman Divacky // never attempt to emit a tentative definition if a real one 2582f22ef01cSRoman Divacky // exists. A use may still exists, however, so we still may need 2583f22ef01cSRoman Divacky // to do a RAUW. 2584f22ef01cSRoman Divacky assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 2585f22ef01cSRoman Divacky Init = EmitNullConstant(D->getType()); 2586f22ef01cSRoman Divacky } else { 25877ae0e2c9SDimitry Andric initializedGlobalDecl = GlobalDecl(D); 2588dff0c46cSDimitry Andric Init = EmitConstantInit(*InitDecl); 2589f785676fSDimitry Andric 2590f22ef01cSRoman Divacky if (!Init) { 2591f22ef01cSRoman Divacky QualType T = InitExpr->getType(); 2592f22ef01cSRoman Divacky if (D->getType()->isReferenceType()) 2593f22ef01cSRoman Divacky T = D->getType(); 2594f22ef01cSRoman Divacky 2595dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus) { 2596f22ef01cSRoman Divacky Init = EmitNullConstant(T); 2597dff0c46cSDimitry Andric NeedsGlobalCtor = true; 2598f22ef01cSRoman Divacky } else { 2599f22ef01cSRoman Divacky ErrorUnsupported(D, "static initializer"); 2600f22ef01cSRoman Divacky Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 2601f22ef01cSRoman Divacky } 2602e580952dSDimitry Andric } else { 2603e580952dSDimitry Andric // We don't need an initializer, so remove the entry for the delayed 2604dff0c46cSDimitry Andric // initializer position (just in case this entry was delayed) if we 2605dff0c46cSDimitry Andric // also don't need to register a destructor. 2606dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 2607e580952dSDimitry Andric DelayedCXXInitPosition.erase(D); 2608f22ef01cSRoman Divacky } 2609f22ef01cSRoman Divacky } 2610f22ef01cSRoman Divacky 26116122f3e6SDimitry Andric llvm::Type* InitType = Init->getType(); 2612e7145dcbSDimitry Andric llvm::Constant *Entry = 261344290647SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 2614f22ef01cSRoman Divacky 2615f22ef01cSRoman Divacky // Strip off a bitcast if we got one back. 261659d1ed5bSDimitry Andric if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2617f22ef01cSRoman Divacky assert(CE->getOpcode() == llvm::Instruction::BitCast || 2618f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 2619f785676fSDimitry Andric // All zero index gep. 2620f22ef01cSRoman Divacky CE->getOpcode() == llvm::Instruction::GetElementPtr); 2621f22ef01cSRoman Divacky Entry = CE->getOperand(0); 2622f22ef01cSRoman Divacky } 2623f22ef01cSRoman Divacky 2624f22ef01cSRoman Divacky // Entry is now either a Function or GlobalVariable. 262559d1ed5bSDimitry Andric auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 2626f22ef01cSRoman Divacky 2627f22ef01cSRoman Divacky // We have a definition after a declaration with the wrong type. 2628f22ef01cSRoman Divacky // We must make a new GlobalVariable* and update everything that used OldGV 2629f22ef01cSRoman Divacky // (a declaration or tentative definition) with the new GlobalVariable* 2630f22ef01cSRoman Divacky // (which will be a definition). 2631f22ef01cSRoman Divacky // 2632f22ef01cSRoman Divacky // This happens if there is a prototype for a global (e.g. 2633f22ef01cSRoman Divacky // "extern int x[];") and then a definition of a different type (e.g. 2634f22ef01cSRoman Divacky // "int x[10];"). This also happens when an initializer has a different type 2635f22ef01cSRoman Divacky // from the type of the global (this happens with unions). 263659d1ed5bSDimitry Andric if (!GV || 2637f22ef01cSRoman Divacky GV->getType()->getElementType() != InitType || 26383b0f4066SDimitry Andric GV->getType()->getAddressSpace() != 26397ae0e2c9SDimitry Andric GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 2640f22ef01cSRoman Divacky 2641f22ef01cSRoman Divacky // Move the old entry aside so that we'll create a new one. 26426122f3e6SDimitry Andric Entry->setName(StringRef()); 2643f22ef01cSRoman Divacky 2644f22ef01cSRoman Divacky // Make a new global with the correct type, this is now guaranteed to work. 2645e7145dcbSDimitry Andric GV = cast<llvm::GlobalVariable>( 264644290647SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))); 2647f22ef01cSRoman Divacky 2648f22ef01cSRoman Divacky // Replace all uses of the old global with the new global 2649f22ef01cSRoman Divacky llvm::Constant *NewPtrForOldDecl = 2650f22ef01cSRoman Divacky llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2651f22ef01cSRoman Divacky Entry->replaceAllUsesWith(NewPtrForOldDecl); 2652f22ef01cSRoman Divacky 2653f22ef01cSRoman Divacky // Erase the old global, since it is no longer used. 2654f22ef01cSRoman Divacky cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 2655f22ef01cSRoman Divacky } 2656f22ef01cSRoman Divacky 2657284c1978SDimitry Andric MaybeHandleStaticInExternC(D, GV); 2658284c1978SDimitry Andric 26596122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 26606122f3e6SDimitry Andric AddGlobalAnnotations(D, GV); 2661f22ef01cSRoman Divacky 2662e7145dcbSDimitry Andric // Set the llvm linkage type as appropriate. 2663e7145dcbSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 2664e7145dcbSDimitry Andric getLLVMLinkageVarDefinition(D, GV->isConstant()); 2665e7145dcbSDimitry Andric 26660623d748SDimitry Andric // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 26670623d748SDimitry Andric // the device. [...]" 26680623d748SDimitry Andric // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 26690623d748SDimitry Andric // __device__, declares a variable that: [...] 26700623d748SDimitry Andric // Is accessible from all the threads within the grid and from the host 26710623d748SDimitry Andric // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 26720623d748SDimitry Andric // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 2673e7145dcbSDimitry Andric if (GV && LangOpts.CUDA) { 2674e7145dcbSDimitry Andric if (LangOpts.CUDAIsDevice) { 2675e7145dcbSDimitry Andric if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) 26760623d748SDimitry Andric GV->setExternallyInitialized(true); 2677e7145dcbSDimitry Andric } else { 2678e7145dcbSDimitry Andric // Host-side shadows of external declarations of device-side 2679e7145dcbSDimitry Andric // global variables become internal definitions. These have to 2680e7145dcbSDimitry Andric // be internal in order to prevent name conflicts with global 2681e7145dcbSDimitry Andric // host variables with the same name in a different TUs. 2682e7145dcbSDimitry Andric if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) { 2683e7145dcbSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 2684e7145dcbSDimitry Andric 2685e7145dcbSDimitry Andric // Shadow variables and their properties must be registered 2686e7145dcbSDimitry Andric // with CUDA runtime. 2687e7145dcbSDimitry Andric unsigned Flags = 0; 2688e7145dcbSDimitry Andric if (!D->hasDefinition()) 2689e7145dcbSDimitry Andric Flags |= CGCUDARuntime::ExternDeviceVar; 2690e7145dcbSDimitry Andric if (D->hasAttr<CUDAConstantAttr>()) 2691e7145dcbSDimitry Andric Flags |= CGCUDARuntime::ConstantDeviceVar; 2692e7145dcbSDimitry Andric getCUDARuntime().registerDeviceVar(*GV, Flags); 2693e7145dcbSDimitry Andric } else if (D->hasAttr<CUDASharedAttr>()) 2694e7145dcbSDimitry Andric // __shared__ variables are odd. Shadows do get created, but 2695e7145dcbSDimitry Andric // they are not registered with the CUDA runtime, so they 2696e7145dcbSDimitry Andric // can't really be used to access their device-side 2697e7145dcbSDimitry Andric // counterparts. It's not clear yet whether it's nvcc's bug or 2698e7145dcbSDimitry Andric // a feature, but we've got to do the same for compatibility. 2699e7145dcbSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 2700e7145dcbSDimitry Andric } 27010623d748SDimitry Andric } 2702f22ef01cSRoman Divacky GV->setInitializer(Init); 2703f22ef01cSRoman Divacky 2704f22ef01cSRoman Divacky // If it is safe to mark the global 'constant', do so now. 2705dff0c46cSDimitry Andric GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 2706dff0c46cSDimitry Andric isTypeConstant(D->getType(), true)); 2707f22ef01cSRoman Divacky 270839d628a0SDimitry Andric // If it is in a read-only section, mark it 'constant'. 270939d628a0SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 271039d628a0SDimitry Andric const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 271139d628a0SDimitry Andric if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 271239d628a0SDimitry Andric GV->setConstant(true); 271339d628a0SDimitry Andric } 271439d628a0SDimitry Andric 2715f22ef01cSRoman Divacky GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 2716f22ef01cSRoman Divacky 2717f785676fSDimitry Andric 27180623d748SDimitry Andric // On Darwin, if the normal linkage of a C++ thread_local variable is 27190623d748SDimitry Andric // LinkOnce or Weak, we keep the normal linkage to prevent multiple 27200623d748SDimitry Andric // copies within a linkage unit; otherwise, the backing variable has 27210623d748SDimitry Andric // internal linkage and all accesses should just be calls to the 272259d1ed5bSDimitry Andric // Itanium-specified entry point, which has the normal linkage of the 27230623d748SDimitry Andric // variable. This is to preserve the ability to change the implementation 27240623d748SDimitry Andric // behind the scenes. 272539d628a0SDimitry Andric if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic && 27260623d748SDimitry Andric Context.getTargetInfo().getTriple().isOSDarwin() && 27270623d748SDimitry Andric !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) && 27280623d748SDimitry Andric !llvm::GlobalVariable::isWeakLinkage(Linkage)) 272959d1ed5bSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 273059d1ed5bSDimitry Andric 273159d1ed5bSDimitry Andric GV->setLinkage(Linkage); 273259d1ed5bSDimitry Andric if (D->hasAttr<DLLImportAttr>()) 273359d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 273459d1ed5bSDimitry Andric else if (D->hasAttr<DLLExportAttr>()) 273559d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 273639d628a0SDimitry Andric else 273739d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 2738f785676fSDimitry Andric 273944290647SDimitry Andric if (Linkage == llvm::GlobalVariable::CommonLinkage) { 2740f22ef01cSRoman Divacky // common vars aren't constant even if declared const. 2741f22ef01cSRoman Divacky GV->setConstant(false); 274244290647SDimitry Andric // Tentative definition of global variables may be initialized with 274344290647SDimitry Andric // non-zero null pointers. In this case they should have weak linkage 274444290647SDimitry Andric // since common linkage must have zero initializer and must not have 274544290647SDimitry Andric // explicit section therefore cannot have non-zero initial value. 274644290647SDimitry Andric if (!GV->getInitializer()->isNullValue()) 274744290647SDimitry Andric GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 274844290647SDimitry Andric } 2749f22ef01cSRoman Divacky 275059d1ed5bSDimitry Andric setNonAliasAttributes(D, GV); 2751f22ef01cSRoman Divacky 275239d628a0SDimitry Andric if (D->getTLSKind() && !GV->isThreadLocal()) { 275339d628a0SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 27540623d748SDimitry Andric CXXThreadLocals.push_back(D); 275539d628a0SDimitry Andric setTLSMode(GV, *D); 275639d628a0SDimitry Andric } 275739d628a0SDimitry Andric 275833956c43SDimitry Andric maybeSetTrivialComdat(*D, *GV); 275933956c43SDimitry Andric 27602754fe60SDimitry Andric // Emit the initializer function if necessary. 2761dff0c46cSDimitry Andric if (NeedsGlobalCtor || NeedsGlobalDtor) 2762dff0c46cSDimitry Andric EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 27632754fe60SDimitry Andric 276439d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 27653861d79fSDimitry Andric 2766f22ef01cSRoman Divacky // Emit global variable debug information. 27676122f3e6SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 2768e7145dcbSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 2769f22ef01cSRoman Divacky DI->EmitGlobalVariable(GV, D); 2770f22ef01cSRoman Divacky } 2771f22ef01cSRoman Divacky 277239d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context, 277333956c43SDimitry Andric CodeGenModule &CGM, const VarDecl *D, 277433956c43SDimitry Andric bool NoCommon) { 277559d1ed5bSDimitry Andric // Don't give variables common linkage if -fno-common was specified unless it 277659d1ed5bSDimitry Andric // was overridden by a NoCommon attribute. 277759d1ed5bSDimitry Andric if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 277859d1ed5bSDimitry Andric return true; 277959d1ed5bSDimitry Andric 278059d1ed5bSDimitry Andric // C11 6.9.2/2: 278159d1ed5bSDimitry Andric // A declaration of an identifier for an object that has file scope without 278259d1ed5bSDimitry Andric // an initializer, and without a storage-class specifier or with the 278359d1ed5bSDimitry Andric // storage-class specifier static, constitutes a tentative definition. 278459d1ed5bSDimitry Andric if (D->getInit() || D->hasExternalStorage()) 278559d1ed5bSDimitry Andric return true; 278659d1ed5bSDimitry Andric 278759d1ed5bSDimitry Andric // A variable cannot be both common and exist in a section. 278859d1ed5bSDimitry Andric if (D->hasAttr<SectionAttr>()) 278959d1ed5bSDimitry Andric return true; 279059d1ed5bSDimitry Andric 279159d1ed5bSDimitry Andric // Thread local vars aren't considered common linkage. 279259d1ed5bSDimitry Andric if (D->getTLSKind()) 279359d1ed5bSDimitry Andric return true; 279459d1ed5bSDimitry Andric 279559d1ed5bSDimitry Andric // Tentative definitions marked with WeakImportAttr are true definitions. 279659d1ed5bSDimitry Andric if (D->hasAttr<WeakImportAttr>()) 279759d1ed5bSDimitry Andric return true; 279859d1ed5bSDimitry Andric 279933956c43SDimitry Andric // A variable cannot be both common and exist in a comdat. 280033956c43SDimitry Andric if (shouldBeInCOMDAT(CGM, *D)) 280133956c43SDimitry Andric return true; 280233956c43SDimitry Andric 2803e7145dcbSDimitry Andric // Declarations with a required alignment do not have common linkage in MSVC 280439d628a0SDimitry Andric // mode. 28050623d748SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 280633956c43SDimitry Andric if (D->hasAttr<AlignedAttr>()) 280739d628a0SDimitry Andric return true; 280833956c43SDimitry Andric QualType VarType = D->getType(); 280933956c43SDimitry Andric if (Context.isAlignmentRequired(VarType)) 281033956c43SDimitry Andric return true; 281133956c43SDimitry Andric 281233956c43SDimitry Andric if (const auto *RT = VarType->getAs<RecordType>()) { 281333956c43SDimitry Andric const RecordDecl *RD = RT->getDecl(); 281433956c43SDimitry Andric for (const FieldDecl *FD : RD->fields()) { 281533956c43SDimitry Andric if (FD->isBitField()) 281633956c43SDimitry Andric continue; 281733956c43SDimitry Andric if (FD->hasAttr<AlignedAttr>()) 281833956c43SDimitry Andric return true; 281933956c43SDimitry Andric if (Context.isAlignmentRequired(FD->getType())) 282033956c43SDimitry Andric return true; 282133956c43SDimitry Andric } 282233956c43SDimitry Andric } 282333956c43SDimitry Andric } 282439d628a0SDimitry Andric 282559d1ed5bSDimitry Andric return false; 282659d1ed5bSDimitry Andric } 282759d1ed5bSDimitry Andric 282859d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 282959d1ed5bSDimitry Andric const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 28302754fe60SDimitry Andric if (Linkage == GVA_Internal) 28312754fe60SDimitry Andric return llvm::Function::InternalLinkage; 283259d1ed5bSDimitry Andric 283359d1ed5bSDimitry Andric if (D->hasAttr<WeakAttr>()) { 283459d1ed5bSDimitry Andric if (IsConstantVariable) 283559d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 283659d1ed5bSDimitry Andric else 283759d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakAnyLinkage; 283859d1ed5bSDimitry Andric } 283959d1ed5bSDimitry Andric 284059d1ed5bSDimitry Andric // We are guaranteed to have a strong definition somewhere else, 284159d1ed5bSDimitry Andric // so we can use available_externally linkage. 284259d1ed5bSDimitry Andric if (Linkage == GVA_AvailableExternally) 284320e90f04SDimitry Andric return llvm::GlobalValue::AvailableExternallyLinkage; 284459d1ed5bSDimitry Andric 284559d1ed5bSDimitry Andric // Note that Apple's kernel linker doesn't support symbol 284659d1ed5bSDimitry Andric // coalescing, so we need to avoid linkonce and weak linkages there. 284759d1ed5bSDimitry Andric // Normally, this means we just map to internal, but for explicit 284859d1ed5bSDimitry Andric // instantiations we'll map to external. 284959d1ed5bSDimitry Andric 285059d1ed5bSDimitry Andric // In C++, the compiler has to emit a definition in every translation unit 285159d1ed5bSDimitry Andric // that references the function. We should use linkonce_odr because 285259d1ed5bSDimitry Andric // a) if all references in this translation unit are optimized away, we 285359d1ed5bSDimitry Andric // don't need to codegen it. b) if the function persists, it needs to be 285459d1ed5bSDimitry Andric // merged with other definitions. c) C++ has the ODR, so we know the 285559d1ed5bSDimitry Andric // definition is dependable. 285659d1ed5bSDimitry Andric if (Linkage == GVA_DiscardableODR) 285759d1ed5bSDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 285859d1ed5bSDimitry Andric : llvm::Function::InternalLinkage; 285959d1ed5bSDimitry Andric 286059d1ed5bSDimitry Andric // An explicit instantiation of a template has weak linkage, since 286159d1ed5bSDimitry Andric // explicit instantiations can occur in multiple translation units 286259d1ed5bSDimitry Andric // and must all be equivalent. However, we are not allowed to 286359d1ed5bSDimitry Andric // throw away these explicit instantiations. 2864e7145dcbSDimitry Andric // 2865e7145dcbSDimitry Andric // We don't currently support CUDA device code spread out across multiple TUs, 2866e7145dcbSDimitry Andric // so say that CUDA templates are either external (for kernels) or internal. 2867e7145dcbSDimitry Andric // This lets llvm perform aggressive inter-procedural optimizations. 2868e7145dcbSDimitry Andric if (Linkage == GVA_StrongODR) { 2869e7145dcbSDimitry Andric if (Context.getLangOpts().AppleKext) 2870e7145dcbSDimitry Andric return llvm::Function::ExternalLinkage; 2871e7145dcbSDimitry Andric if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) 2872e7145dcbSDimitry Andric return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 2873e7145dcbSDimitry Andric : llvm::Function::InternalLinkage; 2874e7145dcbSDimitry Andric return llvm::Function::WeakODRLinkage; 2875e7145dcbSDimitry Andric } 287659d1ed5bSDimitry Andric 287759d1ed5bSDimitry Andric // C++ doesn't have tentative definitions and thus cannot have common 287859d1ed5bSDimitry Andric // linkage. 287959d1ed5bSDimitry Andric if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 288033956c43SDimitry Andric !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 288139d628a0SDimitry Andric CodeGenOpts.NoCommon)) 288259d1ed5bSDimitry Andric return llvm::GlobalVariable::CommonLinkage; 288359d1ed5bSDimitry Andric 2884f785676fSDimitry Andric // selectany symbols are externally visible, so use weak instead of 2885f785676fSDimitry Andric // linkonce. MSVC optimizes away references to const selectany globals, so 2886f785676fSDimitry Andric // all definitions should be the same and ODR linkage should be used. 2887f785676fSDimitry Andric // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 288859d1ed5bSDimitry Andric if (D->hasAttr<SelectAnyAttr>()) 2889f785676fSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 289059d1ed5bSDimitry Andric 289159d1ed5bSDimitry Andric // Otherwise, we have strong external linkage. 289259d1ed5bSDimitry Andric assert(Linkage == GVA_StrongExternal); 28932754fe60SDimitry Andric return llvm::GlobalVariable::ExternalLinkage; 28942754fe60SDimitry Andric } 28952754fe60SDimitry Andric 289659d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 289759d1ed5bSDimitry Andric const VarDecl *VD, bool IsConstant) { 289859d1ed5bSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 289959d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 290059d1ed5bSDimitry Andric } 290159d1ed5bSDimitry Andric 2902139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type. 2903139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites 2904139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 2905139f7f9bSDimitry Andric llvm::Function *newFn) { 2906139f7f9bSDimitry Andric // Fast path. 2907139f7f9bSDimitry Andric if (old->use_empty()) return; 2908139f7f9bSDimitry Andric 2909139f7f9bSDimitry Andric llvm::Type *newRetTy = newFn->getReturnType(); 2910139f7f9bSDimitry Andric SmallVector<llvm::Value*, 4> newArgs; 29110623d748SDimitry Andric SmallVector<llvm::OperandBundleDef, 1> newBundles; 2912139f7f9bSDimitry Andric 2913139f7f9bSDimitry Andric for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 2914139f7f9bSDimitry Andric ui != ue; ) { 2915139f7f9bSDimitry Andric llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 291659d1ed5bSDimitry Andric llvm::User *user = use->getUser(); 2917139f7f9bSDimitry Andric 2918139f7f9bSDimitry Andric // Recognize and replace uses of bitcasts. Most calls to 2919139f7f9bSDimitry Andric // unprototyped functions will use bitcasts. 292059d1ed5bSDimitry Andric if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 2921139f7f9bSDimitry Andric if (bitcast->getOpcode() == llvm::Instruction::BitCast) 2922139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(bitcast, newFn); 2923139f7f9bSDimitry Andric continue; 2924139f7f9bSDimitry Andric } 2925139f7f9bSDimitry Andric 2926139f7f9bSDimitry Andric // Recognize calls to the function. 2927139f7f9bSDimitry Andric llvm::CallSite callSite(user); 2928139f7f9bSDimitry Andric if (!callSite) continue; 292959d1ed5bSDimitry Andric if (!callSite.isCallee(&*use)) continue; 2930139f7f9bSDimitry Andric 2931139f7f9bSDimitry Andric // If the return types don't match exactly, then we can't 2932139f7f9bSDimitry Andric // transform this call unless it's dead. 2933139f7f9bSDimitry Andric if (callSite->getType() != newRetTy && !callSite->use_empty()) 2934139f7f9bSDimitry Andric continue; 2935139f7f9bSDimitry Andric 2936139f7f9bSDimitry Andric // Get the call site's attribute list. 293720e90f04SDimitry Andric SmallVector<llvm::AttributeSet, 8> newArgAttrs; 293820e90f04SDimitry Andric llvm::AttributeList oldAttrs = callSite.getAttributes(); 2939139f7f9bSDimitry Andric 2940139f7f9bSDimitry Andric // If the function was passed too few arguments, don't transform. 2941139f7f9bSDimitry Andric unsigned newNumArgs = newFn->arg_size(); 2942139f7f9bSDimitry Andric if (callSite.arg_size() < newNumArgs) continue; 2943139f7f9bSDimitry Andric 2944139f7f9bSDimitry Andric // If extra arguments were passed, we silently drop them. 2945139f7f9bSDimitry Andric // If any of the types mismatch, we don't transform. 2946139f7f9bSDimitry Andric unsigned argNo = 0; 2947139f7f9bSDimitry Andric bool dontTransform = false; 294820e90f04SDimitry Andric for (llvm::Argument &A : newFn->args()) { 294920e90f04SDimitry Andric if (callSite.getArgument(argNo)->getType() != A.getType()) { 2950139f7f9bSDimitry Andric dontTransform = true; 2951139f7f9bSDimitry Andric break; 2952139f7f9bSDimitry Andric } 2953139f7f9bSDimitry Andric 2954139f7f9bSDimitry Andric // Add any parameter attributes. 295520e90f04SDimitry Andric newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo)); 295620e90f04SDimitry Andric argNo++; 2957139f7f9bSDimitry Andric } 2958139f7f9bSDimitry Andric if (dontTransform) 2959139f7f9bSDimitry Andric continue; 2960139f7f9bSDimitry Andric 2961139f7f9bSDimitry Andric // Okay, we can transform this. Create the new call instruction and copy 2962139f7f9bSDimitry Andric // over the required information. 2963139f7f9bSDimitry Andric newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 2964139f7f9bSDimitry Andric 29650623d748SDimitry Andric // Copy over any operand bundles. 29660623d748SDimitry Andric callSite.getOperandBundlesAsDefs(newBundles); 29670623d748SDimitry Andric 2968139f7f9bSDimitry Andric llvm::CallSite newCall; 2969139f7f9bSDimitry Andric if (callSite.isCall()) { 29700623d748SDimitry Andric newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "", 2971139f7f9bSDimitry Andric callSite.getInstruction()); 2972139f7f9bSDimitry Andric } else { 297359d1ed5bSDimitry Andric auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction()); 2974139f7f9bSDimitry Andric newCall = llvm::InvokeInst::Create(newFn, 2975139f7f9bSDimitry Andric oldInvoke->getNormalDest(), 2976139f7f9bSDimitry Andric oldInvoke->getUnwindDest(), 29770623d748SDimitry Andric newArgs, newBundles, "", 2978139f7f9bSDimitry Andric callSite.getInstruction()); 2979139f7f9bSDimitry Andric } 2980139f7f9bSDimitry Andric newArgs.clear(); // for the next iteration 2981139f7f9bSDimitry Andric 2982139f7f9bSDimitry Andric if (!newCall->getType()->isVoidTy()) 2983139f7f9bSDimitry Andric newCall->takeName(callSite.getInstruction()); 298420e90f04SDimitry Andric newCall.setAttributes(llvm::AttributeList::get( 298520e90f04SDimitry Andric newFn->getContext(), oldAttrs.getFnAttributes(), 298620e90f04SDimitry Andric oldAttrs.getRetAttributes(), newArgAttrs)); 2987139f7f9bSDimitry Andric newCall.setCallingConv(callSite.getCallingConv()); 2988139f7f9bSDimitry Andric 2989139f7f9bSDimitry Andric // Finally, remove the old call, replacing any uses with the new one. 2990139f7f9bSDimitry Andric if (!callSite->use_empty()) 2991139f7f9bSDimitry Andric callSite->replaceAllUsesWith(newCall.getInstruction()); 2992139f7f9bSDimitry Andric 2993139f7f9bSDimitry Andric // Copy debug location attached to CI. 299433956c43SDimitry Andric if (callSite->getDebugLoc()) 2995139f7f9bSDimitry Andric newCall->setDebugLoc(callSite->getDebugLoc()); 29960623d748SDimitry Andric 2997139f7f9bSDimitry Andric callSite->eraseFromParent(); 2998139f7f9bSDimitry Andric } 2999139f7f9bSDimitry Andric } 3000139f7f9bSDimitry Andric 3001f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 3002f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}". If there are 3003f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to 3004f22ef01cSRoman Divacky /// call the new function directly. 3005f22ef01cSRoman Divacky /// 3006f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to 3007f22ef01cSRoman Divacky /// functions to be able to inline them. If there is a bitcast in the way, it 3008f22ef01cSRoman Divacky /// won't inline them. Instcombine normally deletes these calls, but it isn't 3009f22ef01cSRoman Divacky /// run at -O0. 3010f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 3011f22ef01cSRoman Divacky llvm::Function *NewFn) { 3012f22ef01cSRoman Divacky // If we're redefining a global as a function, don't transform it. 3013139f7f9bSDimitry Andric if (!isa<llvm::Function>(Old)) return; 3014f22ef01cSRoman Divacky 3015139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(Old, NewFn); 3016f22ef01cSRoman Divacky } 3017f22ef01cSRoman Divacky 3018dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 3019e7145dcbSDimitry Andric auto DK = VD->isThisDeclarationADefinition(); 3020e7145dcbSDimitry Andric if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 3021e7145dcbSDimitry Andric return; 3022e7145dcbSDimitry Andric 3023dff0c46cSDimitry Andric TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 3024dff0c46cSDimitry Andric // If we have a definition, this might be a deferred decl. If the 3025dff0c46cSDimitry Andric // instantiation is explicit, make sure we emit it at the end. 3026dff0c46cSDimitry Andric if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 3027dff0c46cSDimitry Andric GetAddrOfGlobalVar(VD); 3028139f7f9bSDimitry Andric 3029139f7f9bSDimitry Andric EmitTopLevelDecl(VD); 3030dff0c46cSDimitry Andric } 3031f22ef01cSRoman Divacky 303259d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 303359d1ed5bSDimitry Andric llvm::GlobalValue *GV) { 303459d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 30353b0f4066SDimitry Andric 30363b0f4066SDimitry Andric // Compute the function info and LLVM type. 3037dff0c46cSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3038dff0c46cSDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 30393b0f4066SDimitry Andric 3040f22ef01cSRoman Divacky // Get or create the prototype for the function. 30410623d748SDimitry Andric if (!GV || (GV->getType()->getElementType() != Ty)) 30420623d748SDimitry Andric GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 30430623d748SDimitry Andric /*DontDefer=*/true, 304444290647SDimitry Andric ForDefinition)); 3045f22ef01cSRoman Divacky 30460623d748SDimitry Andric // Already emitted. 30470623d748SDimitry Andric if (!GV->isDeclaration()) 3048f785676fSDimitry Andric return; 3049f22ef01cSRoman Divacky 30502754fe60SDimitry Andric // We need to set linkage and visibility on the function before 30512754fe60SDimitry Andric // generating code for it because various parts of IR generation 30522754fe60SDimitry Andric // want to propagate this information down (e.g. to local static 30532754fe60SDimitry Andric // declarations). 305459d1ed5bSDimitry Andric auto *Fn = cast<llvm::Function>(GV); 3055f785676fSDimitry Andric setFunctionLinkage(GD, Fn); 305697bc6c73SDimitry Andric setFunctionDLLStorageClass(GD, Fn); 3057f22ef01cSRoman Divacky 305859d1ed5bSDimitry Andric // FIXME: this is redundant with part of setFunctionDefinitionAttributes 30592754fe60SDimitry Andric setGlobalVisibility(Fn, D); 30602754fe60SDimitry Andric 3061284c1978SDimitry Andric MaybeHandleStaticInExternC(D, Fn); 3062284c1978SDimitry Andric 306333956c43SDimitry Andric maybeSetTrivialComdat(*D, *Fn); 306433956c43SDimitry Andric 30653b0f4066SDimitry Andric CodeGenFunction(*this).GenerateCode(D, Fn, FI); 3066f22ef01cSRoman Divacky 306759d1ed5bSDimitry Andric setFunctionDefinitionAttributes(D, Fn); 3068f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, Fn); 3069f22ef01cSRoman Divacky 3070f22ef01cSRoman Divacky if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 3071f22ef01cSRoman Divacky AddGlobalCtor(Fn, CA->getPriority()); 3072f22ef01cSRoman Divacky if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 3073f22ef01cSRoman Divacky AddGlobalDtor(Fn, DA->getPriority()); 30746122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 30756122f3e6SDimitry Andric AddGlobalAnnotations(D, Fn); 3076f22ef01cSRoman Divacky } 3077f22ef01cSRoman Divacky 3078f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 307959d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 3080f22ef01cSRoman Divacky const AliasAttr *AA = D->getAttr<AliasAttr>(); 3081f22ef01cSRoman Divacky assert(AA && "Not an alias?"); 3082f22ef01cSRoman Divacky 30836122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 3084f22ef01cSRoman Divacky 30859a4b3118SDimitry Andric if (AA->getAliasee() == MangledName) { 3086e7145dcbSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 30879a4b3118SDimitry Andric return; 30889a4b3118SDimitry Andric } 30899a4b3118SDimitry Andric 3090f22ef01cSRoman Divacky // If there is a definition in the module, then it wins over the alias. 3091f22ef01cSRoman Divacky // This is dubious, but allow it to be safe. Just ignore the alias. 3092f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3093f22ef01cSRoman Divacky if (Entry && !Entry->isDeclaration()) 3094f22ef01cSRoman Divacky return; 3095f22ef01cSRoman Divacky 3096f785676fSDimitry Andric Aliases.push_back(GD); 3097f785676fSDimitry Andric 30986122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 3099f22ef01cSRoman Divacky 3100f22ef01cSRoman Divacky // Create a reference to the named value. This ensures that it is emitted 3101f22ef01cSRoman Divacky // if a deferred decl. 3102f22ef01cSRoman Divacky llvm::Constant *Aliasee; 3103f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 31043861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 31052754fe60SDimitry Andric /*ForVTable=*/false); 3106f22ef01cSRoman Divacky else 3107f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 310859d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 310939d628a0SDimitry Andric /*D=*/nullptr); 3110f22ef01cSRoman Divacky 3111f22ef01cSRoman Divacky // Create the new alias itself, but don't set a name yet. 311259d1ed5bSDimitry Andric auto *GA = llvm::GlobalAlias::create( 31130623d748SDimitry Andric DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule()); 3114f22ef01cSRoman Divacky 3115f22ef01cSRoman Divacky if (Entry) { 311659d1ed5bSDimitry Andric if (GA->getAliasee() == Entry) { 3117e7145dcbSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 311859d1ed5bSDimitry Andric return; 311959d1ed5bSDimitry Andric } 312059d1ed5bSDimitry Andric 3121f22ef01cSRoman Divacky assert(Entry->isDeclaration()); 3122f22ef01cSRoman Divacky 3123f22ef01cSRoman Divacky // If there is a declaration in the module, then we had an extern followed 3124f22ef01cSRoman Divacky // by the alias, as in: 3125f22ef01cSRoman Divacky // extern int test6(); 3126f22ef01cSRoman Divacky // ... 3127f22ef01cSRoman Divacky // int test6() __attribute__((alias("test7"))); 3128f22ef01cSRoman Divacky // 3129f22ef01cSRoman Divacky // Remove it and replace uses of it with the alias. 3130f22ef01cSRoman Divacky GA->takeName(Entry); 3131f22ef01cSRoman Divacky 3132f22ef01cSRoman Divacky Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 3133f22ef01cSRoman Divacky Entry->getType())); 3134f22ef01cSRoman Divacky Entry->eraseFromParent(); 3135f22ef01cSRoman Divacky } else { 3136ffd1746dSEd Schouten GA->setName(MangledName); 3137f22ef01cSRoman Divacky } 3138f22ef01cSRoman Divacky 3139f22ef01cSRoman Divacky // Set attributes which are particular to an alias; this is a 3140f22ef01cSRoman Divacky // specialization of the attributes which may be set on a global 3141f22ef01cSRoman Divacky // variable/function. 314239d628a0SDimitry Andric if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 31433b0f4066SDimitry Andric D->isWeakImported()) { 3144f22ef01cSRoman Divacky GA->setLinkage(llvm::Function::WeakAnyLinkage); 3145f22ef01cSRoman Divacky } 3146f22ef01cSRoman Divacky 314739d628a0SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 314839d628a0SDimitry Andric if (VD->getTLSKind()) 314939d628a0SDimitry Andric setTLSMode(GA, *VD); 315039d628a0SDimitry Andric 315139d628a0SDimitry Andric setAliasAttributes(D, GA); 3152f22ef01cSRoman Divacky } 3153f22ef01cSRoman Divacky 3154e7145dcbSDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 3155e7145dcbSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 3156e7145dcbSDimitry Andric const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 3157e7145dcbSDimitry Andric assert(IFA && "Not an ifunc?"); 3158e7145dcbSDimitry Andric 3159e7145dcbSDimitry Andric StringRef MangledName = getMangledName(GD); 3160e7145dcbSDimitry Andric 3161e7145dcbSDimitry Andric if (IFA->getResolver() == MangledName) { 3162e7145dcbSDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 3163e7145dcbSDimitry Andric return; 3164e7145dcbSDimitry Andric } 3165e7145dcbSDimitry Andric 3166e7145dcbSDimitry Andric // Report an error if some definition overrides ifunc. 3167e7145dcbSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3168e7145dcbSDimitry Andric if (Entry && !Entry->isDeclaration()) { 3169e7145dcbSDimitry Andric GlobalDecl OtherGD; 3170e7145dcbSDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 3171e7145dcbSDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 3172e7145dcbSDimitry Andric Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name); 3173e7145dcbSDimitry Andric Diags.Report(OtherGD.getDecl()->getLocation(), 3174e7145dcbSDimitry Andric diag::note_previous_definition); 3175e7145dcbSDimitry Andric } 3176e7145dcbSDimitry Andric return; 3177e7145dcbSDimitry Andric } 3178e7145dcbSDimitry Andric 3179e7145dcbSDimitry Andric Aliases.push_back(GD); 3180e7145dcbSDimitry Andric 3181e7145dcbSDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 3182e7145dcbSDimitry Andric llvm::Constant *Resolver = 3183e7145dcbSDimitry Andric GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD, 3184e7145dcbSDimitry Andric /*ForVTable=*/false); 3185e7145dcbSDimitry Andric llvm::GlobalIFunc *GIF = 3186e7145dcbSDimitry Andric llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 3187e7145dcbSDimitry Andric "", Resolver, &getModule()); 3188e7145dcbSDimitry Andric if (Entry) { 3189e7145dcbSDimitry Andric if (GIF->getResolver() == Entry) { 3190e7145dcbSDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 3191e7145dcbSDimitry Andric return; 3192e7145dcbSDimitry Andric } 3193e7145dcbSDimitry Andric assert(Entry->isDeclaration()); 3194e7145dcbSDimitry Andric 3195e7145dcbSDimitry Andric // If there is a declaration in the module, then we had an extern followed 3196e7145dcbSDimitry Andric // by the ifunc, as in: 3197e7145dcbSDimitry Andric // extern int test(); 3198e7145dcbSDimitry Andric // ... 3199e7145dcbSDimitry Andric // int test() __attribute__((ifunc("resolver"))); 3200e7145dcbSDimitry Andric // 3201e7145dcbSDimitry Andric // Remove it and replace uses of it with the ifunc. 3202e7145dcbSDimitry Andric GIF->takeName(Entry); 3203e7145dcbSDimitry Andric 3204e7145dcbSDimitry Andric Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 3205e7145dcbSDimitry Andric Entry->getType())); 3206e7145dcbSDimitry Andric Entry->eraseFromParent(); 3207e7145dcbSDimitry Andric } else 3208e7145dcbSDimitry Andric GIF->setName(MangledName); 3209e7145dcbSDimitry Andric 3210e7145dcbSDimitry Andric SetCommonAttributes(D, GIF); 3211e7145dcbSDimitry Andric } 3212e7145dcbSDimitry Andric 321317a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 32146122f3e6SDimitry Andric ArrayRef<llvm::Type*> Tys) { 321517a519f9SDimitry Andric return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 321617a519f9SDimitry Andric Tys); 3217f22ef01cSRoman Divacky } 3218f22ef01cSRoman Divacky 321933956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 322033956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 322133956c43SDimitry Andric const StringLiteral *Literal, bool TargetIsLSB, 322233956c43SDimitry Andric bool &IsUTF16, unsigned &StringLength) { 32236122f3e6SDimitry Andric StringRef String = Literal->getString(); 3224e580952dSDimitry Andric unsigned NumBytes = String.size(); 3225f22ef01cSRoman Divacky 3226f22ef01cSRoman Divacky // Check for simple case. 3227f22ef01cSRoman Divacky if (!Literal->containsNonAsciiOrNull()) { 3228f22ef01cSRoman Divacky StringLength = NumBytes; 322939d628a0SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 3230f22ef01cSRoman Divacky } 3231f22ef01cSRoman Divacky 3232dff0c46cSDimitry Andric // Otherwise, convert the UTF8 literals into a string of shorts. 3233dff0c46cSDimitry Andric IsUTF16 = true; 3234dff0c46cSDimitry Andric 323544290647SDimitry Andric SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 323644290647SDimitry Andric const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 323744290647SDimitry Andric llvm::UTF16 *ToPtr = &ToBuf[0]; 3238f22ef01cSRoman Divacky 323944290647SDimitry Andric (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 324044290647SDimitry Andric ToPtr + NumBytes, llvm::strictConversion); 3241f22ef01cSRoman Divacky 3242f22ef01cSRoman Divacky // ConvertUTF8toUTF16 returns the length in ToPtr. 3243f22ef01cSRoman Divacky StringLength = ToPtr - &ToBuf[0]; 3244f22ef01cSRoman Divacky 3245dff0c46cSDimitry Andric // Add an explicit null. 3246dff0c46cSDimitry Andric *ToPtr = 0; 324739d628a0SDimitry Andric return *Map.insert(std::make_pair( 324839d628a0SDimitry Andric StringRef(reinterpret_cast<const char *>(ToBuf.data()), 324939d628a0SDimitry Andric (StringLength + 1) * 2), 325039d628a0SDimitry Andric nullptr)).first; 3251f22ef01cSRoman Divacky } 3252f22ef01cSRoman Divacky 32530623d748SDimitry Andric ConstantAddress 3254f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 3255f22ef01cSRoman Divacky unsigned StringLength = 0; 3256f22ef01cSRoman Divacky bool isUTF16 = false; 325733956c43SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 3258f22ef01cSRoman Divacky GetConstantCFStringEntry(CFConstantStringMap, Literal, 325933956c43SDimitry Andric getDataLayout().isLittleEndian(), isUTF16, 326033956c43SDimitry Andric StringLength); 3261f22ef01cSRoman Divacky 326239d628a0SDimitry Andric if (auto *C = Entry.second) 32630623d748SDimitry Andric return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 3264f22ef01cSRoman Divacky 3265dff0c46cSDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 3266f22ef01cSRoman Divacky llvm::Constant *Zeros[] = { Zero, Zero }; 3267f22ef01cSRoman Divacky 3268f22ef01cSRoman Divacky // If we don't already have it, get __CFConstantStringClassReference. 3269f22ef01cSRoman Divacky if (!CFConstantStringClassRef) { 32706122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 3271f22ef01cSRoman Divacky Ty = llvm::ArrayType::get(Ty, 0); 3272e7145dcbSDimitry Andric llvm::Constant *GV = 3273e7145dcbSDimitry Andric CreateRuntimeVariable(Ty, "__CFConstantStringClassReference"); 3274e7145dcbSDimitry Andric 327544290647SDimitry Andric if (getTriple().isOSBinFormatCOFF()) { 3276e7145dcbSDimitry Andric IdentifierInfo &II = getContext().Idents.get(GV->getName()); 3277e7145dcbSDimitry Andric TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl(); 3278e7145dcbSDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 3279e7145dcbSDimitry Andric llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV); 3280e7145dcbSDimitry Andric 3281e7145dcbSDimitry Andric const VarDecl *VD = nullptr; 3282e7145dcbSDimitry Andric for (const auto &Result : DC->lookup(&II)) 3283e7145dcbSDimitry Andric if ((VD = dyn_cast<VarDecl>(Result))) 3284e7145dcbSDimitry Andric break; 3285e7145dcbSDimitry Andric 3286e7145dcbSDimitry Andric if (!VD || !VD->hasAttr<DLLExportAttr>()) { 3287e7145dcbSDimitry Andric CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3288e7145dcbSDimitry Andric CGV->setLinkage(llvm::GlobalValue::ExternalLinkage); 3289e7145dcbSDimitry Andric } else { 3290e7145dcbSDimitry Andric CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 3291e7145dcbSDimitry Andric CGV->setLinkage(llvm::GlobalValue::ExternalLinkage); 3292e7145dcbSDimitry Andric } 3293e7145dcbSDimitry Andric } 3294e7145dcbSDimitry Andric 3295f22ef01cSRoman Divacky // Decay array -> ptr 329644290647SDimitry Andric CFConstantStringClassRef = 329744290647SDimitry Andric llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros); 3298e7145dcbSDimitry Andric } 3299f22ef01cSRoman Divacky 3300f22ef01cSRoman Divacky QualType CFTy = getContext().getCFConstantStringType(); 3301f22ef01cSRoman Divacky 330259d1ed5bSDimitry Andric auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 3303f22ef01cSRoman Divacky 330444290647SDimitry Andric ConstantInitBuilder Builder(*this); 330544290647SDimitry Andric auto Fields = Builder.beginStruct(STy); 3306f22ef01cSRoman Divacky 3307f22ef01cSRoman Divacky // Class pointer. 330844290647SDimitry Andric Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef)); 3309f22ef01cSRoman Divacky 3310f22ef01cSRoman Divacky // Flags. 331144290647SDimitry Andric Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 3312f22ef01cSRoman Divacky 3313f22ef01cSRoman Divacky // String pointer. 331459d1ed5bSDimitry Andric llvm::Constant *C = nullptr; 3315dff0c46cSDimitry Andric if (isUTF16) { 33160623d748SDimitry Andric auto Arr = llvm::makeArrayRef( 331739d628a0SDimitry Andric reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 331839d628a0SDimitry Andric Entry.first().size() / 2); 3319dff0c46cSDimitry Andric C = llvm::ConstantDataArray::get(VMContext, Arr); 3320dff0c46cSDimitry Andric } else { 332139d628a0SDimitry Andric C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 3322dff0c46cSDimitry Andric } 3323f22ef01cSRoman Divacky 3324dff0c46cSDimitry Andric // Note: -fwritable-strings doesn't make the backing store strings of 3325dff0c46cSDimitry Andric // CFStrings writable. (See <rdar://problem/10657500>) 332659d1ed5bSDimitry Andric auto *GV = 3327dff0c46cSDimitry Andric new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 332859d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, C, ".str"); 3329e7145dcbSDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3330284c1978SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 3331284c1978SDimitry Andric // of the string is via this class initializer. 3332e7145dcbSDimitry Andric CharUnits Align = isUTF16 3333e7145dcbSDimitry Andric ? getContext().getTypeAlignInChars(getContext().ShortTy) 3334e7145dcbSDimitry Andric : getContext().getTypeAlignInChars(getContext().CharTy); 3335f22ef01cSRoman Divacky GV->setAlignment(Align.getQuantity()); 3336e7145dcbSDimitry Andric 3337e7145dcbSDimitry Andric // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 3338e7145dcbSDimitry Andric // Without it LLVM can merge the string with a non unnamed_addr one during 3339e7145dcbSDimitry Andric // LTO. Doing that changes the section it ends in, which surprises ld64. 334044290647SDimitry Andric if (getTriple().isOSBinFormatMachO()) 3341e7145dcbSDimitry Andric GV->setSection(isUTF16 ? "__TEXT,__ustring" 3342e7145dcbSDimitry Andric : "__TEXT,__cstring,cstring_literals"); 3343dff0c46cSDimitry Andric 3344dff0c46cSDimitry Andric // String. 334544290647SDimitry Andric llvm::Constant *Str = 334633956c43SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 3347f22ef01cSRoman Divacky 3348dff0c46cSDimitry Andric if (isUTF16) 3349dff0c46cSDimitry Andric // Cast the UTF16 string to the correct type. 335044290647SDimitry Andric Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 335144290647SDimitry Andric Fields.add(Str); 3352dff0c46cSDimitry Andric 3353f22ef01cSRoman Divacky // String length. 335444290647SDimitry Andric auto Ty = getTypes().ConvertType(getContext().LongTy); 335544290647SDimitry Andric Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength); 3356f22ef01cSRoman Divacky 33570623d748SDimitry Andric CharUnits Alignment = getPointerAlign(); 33580623d748SDimitry Andric 3359f22ef01cSRoman Divacky // The struct. 336044290647SDimitry Andric GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 336144290647SDimitry Andric /*isConstant=*/false, 336244290647SDimitry Andric llvm::GlobalVariable::PrivateLinkage); 336344290647SDimitry Andric switch (getTriple().getObjectFormat()) { 3364e7145dcbSDimitry Andric case llvm::Triple::UnknownObjectFormat: 3365e7145dcbSDimitry Andric llvm_unreachable("unknown file format"); 3366e7145dcbSDimitry Andric case llvm::Triple::COFF: 3367e7145dcbSDimitry Andric case llvm::Triple::ELF: 336820e90f04SDimitry Andric case llvm::Triple::Wasm: 3369e7145dcbSDimitry Andric GV->setSection("cfstring"); 3370e7145dcbSDimitry Andric break; 3371e7145dcbSDimitry Andric case llvm::Triple::MachO: 3372e7145dcbSDimitry Andric GV->setSection("__DATA,__cfstring"); 3373e7145dcbSDimitry Andric break; 3374e7145dcbSDimitry Andric } 337539d628a0SDimitry Andric Entry.second = GV; 3376f22ef01cSRoman Divacky 33770623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3378f22ef01cSRoman Divacky } 3379f22ef01cSRoman Divacky 33806122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() { 33816122f3e6SDimitry Andric if (ObjCFastEnumerationStateType.isNull()) { 338259d1ed5bSDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 33836122f3e6SDimitry Andric D->startDefinition(); 33846122f3e6SDimitry Andric 33856122f3e6SDimitry Andric QualType FieldTypes[] = { 33866122f3e6SDimitry Andric Context.UnsignedLongTy, 33876122f3e6SDimitry Andric Context.getPointerType(Context.getObjCIdType()), 33886122f3e6SDimitry Andric Context.getPointerType(Context.UnsignedLongTy), 33896122f3e6SDimitry Andric Context.getConstantArrayType(Context.UnsignedLongTy, 33906122f3e6SDimitry Andric llvm::APInt(32, 5), ArrayType::Normal, 0) 33916122f3e6SDimitry Andric }; 33926122f3e6SDimitry Andric 33936122f3e6SDimitry Andric for (size_t i = 0; i < 4; ++i) { 33946122f3e6SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, 33956122f3e6SDimitry Andric D, 33966122f3e6SDimitry Andric SourceLocation(), 339759d1ed5bSDimitry Andric SourceLocation(), nullptr, 339859d1ed5bSDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 339959d1ed5bSDimitry Andric /*BitWidth=*/nullptr, 34006122f3e6SDimitry Andric /*Mutable=*/false, 34017ae0e2c9SDimitry Andric ICIS_NoInit); 34026122f3e6SDimitry Andric Field->setAccess(AS_public); 34036122f3e6SDimitry Andric D->addDecl(Field); 34046122f3e6SDimitry Andric } 34056122f3e6SDimitry Andric 34066122f3e6SDimitry Andric D->completeDefinition(); 34076122f3e6SDimitry Andric ObjCFastEnumerationStateType = Context.getTagDeclType(D); 34086122f3e6SDimitry Andric } 34096122f3e6SDimitry Andric 34106122f3e6SDimitry Andric return ObjCFastEnumerationStateType; 34116122f3e6SDimitry Andric } 34126122f3e6SDimitry Andric 3413dff0c46cSDimitry Andric llvm::Constant * 3414dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 3415dff0c46cSDimitry Andric assert(!E->getType()->isPointerType() && "Strings are always arrays"); 3416f22ef01cSRoman Divacky 3417dff0c46cSDimitry Andric // Don't emit it as the address of the string, emit the string data itself 3418dff0c46cSDimitry Andric // as an inline array. 3419dff0c46cSDimitry Andric if (E->getCharByteWidth() == 1) { 3420dff0c46cSDimitry Andric SmallString<64> Str(E->getString()); 3421f22ef01cSRoman Divacky 3422dff0c46cSDimitry Andric // Resize the string to the right size, which is indicated by its type. 3423dff0c46cSDimitry Andric const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 3424dff0c46cSDimitry Andric Str.resize(CAT->getSize().getZExtValue()); 3425dff0c46cSDimitry Andric return llvm::ConstantDataArray::getString(VMContext, Str, false); 34266122f3e6SDimitry Andric } 3427f22ef01cSRoman Divacky 342859d1ed5bSDimitry Andric auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 3429dff0c46cSDimitry Andric llvm::Type *ElemTy = AType->getElementType(); 3430dff0c46cSDimitry Andric unsigned NumElements = AType->getNumElements(); 3431f22ef01cSRoman Divacky 3432dff0c46cSDimitry Andric // Wide strings have either 2-byte or 4-byte elements. 3433dff0c46cSDimitry Andric if (ElemTy->getPrimitiveSizeInBits() == 16) { 3434dff0c46cSDimitry Andric SmallVector<uint16_t, 32> Elements; 3435dff0c46cSDimitry Andric Elements.reserve(NumElements); 3436dff0c46cSDimitry Andric 3437dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3438dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 3439dff0c46cSDimitry Andric Elements.resize(NumElements); 3440dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 3441dff0c46cSDimitry Andric } 3442dff0c46cSDimitry Andric 3443dff0c46cSDimitry Andric assert(ElemTy->getPrimitiveSizeInBits() == 32); 3444dff0c46cSDimitry Andric SmallVector<uint32_t, 32> Elements; 3445dff0c46cSDimitry Andric Elements.reserve(NumElements); 3446dff0c46cSDimitry Andric 3447dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3448dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 3449dff0c46cSDimitry Andric Elements.resize(NumElements); 3450dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 3451f22ef01cSRoman Divacky } 3452f22ef01cSRoman Divacky 345359d1ed5bSDimitry Andric static llvm::GlobalVariable * 345459d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 345559d1ed5bSDimitry Andric CodeGenModule &CGM, StringRef GlobalName, 34560623d748SDimitry Andric CharUnits Alignment) { 345759d1ed5bSDimitry Andric // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 345859d1ed5bSDimitry Andric unsigned AddrSpace = 0; 345959d1ed5bSDimitry Andric if (CGM.getLangOpts().OpenCL) 346059d1ed5bSDimitry Andric AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 3461dff0c46cSDimitry Andric 346233956c43SDimitry Andric llvm::Module &M = CGM.getModule(); 346359d1ed5bSDimitry Andric // Create a global variable for this string 346459d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 346533956c43SDimitry Andric M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 346633956c43SDimitry Andric nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 34670623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 3468e7145dcbSDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 346933956c43SDimitry Andric if (GV->isWeakForLinker()) { 347033956c43SDimitry Andric assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 347133956c43SDimitry Andric GV->setComdat(M.getOrInsertComdat(GV->getName())); 347233956c43SDimitry Andric } 347333956c43SDimitry Andric 347459d1ed5bSDimitry Andric return GV; 3475f22ef01cSRoman Divacky } 3476dff0c46cSDimitry Andric 347759d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 347859d1ed5bSDimitry Andric /// constant array for the given string literal. 34790623d748SDimitry Andric ConstantAddress 348039d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 348139d628a0SDimitry Andric StringRef Name) { 34820623d748SDimitry Andric CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 3483dff0c46cSDimitry Andric 348459d1ed5bSDimitry Andric llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 348559d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 348659d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 348759d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 348859d1ed5bSDimitry Andric if (auto GV = *Entry) { 34890623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 34900623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 34910623d748SDimitry Andric return ConstantAddress(GV, Alignment); 349259d1ed5bSDimitry Andric } 349359d1ed5bSDimitry Andric } 349459d1ed5bSDimitry Andric 349559d1ed5bSDimitry Andric SmallString<256> MangledNameBuffer; 349659d1ed5bSDimitry Andric StringRef GlobalVariableName; 349759d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes LT; 349859d1ed5bSDimitry Andric 349959d1ed5bSDimitry Andric // Mangle the string literal if the ABI allows for it. However, we cannot 350059d1ed5bSDimitry Andric // do this if we are compiling with ASan or -fwritable-strings because they 350159d1ed5bSDimitry Andric // rely on strings having normal linkage. 350239d628a0SDimitry Andric if (!LangOpts.WritableStrings && 350339d628a0SDimitry Andric !LangOpts.Sanitize.has(SanitizerKind::Address) && 350459d1ed5bSDimitry Andric getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { 350559d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(MangledNameBuffer); 350659d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 350759d1ed5bSDimitry Andric 350859d1ed5bSDimitry Andric LT = llvm::GlobalValue::LinkOnceODRLinkage; 350959d1ed5bSDimitry Andric GlobalVariableName = MangledNameBuffer; 351059d1ed5bSDimitry Andric } else { 351159d1ed5bSDimitry Andric LT = llvm::GlobalValue::PrivateLinkage; 351239d628a0SDimitry Andric GlobalVariableName = Name; 351359d1ed5bSDimitry Andric } 351459d1ed5bSDimitry Andric 351559d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 351659d1ed5bSDimitry Andric if (Entry) 351759d1ed5bSDimitry Andric *Entry = GV; 351859d1ed5bSDimitry Andric 351939d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 352039d628a0SDimitry Andric QualType()); 35210623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3522f22ef01cSRoman Divacky } 3523f22ef01cSRoman Divacky 3524f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 3525f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node. 35260623d748SDimitry Andric ConstantAddress 3527f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 3528f22ef01cSRoman Divacky std::string Str; 3529f22ef01cSRoman Divacky getContext().getObjCEncodingForType(E->getEncodedType(), Str); 3530f22ef01cSRoman Divacky 3531f22ef01cSRoman Divacky return GetAddrOfConstantCString(Str); 3532f22ef01cSRoman Divacky } 3533f22ef01cSRoman Divacky 353459d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing 353559d1ed5bSDimitry Andric /// the literal and a terminating '\0' character. 353659d1ed5bSDimitry Andric /// The result has pointer to array type. 35370623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString( 35380623d748SDimitry Andric const std::string &Str, const char *GlobalName) { 353959d1ed5bSDimitry Andric StringRef StrWithNull(Str.c_str(), Str.size() + 1); 35400623d748SDimitry Andric CharUnits Alignment = 35410623d748SDimitry Andric getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 3542f22ef01cSRoman Divacky 354359d1ed5bSDimitry Andric llvm::Constant *C = 354459d1ed5bSDimitry Andric llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 354559d1ed5bSDimitry Andric 354659d1ed5bSDimitry Andric // Don't share any string literals if strings aren't constant. 354759d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 354859d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 354959d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 355059d1ed5bSDimitry Andric if (auto GV = *Entry) { 35510623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 35520623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 35530623d748SDimitry Andric return ConstantAddress(GV, Alignment); 355459d1ed5bSDimitry Andric } 355559d1ed5bSDimitry Andric } 355659d1ed5bSDimitry Andric 3557f22ef01cSRoman Divacky // Get the default prefix if a name wasn't specified. 3558f22ef01cSRoman Divacky if (!GlobalName) 3559f22ef01cSRoman Divacky GlobalName = ".str"; 3560f22ef01cSRoman Divacky // Create a global variable for this. 356159d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 356259d1ed5bSDimitry Andric GlobalName, Alignment); 356359d1ed5bSDimitry Andric if (Entry) 356459d1ed5bSDimitry Andric *Entry = GV; 35650623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3566f22ef01cSRoman Divacky } 3567f22ef01cSRoman Divacky 35680623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 3569f785676fSDimitry Andric const MaterializeTemporaryExpr *E, const Expr *Init) { 3570f785676fSDimitry Andric assert((E->getStorageDuration() == SD_Static || 3571f785676fSDimitry Andric E->getStorageDuration() == SD_Thread) && "not a global temporary"); 357259d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 3573f785676fSDimitry Andric 3574f785676fSDimitry Andric // If we're not materializing a subobject of the temporary, keep the 3575f785676fSDimitry Andric // cv-qualifiers from the type of the MaterializeTemporaryExpr. 3576f785676fSDimitry Andric QualType MaterializedType = Init->getType(); 3577f785676fSDimitry Andric if (Init == E->GetTemporaryExpr()) 3578f785676fSDimitry Andric MaterializedType = E->getType(); 3579f785676fSDimitry Andric 35800623d748SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 35810623d748SDimitry Andric 35820623d748SDimitry Andric if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E]) 35830623d748SDimitry Andric return ConstantAddress(Slot, Align); 3584f785676fSDimitry Andric 3585f785676fSDimitry Andric // FIXME: If an externally-visible declaration extends multiple temporaries, 3586f785676fSDimitry Andric // we need to give each temporary the same name in every translation unit (and 3587f785676fSDimitry Andric // we also need to make the temporaries externally-visible). 3588f785676fSDimitry Andric SmallString<256> Name; 3589f785676fSDimitry Andric llvm::raw_svector_ostream Out(Name); 359059d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleReferenceTemporary( 359159d1ed5bSDimitry Andric VD, E->getManglingNumber(), Out); 3592f785676fSDimitry Andric 359359d1ed5bSDimitry Andric APValue *Value = nullptr; 3594f785676fSDimitry Andric if (E->getStorageDuration() == SD_Static) { 3595f785676fSDimitry Andric // We might have a cached constant initializer for this temporary. Note 3596f785676fSDimitry Andric // that this might have a different value from the value computed by 3597f785676fSDimitry Andric // evaluating the initializer if the surrounding constant expression 3598f785676fSDimitry Andric // modifies the temporary. 3599f785676fSDimitry Andric Value = getContext().getMaterializedTemporaryValue(E, false); 3600f785676fSDimitry Andric if (Value && Value->isUninit()) 360159d1ed5bSDimitry Andric Value = nullptr; 3602f785676fSDimitry Andric } 3603f785676fSDimitry Andric 3604f785676fSDimitry Andric // Try evaluating it now, it might have a constant initializer. 3605f785676fSDimitry Andric Expr::EvalResult EvalResult; 3606f785676fSDimitry Andric if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 3607f785676fSDimitry Andric !EvalResult.hasSideEffects()) 3608f785676fSDimitry Andric Value = &EvalResult.Val; 3609f785676fSDimitry Andric 361059d1ed5bSDimitry Andric llvm::Constant *InitialValue = nullptr; 3611f785676fSDimitry Andric bool Constant = false; 3612f785676fSDimitry Andric llvm::Type *Type; 3613f785676fSDimitry Andric if (Value) { 3614f785676fSDimitry Andric // The temporary has a constant initializer, use it. 361559d1ed5bSDimitry Andric InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr); 3616f785676fSDimitry Andric Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 3617f785676fSDimitry Andric Type = InitialValue->getType(); 3618f785676fSDimitry Andric } else { 3619f785676fSDimitry Andric // No initializer, the initialization will be provided when we 3620f785676fSDimitry Andric // initialize the declaration which performed lifetime extension. 3621f785676fSDimitry Andric Type = getTypes().ConvertTypeForMem(MaterializedType); 3622f785676fSDimitry Andric } 3623f785676fSDimitry Andric 3624f785676fSDimitry Andric // Create a global variable for this lifetime-extended temporary. 362559d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 362659d1ed5bSDimitry Andric getLLVMLinkageVarDefinition(VD, Constant); 362733956c43SDimitry Andric if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 362833956c43SDimitry Andric const VarDecl *InitVD; 362933956c43SDimitry Andric if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 363033956c43SDimitry Andric isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 363133956c43SDimitry Andric // Temporaries defined inside a class get linkonce_odr linkage because the 363233956c43SDimitry Andric // class can be defined in multipe translation units. 363333956c43SDimitry Andric Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 363433956c43SDimitry Andric } else { 363533956c43SDimitry Andric // There is no need for this temporary to have external linkage if the 363633956c43SDimitry Andric // VarDecl has external linkage. 363733956c43SDimitry Andric Linkage = llvm::GlobalVariable::InternalLinkage; 363833956c43SDimitry Andric } 363933956c43SDimitry Andric } 364059d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace( 364159d1ed5bSDimitry Andric VD, getContext().getTargetAddressSpace(MaterializedType)); 364259d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 364359d1ed5bSDimitry Andric getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 364459d1ed5bSDimitry Andric /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, 364559d1ed5bSDimitry Andric AddrSpace); 364659d1ed5bSDimitry Andric setGlobalVisibility(GV, VD); 36470623d748SDimitry Andric GV->setAlignment(Align.getQuantity()); 364833956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker()) 364933956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3650f785676fSDimitry Andric if (VD->getTLSKind()) 3651f785676fSDimitry Andric setTLSMode(GV, *VD); 36520623d748SDimitry Andric MaterializedGlobalTemporaryMap[E] = GV; 36530623d748SDimitry Andric return ConstantAddress(GV, Align); 3654f785676fSDimitry Andric } 3655f785676fSDimitry Andric 3656f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized 3657f22ef01cSRoman Divacky /// properties for an implementation. 3658f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const 3659f22ef01cSRoman Divacky ObjCImplementationDecl *D) { 366059d1ed5bSDimitry Andric for (const auto *PID : D->property_impls()) { 3661f22ef01cSRoman Divacky // Dynamic is just for type-checking. 3662f22ef01cSRoman Divacky if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 3663f22ef01cSRoman Divacky ObjCPropertyDecl *PD = PID->getPropertyDecl(); 3664f22ef01cSRoman Divacky 3665f22ef01cSRoman Divacky // Determine which methods need to be implemented, some may have 36663861d79fSDimitry Andric // been overridden. Note that ::isPropertyAccessor is not the method 3667f22ef01cSRoman Divacky // we want, that just indicates if the decl came from a 3668f22ef01cSRoman Divacky // property. What we want to know is if the method is defined in 3669f22ef01cSRoman Divacky // this implementation. 3670f22ef01cSRoman Divacky if (!D->getInstanceMethod(PD->getGetterName())) 3671f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCGetter( 3672f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3673f22ef01cSRoman Divacky if (!PD->isReadOnly() && 3674f22ef01cSRoman Divacky !D->getInstanceMethod(PD->getSetterName())) 3675f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCSetter( 3676f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3677f22ef01cSRoman Divacky } 3678f22ef01cSRoman Divacky } 3679f22ef01cSRoman Divacky } 3680f22ef01cSRoman Divacky 36813b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) { 36826122f3e6SDimitry Andric const ObjCInterfaceDecl *iface = impl->getClassInterface(); 36836122f3e6SDimitry Andric for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 36843b0f4066SDimitry Andric ivar; ivar = ivar->getNextIvar()) 36853b0f4066SDimitry Andric if (ivar->getType().isDestructedType()) 36863b0f4066SDimitry Andric return true; 36873b0f4066SDimitry Andric 36883b0f4066SDimitry Andric return false; 36893b0f4066SDimitry Andric } 36903b0f4066SDimitry Andric 369139d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM, 369239d628a0SDimitry Andric ObjCImplementationDecl *D) { 369339d628a0SDimitry Andric CodeGenFunction CGF(CGM); 369439d628a0SDimitry Andric for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 369539d628a0SDimitry Andric E = D->init_end(); B != E; ++B) { 369639d628a0SDimitry Andric CXXCtorInitializer *CtorInitExp = *B; 369739d628a0SDimitry Andric Expr *Init = CtorInitExp->getInit(); 369839d628a0SDimitry Andric if (!CGF.isTrivialInitializer(Init)) 369939d628a0SDimitry Andric return false; 370039d628a0SDimitry Andric } 370139d628a0SDimitry Andric return true; 370239d628a0SDimitry Andric } 370339d628a0SDimitry Andric 3704f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization 3705f22ef01cSRoman Divacky /// for an implementation. 3706f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 37073b0f4066SDimitry Andric // We might need a .cxx_destruct even if we don't have any ivar initializers. 37083b0f4066SDimitry Andric if (needsDestructMethod(D)) { 3709f22ef01cSRoman Divacky IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 3710f22ef01cSRoman Divacky Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 37113b0f4066SDimitry Andric ObjCMethodDecl *DTORMethod = 37123b0f4066SDimitry Andric ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 371359d1ed5bSDimitry Andric cxxSelector, getContext().VoidTy, nullptr, D, 37146122f3e6SDimitry Andric /*isInstance=*/true, /*isVariadic=*/false, 37153861d79fSDimitry Andric /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 37166122f3e6SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 3717f22ef01cSRoman Divacky D->addInstanceMethod(DTORMethod); 3718f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 37193861d79fSDimitry Andric D->setHasDestructors(true); 37203b0f4066SDimitry Andric } 3721f22ef01cSRoman Divacky 37223b0f4066SDimitry Andric // If the implementation doesn't have any ivar initializers, we don't need 37233b0f4066SDimitry Andric // a .cxx_construct. 372439d628a0SDimitry Andric if (D->getNumIvarInitializers() == 0 || 372539d628a0SDimitry Andric AllTrivialInitializers(*this, D)) 37263b0f4066SDimitry Andric return; 37273b0f4066SDimitry Andric 37283b0f4066SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 37293b0f4066SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 3730f22ef01cSRoman Divacky // The constructor returns 'self'. 3731f22ef01cSRoman Divacky ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 3732f22ef01cSRoman Divacky D->getLocation(), 37336122f3e6SDimitry Andric D->getLocation(), 37346122f3e6SDimitry Andric cxxSelector, 373559d1ed5bSDimitry Andric getContext().getObjCIdType(), 373659d1ed5bSDimitry Andric nullptr, D, /*isInstance=*/true, 37376122f3e6SDimitry Andric /*isVariadic=*/false, 37383861d79fSDimitry Andric /*isPropertyAccessor=*/true, 37396122f3e6SDimitry Andric /*isImplicitlyDeclared=*/true, 37406122f3e6SDimitry Andric /*isDefined=*/false, 3741f22ef01cSRoman Divacky ObjCMethodDecl::Required); 3742f22ef01cSRoman Divacky D->addInstanceMethod(CTORMethod); 3743f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 37443861d79fSDimitry Andric D->setHasNonZeroConstructors(true); 3745f22ef01cSRoman Divacky } 3746f22ef01cSRoman Divacky 3747f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec. 3748f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 3749f22ef01cSRoman Divacky if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 3750f22ef01cSRoman Divacky LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 3751f22ef01cSRoman Divacky ErrorUnsupported(LSD, "linkage spec"); 3752f22ef01cSRoman Divacky return; 3753f22ef01cSRoman Divacky } 3754f22ef01cSRoman Divacky 375544290647SDimitry Andric EmitDeclContext(LSD); 375644290647SDimitry Andric } 375744290647SDimitry Andric 375844290647SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 375944290647SDimitry Andric for (auto *I : DC->decls()) { 376044290647SDimitry Andric // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 376144290647SDimitry Andric // are themselves considered "top-level", so EmitTopLevelDecl on an 376244290647SDimitry Andric // ObjCImplDecl does not recursively visit them. We need to do that in 376344290647SDimitry Andric // case they're nested inside another construct (LinkageSpecDecl / 376444290647SDimitry Andric // ExportDecl) that does stop them from being considered "top-level". 376559d1ed5bSDimitry Andric if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 376659d1ed5bSDimitry Andric for (auto *M : OID->methods()) 376759d1ed5bSDimitry Andric EmitTopLevelDecl(M); 37683861d79fSDimitry Andric } 376944290647SDimitry Andric 377059d1ed5bSDimitry Andric EmitTopLevelDecl(I); 3771f22ef01cSRoman Divacky } 37723861d79fSDimitry Andric } 3773f22ef01cSRoman Divacky 3774f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration. 3775f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) { 3776f22ef01cSRoman Divacky // Ignore dependent declarations. 3777f22ef01cSRoman Divacky if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 3778f22ef01cSRoman Divacky return; 3779f22ef01cSRoman Divacky 3780f22ef01cSRoman Divacky switch (D->getKind()) { 3781f22ef01cSRoman Divacky case Decl::CXXConversion: 3782f22ef01cSRoman Divacky case Decl::CXXMethod: 3783f22ef01cSRoman Divacky case Decl::Function: 3784f22ef01cSRoman Divacky // Skip function templates 37853b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 37863b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3787f22ef01cSRoman Divacky return; 3788f22ef01cSRoman Divacky 3789f22ef01cSRoman Divacky EmitGlobal(cast<FunctionDecl>(D)); 379039d628a0SDimitry Andric // Always provide some coverage mapping 379139d628a0SDimitry Andric // even for the functions that aren't emitted. 379239d628a0SDimitry Andric AddDeferredUnusedCoverageMapping(D); 3793f22ef01cSRoman Divacky break; 3794f22ef01cSRoman Divacky 37956bc11b14SDimitry Andric case Decl::CXXDeductionGuide: 37966bc11b14SDimitry Andric // Function-like, but does not result in code emission. 37976bc11b14SDimitry Andric break; 37986bc11b14SDimitry Andric 3799f22ef01cSRoman Divacky case Decl::Var: 380044290647SDimitry Andric case Decl::Decomposition: 3801f785676fSDimitry Andric // Skip variable templates 3802f785676fSDimitry Andric if (cast<VarDecl>(D)->getDescribedVarTemplate()) 3803f785676fSDimitry Andric return; 3804f785676fSDimitry Andric case Decl::VarTemplateSpecialization: 3805f22ef01cSRoman Divacky EmitGlobal(cast<VarDecl>(D)); 380644290647SDimitry Andric if (auto *DD = dyn_cast<DecompositionDecl>(D)) 380744290647SDimitry Andric for (auto *B : DD->bindings()) 380844290647SDimitry Andric if (auto *HD = B->getHoldingVar()) 380944290647SDimitry Andric EmitGlobal(HD); 3810f22ef01cSRoman Divacky break; 3811f22ef01cSRoman Divacky 38123b0f4066SDimitry Andric // Indirect fields from global anonymous structs and unions can be 38133b0f4066SDimitry Andric // ignored; only the actual variable requires IR gen support. 38143b0f4066SDimitry Andric case Decl::IndirectField: 38153b0f4066SDimitry Andric break; 38163b0f4066SDimitry Andric 3817f22ef01cSRoman Divacky // C++ Decls 3818f22ef01cSRoman Divacky case Decl::Namespace: 381944290647SDimitry Andric EmitDeclContext(cast<NamespaceDecl>(D)); 3820f22ef01cSRoman Divacky break; 3821e7145dcbSDimitry Andric case Decl::CXXRecord: 382220e90f04SDimitry Andric if (DebugInfo) { 382320e90f04SDimitry Andric if (auto *ES = D->getASTContext().getExternalSource()) 382420e90f04SDimitry Andric if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 382520e90f04SDimitry Andric DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D)); 382620e90f04SDimitry Andric } 3827e7145dcbSDimitry Andric // Emit any static data members, they may be definitions. 3828e7145dcbSDimitry Andric for (auto *I : cast<CXXRecordDecl>(D)->decls()) 3829e7145dcbSDimitry Andric if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 3830e7145dcbSDimitry Andric EmitTopLevelDecl(I); 3831e7145dcbSDimitry Andric break; 3832f22ef01cSRoman Divacky // No code generation needed. 3833f22ef01cSRoman Divacky case Decl::UsingShadow: 3834f22ef01cSRoman Divacky case Decl::ClassTemplate: 3835f785676fSDimitry Andric case Decl::VarTemplate: 3836f785676fSDimitry Andric case Decl::VarTemplatePartialSpecialization: 3837f22ef01cSRoman Divacky case Decl::FunctionTemplate: 3838bd5abe19SDimitry Andric case Decl::TypeAliasTemplate: 3839bd5abe19SDimitry Andric case Decl::Block: 3840139f7f9bSDimitry Andric case Decl::Empty: 3841f22ef01cSRoman Divacky break; 384259d1ed5bSDimitry Andric case Decl::Using: // using X; [C++] 384359d1ed5bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 384459d1ed5bSDimitry Andric DI->EmitUsingDecl(cast<UsingDecl>(*D)); 384559d1ed5bSDimitry Andric return; 3846f785676fSDimitry Andric case Decl::NamespaceAlias: 3847f785676fSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3848f785676fSDimitry Andric DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 3849f785676fSDimitry Andric return; 3850284c1978SDimitry Andric case Decl::UsingDirective: // using namespace X; [C++] 3851284c1978SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3852284c1978SDimitry Andric DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 3853284c1978SDimitry Andric return; 3854f22ef01cSRoman Divacky case Decl::CXXConstructor: 3855f22ef01cSRoman Divacky // Skip function templates 38563b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 38573b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3858f22ef01cSRoman Divacky return; 3859f22ef01cSRoman Divacky 3860f785676fSDimitry Andric getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 3861f22ef01cSRoman Divacky break; 3862f22ef01cSRoman Divacky case Decl::CXXDestructor: 38633b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 38643b0f4066SDimitry Andric return; 3865f785676fSDimitry Andric getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 3866f22ef01cSRoman Divacky break; 3867f22ef01cSRoman Divacky 3868f22ef01cSRoman Divacky case Decl::StaticAssert: 3869f22ef01cSRoman Divacky // Nothing to do. 3870f22ef01cSRoman Divacky break; 3871f22ef01cSRoman Divacky 3872f22ef01cSRoman Divacky // Objective-C Decls 3873f22ef01cSRoman Divacky 3874f22ef01cSRoman Divacky // Forward declarations, no (immediate) code generation. 3875f22ef01cSRoman Divacky case Decl::ObjCInterface: 38767ae0e2c9SDimitry Andric case Decl::ObjCCategory: 3877f22ef01cSRoman Divacky break; 3878f22ef01cSRoman Divacky 3879dff0c46cSDimitry Andric case Decl::ObjCProtocol: { 388059d1ed5bSDimitry Andric auto *Proto = cast<ObjCProtocolDecl>(D); 3881dff0c46cSDimitry Andric if (Proto->isThisDeclarationADefinition()) 3882dff0c46cSDimitry Andric ObjCRuntime->GenerateProtocol(Proto); 3883f22ef01cSRoman Divacky break; 3884dff0c46cSDimitry Andric } 3885f22ef01cSRoman Divacky 3886f22ef01cSRoman Divacky case Decl::ObjCCategoryImpl: 3887f22ef01cSRoman Divacky // Categories have properties but don't support synthesize so we 3888f22ef01cSRoman Divacky // can ignore them here. 38896122f3e6SDimitry Andric ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 3890f22ef01cSRoman Divacky break; 3891f22ef01cSRoman Divacky 3892f22ef01cSRoman Divacky case Decl::ObjCImplementation: { 389359d1ed5bSDimitry Andric auto *OMD = cast<ObjCImplementationDecl>(D); 3894f22ef01cSRoman Divacky EmitObjCPropertyImplementations(OMD); 3895f22ef01cSRoman Divacky EmitObjCIvarInitializations(OMD); 38966122f3e6SDimitry Andric ObjCRuntime->GenerateClass(OMD); 3897dff0c46cSDimitry Andric // Emit global variable debug information. 3898dff0c46cSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3899e7145dcbSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 3900139f7f9bSDimitry Andric DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 3901139f7f9bSDimitry Andric OMD->getClassInterface()), OMD->getLocation()); 3902f22ef01cSRoman Divacky break; 3903f22ef01cSRoman Divacky } 3904f22ef01cSRoman Divacky case Decl::ObjCMethod: { 390559d1ed5bSDimitry Andric auto *OMD = cast<ObjCMethodDecl>(D); 3906f22ef01cSRoman Divacky // If this is not a prototype, emit the body. 3907f22ef01cSRoman Divacky if (OMD->getBody()) 3908f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCMethod(OMD); 3909f22ef01cSRoman Divacky break; 3910f22ef01cSRoman Divacky } 3911f22ef01cSRoman Divacky case Decl::ObjCCompatibleAlias: 3912dff0c46cSDimitry Andric ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 3913f22ef01cSRoman Divacky break; 3914f22ef01cSRoman Divacky 3915e7145dcbSDimitry Andric case Decl::PragmaComment: { 3916e7145dcbSDimitry Andric const auto *PCD = cast<PragmaCommentDecl>(D); 3917e7145dcbSDimitry Andric switch (PCD->getCommentKind()) { 3918e7145dcbSDimitry Andric case PCK_Unknown: 3919e7145dcbSDimitry Andric llvm_unreachable("unexpected pragma comment kind"); 3920e7145dcbSDimitry Andric case PCK_Linker: 3921e7145dcbSDimitry Andric AppendLinkerOptions(PCD->getArg()); 3922e7145dcbSDimitry Andric break; 3923e7145dcbSDimitry Andric case PCK_Lib: 3924e7145dcbSDimitry Andric AddDependentLib(PCD->getArg()); 3925e7145dcbSDimitry Andric break; 3926e7145dcbSDimitry Andric case PCK_Compiler: 3927e7145dcbSDimitry Andric case PCK_ExeStr: 3928e7145dcbSDimitry Andric case PCK_User: 3929e7145dcbSDimitry Andric break; // We ignore all of these. 3930e7145dcbSDimitry Andric } 3931e7145dcbSDimitry Andric break; 3932e7145dcbSDimitry Andric } 3933e7145dcbSDimitry Andric 3934e7145dcbSDimitry Andric case Decl::PragmaDetectMismatch: { 3935e7145dcbSDimitry Andric const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 3936e7145dcbSDimitry Andric AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 3937e7145dcbSDimitry Andric break; 3938e7145dcbSDimitry Andric } 3939e7145dcbSDimitry Andric 3940f22ef01cSRoman Divacky case Decl::LinkageSpec: 3941f22ef01cSRoman Divacky EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 3942f22ef01cSRoman Divacky break; 3943f22ef01cSRoman Divacky 3944f22ef01cSRoman Divacky case Decl::FileScopeAsm: { 394533956c43SDimitry Andric // File-scope asm is ignored during device-side CUDA compilation. 394633956c43SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 394733956c43SDimitry Andric break; 3948ea942507SDimitry Andric // File-scope asm is ignored during device-side OpenMP compilation. 3949ea942507SDimitry Andric if (LangOpts.OpenMPIsDevice) 3950ea942507SDimitry Andric break; 395159d1ed5bSDimitry Andric auto *AD = cast<FileScopeAsmDecl>(D); 395233956c43SDimitry Andric getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 3953f22ef01cSRoman Divacky break; 3954f22ef01cSRoman Divacky } 3955f22ef01cSRoman Divacky 3956139f7f9bSDimitry Andric case Decl::Import: { 395759d1ed5bSDimitry Andric auto *Import = cast<ImportDecl>(D); 3958139f7f9bSDimitry Andric 395944290647SDimitry Andric // If we've already imported this module, we're done. 396044290647SDimitry Andric if (!ImportedModules.insert(Import->getImportedModule())) 3961139f7f9bSDimitry Andric break; 396244290647SDimitry Andric 396344290647SDimitry Andric // Emit debug information for direct imports. 396444290647SDimitry Andric if (!Import->getImportedOwningModule()) { 39653dac3a9bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 39663dac3a9bSDimitry Andric DI->EmitImportDecl(*Import); 396744290647SDimitry Andric } 3968139f7f9bSDimitry Andric 396944290647SDimitry Andric // Find all of the submodules and emit the module initializers. 397044290647SDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 397144290647SDimitry Andric SmallVector<clang::Module *, 16> Stack; 397244290647SDimitry Andric Visited.insert(Import->getImportedModule()); 397344290647SDimitry Andric Stack.push_back(Import->getImportedModule()); 397444290647SDimitry Andric 397544290647SDimitry Andric while (!Stack.empty()) { 397644290647SDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 397744290647SDimitry Andric if (!EmittedModuleInitializers.insert(Mod).second) 397844290647SDimitry Andric continue; 397944290647SDimitry Andric 398044290647SDimitry Andric for (auto *D : Context.getModuleInitializers(Mod)) 398144290647SDimitry Andric EmitTopLevelDecl(D); 398244290647SDimitry Andric 398344290647SDimitry Andric // Visit the submodules of this module. 398444290647SDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 398544290647SDimitry Andric SubEnd = Mod->submodule_end(); 398644290647SDimitry Andric Sub != SubEnd; ++Sub) { 398744290647SDimitry Andric // Skip explicit children; they need to be explicitly imported to emit 398844290647SDimitry Andric // the initializers. 398944290647SDimitry Andric if ((*Sub)->IsExplicit) 399044290647SDimitry Andric continue; 399144290647SDimitry Andric 399244290647SDimitry Andric if (Visited.insert(*Sub).second) 399344290647SDimitry Andric Stack.push_back(*Sub); 399444290647SDimitry Andric } 399544290647SDimitry Andric } 3996139f7f9bSDimitry Andric break; 3997139f7f9bSDimitry Andric } 3998139f7f9bSDimitry Andric 399944290647SDimitry Andric case Decl::Export: 400044290647SDimitry Andric EmitDeclContext(cast<ExportDecl>(D)); 400144290647SDimitry Andric break; 400244290647SDimitry Andric 400339d628a0SDimitry Andric case Decl::OMPThreadPrivate: 400439d628a0SDimitry Andric EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 400539d628a0SDimitry Andric break; 400639d628a0SDimitry Andric 400759d1ed5bSDimitry Andric case Decl::ClassTemplateSpecialization: { 400859d1ed5bSDimitry Andric const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 400959d1ed5bSDimitry Andric if (DebugInfo && 401039d628a0SDimitry Andric Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition && 401139d628a0SDimitry Andric Spec->hasDefinition()) 401259d1ed5bSDimitry Andric DebugInfo->completeTemplateDefinition(*Spec); 401339d628a0SDimitry Andric break; 401459d1ed5bSDimitry Andric } 401559d1ed5bSDimitry Andric 4016e7145dcbSDimitry Andric case Decl::OMPDeclareReduction: 4017e7145dcbSDimitry Andric EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 4018e7145dcbSDimitry Andric break; 4019e7145dcbSDimitry Andric 4020f22ef01cSRoman Divacky default: 4021f22ef01cSRoman Divacky // Make sure we handled everything we should, every other kind is a 4022f22ef01cSRoman Divacky // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 4023f22ef01cSRoman Divacky // function. Need to recode Decl::Kind to do that easily. 4024f22ef01cSRoman Divacky assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 402539d628a0SDimitry Andric break; 402639d628a0SDimitry Andric } 402739d628a0SDimitry Andric } 402839d628a0SDimitry Andric 402939d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 403039d628a0SDimitry Andric // Do we need to generate coverage mapping? 403139d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 403239d628a0SDimitry Andric return; 403339d628a0SDimitry Andric switch (D->getKind()) { 403439d628a0SDimitry Andric case Decl::CXXConversion: 403539d628a0SDimitry Andric case Decl::CXXMethod: 403639d628a0SDimitry Andric case Decl::Function: 403739d628a0SDimitry Andric case Decl::ObjCMethod: 403839d628a0SDimitry Andric case Decl::CXXConstructor: 403939d628a0SDimitry Andric case Decl::CXXDestructor: { 40400623d748SDimitry Andric if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 404139d628a0SDimitry Andric return; 404239d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 404339d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 404439d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = true; 404539d628a0SDimitry Andric break; 404639d628a0SDimitry Andric } 404739d628a0SDimitry Andric default: 404839d628a0SDimitry Andric break; 404939d628a0SDimitry Andric }; 405039d628a0SDimitry Andric } 405139d628a0SDimitry Andric 405239d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 405339d628a0SDimitry Andric // Do we need to generate coverage mapping? 405439d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 405539d628a0SDimitry Andric return; 405639d628a0SDimitry Andric if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 405739d628a0SDimitry Andric if (Fn->isTemplateInstantiation()) 405839d628a0SDimitry Andric ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 405939d628a0SDimitry Andric } 406039d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 406139d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 406239d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = false; 406339d628a0SDimitry Andric else 406439d628a0SDimitry Andric I->second = false; 406539d628a0SDimitry Andric } 406639d628a0SDimitry Andric 406739d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 406839d628a0SDimitry Andric std::vector<const Decl *> DeferredDecls; 406933956c43SDimitry Andric for (const auto &I : DeferredEmptyCoverageMappingDecls) { 407039d628a0SDimitry Andric if (!I.second) 407139d628a0SDimitry Andric continue; 407239d628a0SDimitry Andric DeferredDecls.push_back(I.first); 407339d628a0SDimitry Andric } 407439d628a0SDimitry Andric // Sort the declarations by their location to make sure that the tests get a 407539d628a0SDimitry Andric // predictable order for the coverage mapping for the unused declarations. 407639d628a0SDimitry Andric if (CodeGenOpts.DumpCoverageMapping) 407739d628a0SDimitry Andric std::sort(DeferredDecls.begin(), DeferredDecls.end(), 407839d628a0SDimitry Andric [] (const Decl *LHS, const Decl *RHS) { 407939d628a0SDimitry Andric return LHS->getLocStart() < RHS->getLocStart(); 408039d628a0SDimitry Andric }); 408139d628a0SDimitry Andric for (const auto *D : DeferredDecls) { 408239d628a0SDimitry Andric switch (D->getKind()) { 408339d628a0SDimitry Andric case Decl::CXXConversion: 408439d628a0SDimitry Andric case Decl::CXXMethod: 408539d628a0SDimitry Andric case Decl::Function: 408639d628a0SDimitry Andric case Decl::ObjCMethod: { 408739d628a0SDimitry Andric CodeGenPGO PGO(*this); 408839d628a0SDimitry Andric GlobalDecl GD(cast<FunctionDecl>(D)); 408939d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 409039d628a0SDimitry Andric getFunctionLinkage(GD)); 409139d628a0SDimitry Andric break; 409239d628a0SDimitry Andric } 409339d628a0SDimitry Andric case Decl::CXXConstructor: { 409439d628a0SDimitry Andric CodeGenPGO PGO(*this); 409539d628a0SDimitry Andric GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 409639d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 409739d628a0SDimitry Andric getFunctionLinkage(GD)); 409839d628a0SDimitry Andric break; 409939d628a0SDimitry Andric } 410039d628a0SDimitry Andric case Decl::CXXDestructor: { 410139d628a0SDimitry Andric CodeGenPGO PGO(*this); 410239d628a0SDimitry Andric GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 410339d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 410439d628a0SDimitry Andric getFunctionLinkage(GD)); 410539d628a0SDimitry Andric break; 410639d628a0SDimitry Andric } 410739d628a0SDimitry Andric default: 410839d628a0SDimitry Andric break; 410939d628a0SDimitry Andric }; 4110f22ef01cSRoman Divacky } 4111f22ef01cSRoman Divacky } 4112ffd1746dSEd Schouten 4113ffd1746dSEd Schouten /// Turns the given pointer into a constant. 4114ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 4115ffd1746dSEd Schouten const void *Ptr) { 4116ffd1746dSEd Schouten uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 41176122f3e6SDimitry Andric llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 4118ffd1746dSEd Schouten return llvm::ConstantInt::get(i64, PtrInt); 4119ffd1746dSEd Schouten } 4120ffd1746dSEd Schouten 4121ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 4122ffd1746dSEd Schouten llvm::NamedMDNode *&GlobalMetadata, 4123ffd1746dSEd Schouten GlobalDecl D, 4124ffd1746dSEd Schouten llvm::GlobalValue *Addr) { 4125ffd1746dSEd Schouten if (!GlobalMetadata) 4126ffd1746dSEd Schouten GlobalMetadata = 4127ffd1746dSEd Schouten CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 4128ffd1746dSEd Schouten 4129ffd1746dSEd Schouten // TODO: should we report variant information for ctors/dtors? 413039d628a0SDimitry Andric llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 413139d628a0SDimitry Andric llvm::ConstantAsMetadata::get(GetPointerConstant( 413239d628a0SDimitry Andric CGM.getLLVMContext(), D.getDecl()))}; 41333b0f4066SDimitry Andric GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 4134ffd1746dSEd Schouten } 4135ffd1746dSEd Schouten 4136284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked 4137284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled 4138284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer 4139284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the 4140284c1978SDimitry Andric /// same translation unit. 4141284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() { 4142e7145dcbSDimitry Andric // Don't do anything if we're generating CUDA device code -- the NVPTX 4143e7145dcbSDimitry Andric // assembly target doesn't support aliases. 4144e7145dcbSDimitry Andric if (Context.getTargetInfo().getTriple().isNVPTX()) 4145e7145dcbSDimitry Andric return; 41468f0fd8f6SDimitry Andric for (auto &I : StaticExternCValues) { 41478f0fd8f6SDimitry Andric IdentifierInfo *Name = I.first; 41488f0fd8f6SDimitry Andric llvm::GlobalValue *Val = I.second; 4149284c1978SDimitry Andric if (Val && !getModule().getNamedValue(Name->getName())) 415059d1ed5bSDimitry Andric addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 4151284c1978SDimitry Andric } 4152284c1978SDimitry Andric } 4153284c1978SDimitry Andric 415459d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 415559d1ed5bSDimitry Andric GlobalDecl &Result) const { 415659d1ed5bSDimitry Andric auto Res = Manglings.find(MangledName); 415759d1ed5bSDimitry Andric if (Res == Manglings.end()) 415859d1ed5bSDimitry Andric return false; 415959d1ed5bSDimitry Andric Result = Res->getValue(); 416059d1ed5bSDimitry Andric return true; 416159d1ed5bSDimitry Andric } 416259d1ed5bSDimitry Andric 4163ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the 4164ffd1746dSEd Schouten /// current module with the Decls they came from. This is useful for 4165ffd1746dSEd Schouten /// projects using IR gen as a subroutine. 4166ffd1746dSEd Schouten /// 4167ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly 4168ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata 4169ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'. 4170ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() { 417159d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 4172ffd1746dSEd Schouten 417359d1ed5bSDimitry Andric for (auto &I : MangledDeclNames) { 417459d1ed5bSDimitry Andric llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 41750623d748SDimitry Andric // Some mangled names don't necessarily have an associated GlobalValue 41760623d748SDimitry Andric // in this module, e.g. if we mangled it for DebugInfo. 41770623d748SDimitry Andric if (Addr) 417859d1ed5bSDimitry Andric EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 4179ffd1746dSEd Schouten } 4180ffd1746dSEd Schouten } 4181ffd1746dSEd Schouten 4182ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current 4183ffd1746dSEd Schouten /// function. 4184ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() { 4185ffd1746dSEd Schouten if (LocalDeclMap.empty()) return; 4186ffd1746dSEd Schouten 4187ffd1746dSEd Schouten llvm::LLVMContext &Context = getLLVMContext(); 4188ffd1746dSEd Schouten 4189ffd1746dSEd Schouten // Find the unique metadata ID for this name. 4190ffd1746dSEd Schouten unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 4191ffd1746dSEd Schouten 419259d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 4193ffd1746dSEd Schouten 419459d1ed5bSDimitry Andric for (auto &I : LocalDeclMap) { 419559d1ed5bSDimitry Andric const Decl *D = I.first; 41960623d748SDimitry Andric llvm::Value *Addr = I.second.getPointer(); 419759d1ed5bSDimitry Andric if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 4198ffd1746dSEd Schouten llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 419939d628a0SDimitry Andric Alloca->setMetadata( 420039d628a0SDimitry Andric DeclPtrKind, llvm::MDNode::get( 420139d628a0SDimitry Andric Context, llvm::ValueAsMetadata::getConstant(DAddr))); 420259d1ed5bSDimitry Andric } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 4203ffd1746dSEd Schouten GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 4204ffd1746dSEd Schouten EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 4205ffd1746dSEd Schouten } 4206ffd1746dSEd Schouten } 4207ffd1746dSEd Schouten } 4208e580952dSDimitry Andric 4209f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() { 4210f785676fSDimitry Andric llvm::NamedMDNode *IdentMetadata = 4211f785676fSDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.ident"); 4212f785676fSDimitry Andric std::string Version = getClangFullVersion(); 4213f785676fSDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 4214f785676fSDimitry Andric 421539d628a0SDimitry Andric llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 4216f785676fSDimitry Andric IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 4217f785676fSDimitry Andric } 4218f785676fSDimitry Andric 421959d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() { 422039d628a0SDimitry Andric // Warning, new MangledDeclNames may be appended within this loop. 422139d628a0SDimitry Andric // We rely on MapVector insertions adding new elements to the end 422239d628a0SDimitry Andric // of the container. 422339d628a0SDimitry Andric // FIXME: Move this loop into the one target that needs it, and only 422439d628a0SDimitry Andric // loop over those declarations for which we couldn't emit the target 422539d628a0SDimitry Andric // metadata when we emitted the declaration. 422639d628a0SDimitry Andric for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 422739d628a0SDimitry Andric auto Val = *(MangledDeclNames.begin() + I); 422839d628a0SDimitry Andric const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 422939d628a0SDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(Val.second); 423059d1ed5bSDimitry Andric getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 423159d1ed5bSDimitry Andric } 423259d1ed5bSDimitry Andric } 423359d1ed5bSDimitry Andric 4234bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() { 423544290647SDimitry Andric if (getCodeGenOpts().CoverageDataFile.empty() && 423644290647SDimitry Andric getCodeGenOpts().CoverageNotesFile.empty()) 423744290647SDimitry Andric return; 423844290647SDimitry Andric 423944290647SDimitry Andric llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 424044290647SDimitry Andric if (!CUNode) 424144290647SDimitry Andric return; 424244290647SDimitry Andric 4243bd5abe19SDimitry Andric llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 4244bd5abe19SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 424544290647SDimitry Andric auto *CoverageDataFile = 424644290647SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 424744290647SDimitry Andric auto *CoverageNotesFile = 424844290647SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 4249bd5abe19SDimitry Andric for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 4250bd5abe19SDimitry Andric llvm::MDNode *CU = CUNode->getOperand(i); 425144290647SDimitry Andric llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 425239d628a0SDimitry Andric GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 4253bd5abe19SDimitry Andric } 4254bd5abe19SDimitry Andric } 42553861d79fSDimitry Andric 425639d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { 42573861d79fSDimitry Andric // Sema has checked that all uuid strings are of the form 42583861d79fSDimitry Andric // "12345678-1234-1234-1234-1234567890ab". 42593861d79fSDimitry Andric assert(Uuid.size() == 36); 4260f785676fSDimitry Andric for (unsigned i = 0; i < 36; ++i) { 4261f785676fSDimitry Andric if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 4262f785676fSDimitry Andric else assert(isHexDigit(Uuid[i])); 42633861d79fSDimitry Andric } 42643861d79fSDimitry Andric 426539d628a0SDimitry Andric // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". 4266f785676fSDimitry Andric const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 42673861d79fSDimitry Andric 4268f785676fSDimitry Andric llvm::Constant *Field3[8]; 4269f785676fSDimitry Andric for (unsigned Idx = 0; Idx < 8; ++Idx) 4270f785676fSDimitry Andric Field3[Idx] = llvm::ConstantInt::get( 4271f785676fSDimitry Andric Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 42723861d79fSDimitry Andric 4273f785676fSDimitry Andric llvm::Constant *Fields[4] = { 4274f785676fSDimitry Andric llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 4275f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 4276f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 4277f785676fSDimitry Andric llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 4278f785676fSDimitry Andric }; 4279f785676fSDimitry Andric 4280f785676fSDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 42813861d79fSDimitry Andric } 428259d1ed5bSDimitry Andric 428359d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 428459d1ed5bSDimitry Andric bool ForEH) { 428559d1ed5bSDimitry Andric // Return a bogus pointer if RTTI is disabled, unless it's for EH. 428659d1ed5bSDimitry Andric // FIXME: should we even be calling this method if RTTI is disabled 428759d1ed5bSDimitry Andric // and it's not for EH? 428859d1ed5bSDimitry Andric if (!ForEH && !getLangOpts().RTTI) 428959d1ed5bSDimitry Andric return llvm::Constant::getNullValue(Int8PtrTy); 429059d1ed5bSDimitry Andric 429159d1ed5bSDimitry Andric if (ForEH && Ty->isObjCObjectPointerType() && 429259d1ed5bSDimitry Andric LangOpts.ObjCRuntime.isGNUFamily()) 429359d1ed5bSDimitry Andric return ObjCRuntime->GetEHType(Ty); 429459d1ed5bSDimitry Andric 429559d1ed5bSDimitry Andric return getCXXABI().getAddrOfRTTIDescriptor(Ty); 429659d1ed5bSDimitry Andric } 429759d1ed5bSDimitry Andric 429839d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 429939d628a0SDimitry Andric for (auto RefExpr : D->varlists()) { 430039d628a0SDimitry Andric auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 430139d628a0SDimitry Andric bool PerformInit = 430239d628a0SDimitry Andric VD->getAnyInitializer() && 430339d628a0SDimitry Andric !VD->getAnyInitializer()->isConstantInitializer(getContext(), 430439d628a0SDimitry Andric /*ForRef=*/false); 43050623d748SDimitry Andric 43060623d748SDimitry Andric Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 430733956c43SDimitry Andric if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 43080623d748SDimitry Andric VD, Addr, RefExpr->getLocStart(), PerformInit)) 430939d628a0SDimitry Andric CXXGlobalInits.push_back(InitFunction); 431039d628a0SDimitry Andric } 431139d628a0SDimitry Andric } 43128f0fd8f6SDimitry Andric 43130623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 43140623d748SDimitry Andric llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()]; 43150623d748SDimitry Andric if (InternalId) 43160623d748SDimitry Andric return InternalId; 43170623d748SDimitry Andric 43180623d748SDimitry Andric if (isExternallyVisible(T->getLinkage())) { 43198f0fd8f6SDimitry Andric std::string OutName; 43208f0fd8f6SDimitry Andric llvm::raw_string_ostream Out(OutName); 43210623d748SDimitry Andric getCXXABI().getMangleContext().mangleTypeName(T, Out); 43228f0fd8f6SDimitry Andric 43230623d748SDimitry Andric InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 43240623d748SDimitry Andric } else { 43250623d748SDimitry Andric InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 43260623d748SDimitry Andric llvm::ArrayRef<llvm::Metadata *>()); 43270623d748SDimitry Andric } 43280623d748SDimitry Andric 43290623d748SDimitry Andric return InternalId; 43300623d748SDimitry Andric } 43310623d748SDimitry Andric 4332e7145dcbSDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier. 4333e7145dcbSDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const { 4334e7145dcbSDimitry Andric // Returns true if at least one of vtable-based CFI checkers is enabled and 4335e7145dcbSDimitry Andric // is not in the trapping mode. 4336e7145dcbSDimitry Andric return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 4337e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 4338e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 4339e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 4340e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 4341e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 4342e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 4343e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 4344e7145dcbSDimitry Andric } 4345e7145dcbSDimitry Andric 4346e7145dcbSDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 43470623d748SDimitry Andric CharUnits Offset, 43480623d748SDimitry Andric const CXXRecordDecl *RD) { 43490623d748SDimitry Andric llvm::Metadata *MD = 43500623d748SDimitry Andric CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 4351e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 43520623d748SDimitry Andric 4353e7145dcbSDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 4354e7145dcbSDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 4355e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), 4356e7145dcbSDimitry Andric llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 4357e7145dcbSDimitry Andric 4358e7145dcbSDimitry Andric if (NeedAllVtablesTypeId()) { 4359e7145dcbSDimitry Andric llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 4360e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 43610623d748SDimitry Andric } 43620623d748SDimitry Andric } 43630623d748SDimitry Andric 43640623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the 43650623d748SDimitry Andric // passed in function. 43660623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 43670623d748SDimitry Andric const FunctionDecl *FD) { 43680623d748SDimitry Andric StringRef TargetCPU = Target.getTargetOpts().CPU; 43690623d748SDimitry Andric if (const auto *TD = FD->getAttr<TargetAttr>()) { 43700623d748SDimitry Andric // If we have a TargetAttr build up the feature map based on that. 43710623d748SDimitry Andric TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); 43720623d748SDimitry Andric 43730623d748SDimitry Andric // Make a copy of the features as passed on the command line into the 43740623d748SDimitry Andric // beginning of the additional features from the function to override. 43750623d748SDimitry Andric ParsedAttr.first.insert(ParsedAttr.first.begin(), 43760623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.begin(), 43770623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.end()); 43780623d748SDimitry Andric 43790623d748SDimitry Andric if (ParsedAttr.second != "") 43800623d748SDimitry Andric TargetCPU = ParsedAttr.second; 43810623d748SDimitry Andric 43820623d748SDimitry Andric // Now populate the feature map, first with the TargetCPU which is either 43830623d748SDimitry Andric // the default or a new one from the target attribute string. Then we'll use 43840623d748SDimitry Andric // the passed in features (FeaturesAsWritten) along with the new ones from 43850623d748SDimitry Andric // the attribute. 43860623d748SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first); 43870623d748SDimitry Andric } else { 43880623d748SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 43890623d748SDimitry Andric Target.getTargetOpts().Features); 43900623d748SDimitry Andric } 43918f0fd8f6SDimitry Andric } 4392e7145dcbSDimitry Andric 4393e7145dcbSDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 4394e7145dcbSDimitry Andric if (!SanStats) 4395e7145dcbSDimitry Andric SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule()); 4396e7145dcbSDimitry Andric 4397e7145dcbSDimitry Andric return *SanStats; 4398e7145dcbSDimitry Andric } 439944290647SDimitry Andric llvm::Value * 440044290647SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 440144290647SDimitry Andric CodeGenFunction &CGF) { 440244290647SDimitry Andric llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF); 440344290647SDimitry Andric auto SamplerT = getOpenCLRuntime().getSamplerType(); 440444290647SDimitry Andric auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 440544290647SDimitry Andric return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy, 440644290647SDimitry Andric "__translate_sampler_initializer"), 440744290647SDimitry Andric {C}); 440844290647SDimitry Andric } 4409