1*7330f729Sjoerg //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 2*7330f729Sjoerg // 3*7330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4*7330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information. 5*7330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6*7330f729Sjoerg // 7*7330f729Sjoerg //===----------------------------------------------------------------------===// 8*7330f729Sjoerg // 9*7330f729Sjoerg // This coordinates the per-module state used while generating code. 10*7330f729Sjoerg // 11*7330f729Sjoerg //===----------------------------------------------------------------------===// 12*7330f729Sjoerg 13*7330f729Sjoerg #include "CodeGenModule.h" 14*7330f729Sjoerg #include "CGBlocks.h" 15*7330f729Sjoerg #include "CGCUDARuntime.h" 16*7330f729Sjoerg #include "CGCXXABI.h" 17*7330f729Sjoerg #include "CGCall.h" 18*7330f729Sjoerg #include "CGDebugInfo.h" 19*7330f729Sjoerg #include "CGObjCRuntime.h" 20*7330f729Sjoerg #include "CGOpenCLRuntime.h" 21*7330f729Sjoerg #include "CGOpenMPRuntime.h" 22*7330f729Sjoerg #include "CGOpenMPRuntimeNVPTX.h" 23*7330f729Sjoerg #include "CodeGenFunction.h" 24*7330f729Sjoerg #include "CodeGenPGO.h" 25*7330f729Sjoerg #include "ConstantEmitter.h" 26*7330f729Sjoerg #include "CoverageMappingGen.h" 27*7330f729Sjoerg #include "TargetInfo.h" 28*7330f729Sjoerg #include "clang/AST/ASTContext.h" 29*7330f729Sjoerg #include "clang/AST/CharUnits.h" 30*7330f729Sjoerg #include "clang/AST/DeclCXX.h" 31*7330f729Sjoerg #include "clang/AST/DeclObjC.h" 32*7330f729Sjoerg #include "clang/AST/DeclTemplate.h" 33*7330f729Sjoerg #include "clang/AST/Mangle.h" 34*7330f729Sjoerg #include "clang/AST/RecordLayout.h" 35*7330f729Sjoerg #include "clang/AST/RecursiveASTVisitor.h" 36*7330f729Sjoerg #include "clang/AST/StmtVisitor.h" 37*7330f729Sjoerg #include "clang/Basic/Builtins.h" 38*7330f729Sjoerg #include "clang/Basic/CharInfo.h" 39*7330f729Sjoerg #include "clang/Basic/CodeGenOptions.h" 40*7330f729Sjoerg #include "clang/Basic/Diagnostic.h" 41*7330f729Sjoerg #include "clang/Basic/Module.h" 42*7330f729Sjoerg #include "clang/Basic/SourceManager.h" 43*7330f729Sjoerg #include "clang/Basic/TargetInfo.h" 44*7330f729Sjoerg #include "clang/Basic/Version.h" 45*7330f729Sjoerg #include "clang/CodeGen/ConstantInitBuilder.h" 46*7330f729Sjoerg #include "clang/Frontend/FrontendDiagnostic.h" 47*7330f729Sjoerg #include "llvm/ADT/StringSwitch.h" 48*7330f729Sjoerg #include "llvm/ADT/Triple.h" 49*7330f729Sjoerg #include "llvm/Analysis/TargetLibraryInfo.h" 50*7330f729Sjoerg #include "llvm/IR/CallingConv.h" 51*7330f729Sjoerg #include "llvm/IR/DataLayout.h" 52*7330f729Sjoerg #include "llvm/IR/Intrinsics.h" 53*7330f729Sjoerg #include "llvm/IR/LLVMContext.h" 54*7330f729Sjoerg #include "llvm/IR/Module.h" 55*7330f729Sjoerg #include "llvm/IR/ProfileSummary.h" 56*7330f729Sjoerg #include "llvm/ProfileData/InstrProfReader.h" 57*7330f729Sjoerg #include "llvm/Support/CodeGen.h" 58*7330f729Sjoerg #include "llvm/Support/ConvertUTF.h" 59*7330f729Sjoerg #include "llvm/Support/ErrorHandling.h" 60*7330f729Sjoerg #include "llvm/Support/MD5.h" 61*7330f729Sjoerg #include "llvm/Support/TimeProfiler.h" 62*7330f729Sjoerg 63*7330f729Sjoerg using namespace clang; 64*7330f729Sjoerg using namespace CodeGen; 65*7330f729Sjoerg 66*7330f729Sjoerg static llvm::cl::opt<bool> LimitedCoverage( 67*7330f729Sjoerg "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden, 68*7330f729Sjoerg llvm::cl::desc("Emit limited coverage mapping information (experimental)"), 69*7330f729Sjoerg llvm::cl::init(false)); 70*7330f729Sjoerg 71*7330f729Sjoerg static const char AnnotationSection[] = "llvm.metadata"; 72*7330f729Sjoerg 73*7330f729Sjoerg static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 74*7330f729Sjoerg switch (CGM.getTarget().getCXXABI().getKind()) { 75*7330f729Sjoerg case TargetCXXABI::GenericAArch64: 76*7330f729Sjoerg case TargetCXXABI::GenericARM: 77*7330f729Sjoerg case TargetCXXABI::iOS: 78*7330f729Sjoerg case TargetCXXABI::iOS64: 79*7330f729Sjoerg case TargetCXXABI::WatchOS: 80*7330f729Sjoerg case TargetCXXABI::GenericMIPS: 81*7330f729Sjoerg case TargetCXXABI::GenericItanium: 82*7330f729Sjoerg case TargetCXXABI::WebAssembly: 83*7330f729Sjoerg return CreateItaniumCXXABI(CGM); 84*7330f729Sjoerg case TargetCXXABI::Microsoft: 85*7330f729Sjoerg return CreateMicrosoftCXXABI(CGM); 86*7330f729Sjoerg } 87*7330f729Sjoerg 88*7330f729Sjoerg llvm_unreachable("invalid C++ ABI kind"); 89*7330f729Sjoerg } 90*7330f729Sjoerg 91*7330f729Sjoerg CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO, 92*7330f729Sjoerg const PreprocessorOptions &PPO, 93*7330f729Sjoerg const CodeGenOptions &CGO, llvm::Module &M, 94*7330f729Sjoerg DiagnosticsEngine &diags, 95*7330f729Sjoerg CoverageSourceInfo *CoverageInfo) 96*7330f729Sjoerg : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO), 97*7330f729Sjoerg PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), 98*7330f729Sjoerg Target(C.getTargetInfo()), ABI(createCXXABI(*this)), 99*7330f729Sjoerg VMContext(M.getContext()), Types(*this), VTables(*this), 100*7330f729Sjoerg SanitizerMD(new SanitizerMetadata(*this)) { 101*7330f729Sjoerg 102*7330f729Sjoerg // Initialize the type cache. 103*7330f729Sjoerg llvm::LLVMContext &LLVMContext = M.getContext(); 104*7330f729Sjoerg VoidTy = llvm::Type::getVoidTy(LLVMContext); 105*7330f729Sjoerg Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 106*7330f729Sjoerg Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 107*7330f729Sjoerg Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 108*7330f729Sjoerg Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 109*7330f729Sjoerg HalfTy = llvm::Type::getHalfTy(LLVMContext); 110*7330f729Sjoerg FloatTy = llvm::Type::getFloatTy(LLVMContext); 111*7330f729Sjoerg DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 112*7330f729Sjoerg PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 113*7330f729Sjoerg PointerAlignInBytes = 114*7330f729Sjoerg C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 115*7330f729Sjoerg SizeSizeInBytes = 116*7330f729Sjoerg C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); 117*7330f729Sjoerg IntAlignInBytes = 118*7330f729Sjoerg C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 119*7330f729Sjoerg IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 120*7330f729Sjoerg IntPtrTy = llvm::IntegerType::get(LLVMContext, 121*7330f729Sjoerg C.getTargetInfo().getMaxPointerWidth()); 122*7330f729Sjoerg Int8PtrTy = Int8Ty->getPointerTo(0); 123*7330f729Sjoerg Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 124*7330f729Sjoerg AllocaInt8PtrTy = Int8Ty->getPointerTo( 125*7330f729Sjoerg M.getDataLayout().getAllocaAddrSpace()); 126*7330f729Sjoerg ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); 127*7330f729Sjoerg 128*7330f729Sjoerg RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 129*7330f729Sjoerg 130*7330f729Sjoerg if (LangOpts.ObjC) 131*7330f729Sjoerg createObjCRuntime(); 132*7330f729Sjoerg if (LangOpts.OpenCL) 133*7330f729Sjoerg createOpenCLRuntime(); 134*7330f729Sjoerg if (LangOpts.OpenMP) 135*7330f729Sjoerg createOpenMPRuntime(); 136*7330f729Sjoerg if (LangOpts.CUDA) 137*7330f729Sjoerg createCUDARuntime(); 138*7330f729Sjoerg 139*7330f729Sjoerg // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 140*7330f729Sjoerg if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 141*7330f729Sjoerg (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 142*7330f729Sjoerg TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(), 143*7330f729Sjoerg getCXXABI().getMangleContext())); 144*7330f729Sjoerg 145*7330f729Sjoerg // If debug info or coverage generation is enabled, create the CGDebugInfo 146*7330f729Sjoerg // object. 147*7330f729Sjoerg if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo || 148*7330f729Sjoerg CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) 149*7330f729Sjoerg DebugInfo.reset(new CGDebugInfo(*this)); 150*7330f729Sjoerg 151*7330f729Sjoerg Block.GlobalUniqueCount = 0; 152*7330f729Sjoerg 153*7330f729Sjoerg if (C.getLangOpts().ObjC) 154*7330f729Sjoerg ObjCData.reset(new ObjCEntrypoints()); 155*7330f729Sjoerg 156*7330f729Sjoerg if (CodeGenOpts.hasProfileClangUse()) { 157*7330f729Sjoerg auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 158*7330f729Sjoerg CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile); 159*7330f729Sjoerg if (auto E = ReaderOrErr.takeError()) { 160*7330f729Sjoerg unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 161*7330f729Sjoerg "Could not read profile %0: %1"); 162*7330f729Sjoerg llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { 163*7330f729Sjoerg getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath 164*7330f729Sjoerg << EI.message(); 165*7330f729Sjoerg }); 166*7330f729Sjoerg } else 167*7330f729Sjoerg PGOReader = std::move(ReaderOrErr.get()); 168*7330f729Sjoerg } 169*7330f729Sjoerg 170*7330f729Sjoerg // If coverage mapping generation is enabled, create the 171*7330f729Sjoerg // CoverageMappingModuleGen object. 172*7330f729Sjoerg if (CodeGenOpts.CoverageMapping) 173*7330f729Sjoerg CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 174*7330f729Sjoerg } 175*7330f729Sjoerg 176*7330f729Sjoerg CodeGenModule::~CodeGenModule() {} 177*7330f729Sjoerg 178*7330f729Sjoerg void CodeGenModule::createObjCRuntime() { 179*7330f729Sjoerg // This is just isGNUFamily(), but we want to force implementors of 180*7330f729Sjoerg // new ABIs to decide how best to do this. 181*7330f729Sjoerg switch (LangOpts.ObjCRuntime.getKind()) { 182*7330f729Sjoerg case ObjCRuntime::GNUstep: 183*7330f729Sjoerg case ObjCRuntime::GCC: 184*7330f729Sjoerg case ObjCRuntime::ObjFW: 185*7330f729Sjoerg ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 186*7330f729Sjoerg return; 187*7330f729Sjoerg 188*7330f729Sjoerg case ObjCRuntime::FragileMacOSX: 189*7330f729Sjoerg case ObjCRuntime::MacOSX: 190*7330f729Sjoerg case ObjCRuntime::iOS: 191*7330f729Sjoerg case ObjCRuntime::WatchOS: 192*7330f729Sjoerg ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 193*7330f729Sjoerg return; 194*7330f729Sjoerg } 195*7330f729Sjoerg llvm_unreachable("bad runtime kind"); 196*7330f729Sjoerg } 197*7330f729Sjoerg 198*7330f729Sjoerg void CodeGenModule::createOpenCLRuntime() { 199*7330f729Sjoerg OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 200*7330f729Sjoerg } 201*7330f729Sjoerg 202*7330f729Sjoerg void CodeGenModule::createOpenMPRuntime() { 203*7330f729Sjoerg // Select a specialized code generation class based on the target, if any. 204*7330f729Sjoerg // If it does not exist use the default implementation. 205*7330f729Sjoerg switch (getTriple().getArch()) { 206*7330f729Sjoerg case llvm::Triple::nvptx: 207*7330f729Sjoerg case llvm::Triple::nvptx64: 208*7330f729Sjoerg assert(getLangOpts().OpenMPIsDevice && 209*7330f729Sjoerg "OpenMP NVPTX is only prepared to deal with device code."); 210*7330f729Sjoerg OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this)); 211*7330f729Sjoerg break; 212*7330f729Sjoerg default: 213*7330f729Sjoerg if (LangOpts.OpenMPSimd) 214*7330f729Sjoerg OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this)); 215*7330f729Sjoerg else 216*7330f729Sjoerg OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 217*7330f729Sjoerg break; 218*7330f729Sjoerg } 219*7330f729Sjoerg } 220*7330f729Sjoerg 221*7330f729Sjoerg void CodeGenModule::createCUDARuntime() { 222*7330f729Sjoerg CUDARuntime.reset(CreateNVCUDARuntime(*this)); 223*7330f729Sjoerg } 224*7330f729Sjoerg 225*7330f729Sjoerg void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 226*7330f729Sjoerg Replacements[Name] = C; 227*7330f729Sjoerg } 228*7330f729Sjoerg 229*7330f729Sjoerg void CodeGenModule::applyReplacements() { 230*7330f729Sjoerg for (auto &I : Replacements) { 231*7330f729Sjoerg StringRef MangledName = I.first(); 232*7330f729Sjoerg llvm::Constant *Replacement = I.second; 233*7330f729Sjoerg llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 234*7330f729Sjoerg if (!Entry) 235*7330f729Sjoerg continue; 236*7330f729Sjoerg auto *OldF = cast<llvm::Function>(Entry); 237*7330f729Sjoerg auto *NewF = dyn_cast<llvm::Function>(Replacement); 238*7330f729Sjoerg if (!NewF) { 239*7330f729Sjoerg if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 240*7330f729Sjoerg NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 241*7330f729Sjoerg } else { 242*7330f729Sjoerg auto *CE = cast<llvm::ConstantExpr>(Replacement); 243*7330f729Sjoerg assert(CE->getOpcode() == llvm::Instruction::BitCast || 244*7330f729Sjoerg CE->getOpcode() == llvm::Instruction::GetElementPtr); 245*7330f729Sjoerg NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 246*7330f729Sjoerg } 247*7330f729Sjoerg } 248*7330f729Sjoerg 249*7330f729Sjoerg // Replace old with new, but keep the old order. 250*7330f729Sjoerg OldF->replaceAllUsesWith(Replacement); 251*7330f729Sjoerg if (NewF) { 252*7330f729Sjoerg NewF->removeFromParent(); 253*7330f729Sjoerg OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 254*7330f729Sjoerg NewF); 255*7330f729Sjoerg } 256*7330f729Sjoerg OldF->eraseFromParent(); 257*7330f729Sjoerg } 258*7330f729Sjoerg } 259*7330f729Sjoerg 260*7330f729Sjoerg void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 261*7330f729Sjoerg GlobalValReplacements.push_back(std::make_pair(GV, C)); 262*7330f729Sjoerg } 263*7330f729Sjoerg 264*7330f729Sjoerg void CodeGenModule::applyGlobalValReplacements() { 265*7330f729Sjoerg for (auto &I : GlobalValReplacements) { 266*7330f729Sjoerg llvm::GlobalValue *GV = I.first; 267*7330f729Sjoerg llvm::Constant *C = I.second; 268*7330f729Sjoerg 269*7330f729Sjoerg GV->replaceAllUsesWith(C); 270*7330f729Sjoerg GV->eraseFromParent(); 271*7330f729Sjoerg } 272*7330f729Sjoerg } 273*7330f729Sjoerg 274*7330f729Sjoerg // This is only used in aliases that we created and we know they have a 275*7330f729Sjoerg // linear structure. 276*7330f729Sjoerg static const llvm::GlobalObject *getAliasedGlobal( 277*7330f729Sjoerg const llvm::GlobalIndirectSymbol &GIS) { 278*7330f729Sjoerg llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited; 279*7330f729Sjoerg const llvm::Constant *C = &GIS; 280*7330f729Sjoerg for (;;) { 281*7330f729Sjoerg C = C->stripPointerCasts(); 282*7330f729Sjoerg if (auto *GO = dyn_cast<llvm::GlobalObject>(C)) 283*7330f729Sjoerg return GO; 284*7330f729Sjoerg // stripPointerCasts will not walk over weak aliases. 285*7330f729Sjoerg auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C); 286*7330f729Sjoerg if (!GIS2) 287*7330f729Sjoerg return nullptr; 288*7330f729Sjoerg if (!Visited.insert(GIS2).second) 289*7330f729Sjoerg return nullptr; 290*7330f729Sjoerg C = GIS2->getIndirectSymbol(); 291*7330f729Sjoerg } 292*7330f729Sjoerg } 293*7330f729Sjoerg 294*7330f729Sjoerg void CodeGenModule::checkAliases() { 295*7330f729Sjoerg // Check if the constructed aliases are well formed. It is really unfortunate 296*7330f729Sjoerg // that we have to do this in CodeGen, but we only construct mangled names 297*7330f729Sjoerg // and aliases during codegen. 298*7330f729Sjoerg bool Error = false; 299*7330f729Sjoerg DiagnosticsEngine &Diags = getDiags(); 300*7330f729Sjoerg for (const GlobalDecl &GD : Aliases) { 301*7330f729Sjoerg const auto *D = cast<ValueDecl>(GD.getDecl()); 302*7330f729Sjoerg SourceLocation Location; 303*7330f729Sjoerg bool IsIFunc = D->hasAttr<IFuncAttr>(); 304*7330f729Sjoerg if (const Attr *A = D->getDefiningAttr()) 305*7330f729Sjoerg Location = A->getLocation(); 306*7330f729Sjoerg else 307*7330f729Sjoerg llvm_unreachable("Not an alias or ifunc?"); 308*7330f729Sjoerg StringRef MangledName = getMangledName(GD); 309*7330f729Sjoerg llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 310*7330f729Sjoerg auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry); 311*7330f729Sjoerg const llvm::GlobalValue *GV = getAliasedGlobal(*Alias); 312*7330f729Sjoerg if (!GV) { 313*7330f729Sjoerg Error = true; 314*7330f729Sjoerg Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 315*7330f729Sjoerg } else if (GV->isDeclaration()) { 316*7330f729Sjoerg Error = true; 317*7330f729Sjoerg Diags.Report(Location, diag::err_alias_to_undefined) 318*7330f729Sjoerg << IsIFunc << IsIFunc; 319*7330f729Sjoerg } else if (IsIFunc) { 320*7330f729Sjoerg // Check resolver function type. 321*7330f729Sjoerg llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>( 322*7330f729Sjoerg GV->getType()->getPointerElementType()); 323*7330f729Sjoerg assert(FTy); 324*7330f729Sjoerg if (!FTy->getReturnType()->isPointerTy()) 325*7330f729Sjoerg Diags.Report(Location, diag::err_ifunc_resolver_return); 326*7330f729Sjoerg } 327*7330f729Sjoerg 328*7330f729Sjoerg llvm::Constant *Aliasee = Alias->getIndirectSymbol(); 329*7330f729Sjoerg llvm::GlobalValue *AliaseeGV; 330*7330f729Sjoerg if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 331*7330f729Sjoerg AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 332*7330f729Sjoerg else 333*7330f729Sjoerg AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 334*7330f729Sjoerg 335*7330f729Sjoerg if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 336*7330f729Sjoerg StringRef AliasSection = SA->getName(); 337*7330f729Sjoerg if (AliasSection != AliaseeGV->getSection()) 338*7330f729Sjoerg Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 339*7330f729Sjoerg << AliasSection << IsIFunc << IsIFunc; 340*7330f729Sjoerg } 341*7330f729Sjoerg 342*7330f729Sjoerg // We have to handle alias to weak aliases in here. LLVM itself disallows 343*7330f729Sjoerg // this since the object semantics would not match the IL one. For 344*7330f729Sjoerg // compatibility with gcc we implement it by just pointing the alias 345*7330f729Sjoerg // to its aliasee's aliasee. We also warn, since the user is probably 346*7330f729Sjoerg // expecting the link to be weak. 347*7330f729Sjoerg if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) { 348*7330f729Sjoerg if (GA->isInterposable()) { 349*7330f729Sjoerg Diags.Report(Location, diag::warn_alias_to_weak_alias) 350*7330f729Sjoerg << GV->getName() << GA->getName() << IsIFunc; 351*7330f729Sjoerg Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 352*7330f729Sjoerg GA->getIndirectSymbol(), Alias->getType()); 353*7330f729Sjoerg Alias->setIndirectSymbol(Aliasee); 354*7330f729Sjoerg } 355*7330f729Sjoerg } 356*7330f729Sjoerg } 357*7330f729Sjoerg if (!Error) 358*7330f729Sjoerg return; 359*7330f729Sjoerg 360*7330f729Sjoerg for (const GlobalDecl &GD : Aliases) { 361*7330f729Sjoerg StringRef MangledName = getMangledName(GD); 362*7330f729Sjoerg llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 363*7330f729Sjoerg auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry); 364*7330f729Sjoerg Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 365*7330f729Sjoerg Alias->eraseFromParent(); 366*7330f729Sjoerg } 367*7330f729Sjoerg } 368*7330f729Sjoerg 369*7330f729Sjoerg void CodeGenModule::clear() { 370*7330f729Sjoerg DeferredDeclsToEmit.clear(); 371*7330f729Sjoerg if (OpenMPRuntime) 372*7330f729Sjoerg OpenMPRuntime->clear(); 373*7330f729Sjoerg } 374*7330f729Sjoerg 375*7330f729Sjoerg void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 376*7330f729Sjoerg StringRef MainFile) { 377*7330f729Sjoerg if (!hasDiagnostics()) 378*7330f729Sjoerg return; 379*7330f729Sjoerg if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 380*7330f729Sjoerg if (MainFile.empty()) 381*7330f729Sjoerg MainFile = "<stdin>"; 382*7330f729Sjoerg Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 383*7330f729Sjoerg } else { 384*7330f729Sjoerg if (Mismatched > 0) 385*7330f729Sjoerg Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; 386*7330f729Sjoerg 387*7330f729Sjoerg if (Missing > 0) 388*7330f729Sjoerg Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; 389*7330f729Sjoerg } 390*7330f729Sjoerg } 391*7330f729Sjoerg 392*7330f729Sjoerg void CodeGenModule::Release() { 393*7330f729Sjoerg EmitDeferred(); 394*7330f729Sjoerg EmitVTablesOpportunistically(); 395*7330f729Sjoerg applyGlobalValReplacements(); 396*7330f729Sjoerg applyReplacements(); 397*7330f729Sjoerg checkAliases(); 398*7330f729Sjoerg emitMultiVersionFunctions(); 399*7330f729Sjoerg EmitCXXGlobalInitFunc(); 400*7330f729Sjoerg EmitCXXGlobalDtorFunc(); 401*7330f729Sjoerg registerGlobalDtorsWithAtExit(); 402*7330f729Sjoerg EmitCXXThreadLocalInitFunc(); 403*7330f729Sjoerg if (ObjCRuntime) 404*7330f729Sjoerg if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 405*7330f729Sjoerg AddGlobalCtor(ObjCInitFunction); 406*7330f729Sjoerg if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice && 407*7330f729Sjoerg CUDARuntime) { 408*7330f729Sjoerg if (llvm::Function *CudaCtorFunction = 409*7330f729Sjoerg CUDARuntime->makeModuleCtorFunction()) 410*7330f729Sjoerg AddGlobalCtor(CudaCtorFunction); 411*7330f729Sjoerg } 412*7330f729Sjoerg if (OpenMPRuntime) { 413*7330f729Sjoerg if (llvm::Function *OpenMPRequiresDirectiveRegFun = 414*7330f729Sjoerg OpenMPRuntime->emitRequiresDirectiveRegFun()) { 415*7330f729Sjoerg AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0); 416*7330f729Sjoerg } 417*7330f729Sjoerg OpenMPRuntime->createOffloadEntriesAndInfoMetadata(); 418*7330f729Sjoerg OpenMPRuntime->clear(); 419*7330f729Sjoerg } 420*7330f729Sjoerg if (PGOReader) { 421*7330f729Sjoerg getModule().setProfileSummary( 422*7330f729Sjoerg PGOReader->getSummary(/* UseCS */ false).getMD(VMContext), 423*7330f729Sjoerg llvm::ProfileSummary::PSK_Instr); 424*7330f729Sjoerg if (PGOStats.hasDiagnostics()) 425*7330f729Sjoerg PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 426*7330f729Sjoerg } 427*7330f729Sjoerg EmitCtorList(GlobalCtors, "llvm.global_ctors"); 428*7330f729Sjoerg EmitCtorList(GlobalDtors, "llvm.global_dtors"); 429*7330f729Sjoerg EmitGlobalAnnotations(); 430*7330f729Sjoerg EmitStaticExternCAliases(); 431*7330f729Sjoerg EmitDeferredUnusedCoverageMappings(); 432*7330f729Sjoerg if (CoverageMapping) 433*7330f729Sjoerg CoverageMapping->emit(); 434*7330f729Sjoerg if (CodeGenOpts.SanitizeCfiCrossDso) { 435*7330f729Sjoerg CodeGenFunction(*this).EmitCfiCheckFail(); 436*7330f729Sjoerg CodeGenFunction(*this).EmitCfiCheckStub(); 437*7330f729Sjoerg } 438*7330f729Sjoerg emitAtAvailableLinkGuard(); 439*7330f729Sjoerg emitLLVMUsed(); 440*7330f729Sjoerg if (SanStats) 441*7330f729Sjoerg SanStats->finish(); 442*7330f729Sjoerg 443*7330f729Sjoerg if (CodeGenOpts.Autolink && 444*7330f729Sjoerg (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 445*7330f729Sjoerg EmitModuleLinkOptions(); 446*7330f729Sjoerg } 447*7330f729Sjoerg 448*7330f729Sjoerg // On ELF we pass the dependent library specifiers directly to the linker 449*7330f729Sjoerg // without manipulating them. This is in contrast to other platforms where 450*7330f729Sjoerg // they are mapped to a specific linker option by the compiler. This 451*7330f729Sjoerg // difference is a result of the greater variety of ELF linkers and the fact 452*7330f729Sjoerg // that ELF linkers tend to handle libraries in a more complicated fashion 453*7330f729Sjoerg // than on other platforms. This forces us to defer handling the dependent 454*7330f729Sjoerg // libs to the linker. 455*7330f729Sjoerg // 456*7330f729Sjoerg // CUDA/HIP device and host libraries are different. Currently there is no 457*7330f729Sjoerg // way to differentiate dependent libraries for host or device. Existing 458*7330f729Sjoerg // usage of #pragma comment(lib, *) is intended for host libraries on 459*7330f729Sjoerg // Windows. Therefore emit llvm.dependent-libraries only for host. 460*7330f729Sjoerg if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) { 461*7330f729Sjoerg auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries"); 462*7330f729Sjoerg for (auto *MD : ELFDependentLibraries) 463*7330f729Sjoerg NMD->addOperand(MD); 464*7330f729Sjoerg } 465*7330f729Sjoerg 466*7330f729Sjoerg // Record mregparm value now so it is visible through rest of codegen. 467*7330f729Sjoerg if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 468*7330f729Sjoerg getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", 469*7330f729Sjoerg CodeGenOpts.NumRegisterParameters); 470*7330f729Sjoerg 471*7330f729Sjoerg if (CodeGenOpts.DwarfVersion) { 472*7330f729Sjoerg // We actually want the latest version when there are conflicts. 473*7330f729Sjoerg // We can change from Warning to Latest if such mode is supported. 474*7330f729Sjoerg getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 475*7330f729Sjoerg CodeGenOpts.DwarfVersion); 476*7330f729Sjoerg } 477*7330f729Sjoerg if (CodeGenOpts.EmitCodeView) { 478*7330f729Sjoerg // Indicate that we want CodeView in the metadata. 479*7330f729Sjoerg getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 480*7330f729Sjoerg } 481*7330f729Sjoerg if (CodeGenOpts.CodeViewGHash) { 482*7330f729Sjoerg getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1); 483*7330f729Sjoerg } 484*7330f729Sjoerg if (CodeGenOpts.ControlFlowGuard) { 485*7330f729Sjoerg // Function ID tables and checks for Control Flow Guard (cfguard=2). 486*7330f729Sjoerg getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2); 487*7330f729Sjoerg } else if (CodeGenOpts.ControlFlowGuardNoChecks) { 488*7330f729Sjoerg // Function ID tables for Control Flow Guard (cfguard=1). 489*7330f729Sjoerg getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1); 490*7330f729Sjoerg } 491*7330f729Sjoerg if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 492*7330f729Sjoerg // We don't support LTO with 2 with different StrictVTablePointers 493*7330f729Sjoerg // FIXME: we could support it by stripping all the information introduced 494*7330f729Sjoerg // by StrictVTablePointers. 495*7330f729Sjoerg 496*7330f729Sjoerg getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 497*7330f729Sjoerg 498*7330f729Sjoerg llvm::Metadata *Ops[2] = { 499*7330f729Sjoerg llvm::MDString::get(VMContext, "StrictVTablePointers"), 500*7330f729Sjoerg llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 501*7330f729Sjoerg llvm::Type::getInt32Ty(VMContext), 1))}; 502*7330f729Sjoerg 503*7330f729Sjoerg getModule().addModuleFlag(llvm::Module::Require, 504*7330f729Sjoerg "StrictVTablePointersRequirement", 505*7330f729Sjoerg llvm::MDNode::get(VMContext, Ops)); 506*7330f729Sjoerg } 507*7330f729Sjoerg if (DebugInfo) 508*7330f729Sjoerg // We support a single version in the linked module. The LLVM 509*7330f729Sjoerg // parser will drop debug info with a different version number 510*7330f729Sjoerg // (and warn about it, too). 511*7330f729Sjoerg getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 512*7330f729Sjoerg llvm::DEBUG_METADATA_VERSION); 513*7330f729Sjoerg 514*7330f729Sjoerg // We need to record the widths of enums and wchar_t, so that we can generate 515*7330f729Sjoerg // the correct build attributes in the ARM backend. wchar_size is also used by 516*7330f729Sjoerg // TargetLibraryInfo. 517*7330f729Sjoerg uint64_t WCharWidth = 518*7330f729Sjoerg Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 519*7330f729Sjoerg getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 520*7330f729Sjoerg 521*7330f729Sjoerg llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 522*7330f729Sjoerg if ( Arch == llvm::Triple::arm 523*7330f729Sjoerg || Arch == llvm::Triple::armeb 524*7330f729Sjoerg || Arch == llvm::Triple::thumb 525*7330f729Sjoerg || Arch == llvm::Triple::thumbeb) { 526*7330f729Sjoerg // The minimum width of an enum in bytes 527*7330f729Sjoerg uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 528*7330f729Sjoerg getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 529*7330f729Sjoerg } 530*7330f729Sjoerg 531*7330f729Sjoerg if (CodeGenOpts.SanitizeCfiCrossDso) { 532*7330f729Sjoerg // Indicate that we want cross-DSO control flow integrity checks. 533*7330f729Sjoerg getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 534*7330f729Sjoerg } 535*7330f729Sjoerg 536*7330f729Sjoerg if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) { 537*7330f729Sjoerg getModule().addModuleFlag(llvm::Module::Override, 538*7330f729Sjoerg "CFI Canonical Jump Tables", 539*7330f729Sjoerg CodeGenOpts.SanitizeCfiCanonicalJumpTables); 540*7330f729Sjoerg } 541*7330f729Sjoerg 542*7330f729Sjoerg if (CodeGenOpts.CFProtectionReturn && 543*7330f729Sjoerg Target.checkCFProtectionReturnSupported(getDiags())) { 544*7330f729Sjoerg // Indicate that we want to instrument return control flow protection. 545*7330f729Sjoerg getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return", 546*7330f729Sjoerg 1); 547*7330f729Sjoerg } 548*7330f729Sjoerg 549*7330f729Sjoerg if (CodeGenOpts.CFProtectionBranch && 550*7330f729Sjoerg Target.checkCFProtectionBranchSupported(getDiags())) { 551*7330f729Sjoerg // Indicate that we want to instrument branch control flow protection. 552*7330f729Sjoerg getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch", 553*7330f729Sjoerg 1); 554*7330f729Sjoerg } 555*7330f729Sjoerg 556*7330f729Sjoerg if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { 557*7330f729Sjoerg // Indicate whether __nvvm_reflect should be configured to flush denormal 558*7330f729Sjoerg // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 559*7330f729Sjoerg // property.) 560*7330f729Sjoerg getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 561*7330f729Sjoerg CodeGenOpts.FlushDenorm ? 1 : 0); 562*7330f729Sjoerg } 563*7330f729Sjoerg 564*7330f729Sjoerg // Emit OpenCL specific module metadata: OpenCL/SPIR version. 565*7330f729Sjoerg if (LangOpts.OpenCL) { 566*7330f729Sjoerg EmitOpenCLMetadata(); 567*7330f729Sjoerg // Emit SPIR version. 568*7330f729Sjoerg if (getTriple().isSPIR()) { 569*7330f729Sjoerg // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the 570*7330f729Sjoerg // opencl.spir.version named metadata. 571*7330f729Sjoerg // C++ is backwards compatible with OpenCL v2.0. 572*7330f729Sjoerg auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion; 573*7330f729Sjoerg llvm::Metadata *SPIRVerElts[] = { 574*7330f729Sjoerg llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 575*7330f729Sjoerg Int32Ty, Version / 100)), 576*7330f729Sjoerg llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 577*7330f729Sjoerg Int32Ty, (Version / 100 > 1) ? 0 : 2))}; 578*7330f729Sjoerg llvm::NamedMDNode *SPIRVerMD = 579*7330f729Sjoerg TheModule.getOrInsertNamedMetadata("opencl.spir.version"); 580*7330f729Sjoerg llvm::LLVMContext &Ctx = TheModule.getContext(); 581*7330f729Sjoerg SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts)); 582*7330f729Sjoerg } 583*7330f729Sjoerg } 584*7330f729Sjoerg 585*7330f729Sjoerg if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 586*7330f729Sjoerg assert(PLevel < 3 && "Invalid PIC Level"); 587*7330f729Sjoerg getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 588*7330f729Sjoerg if (Context.getLangOpts().PIE) 589*7330f729Sjoerg getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 590*7330f729Sjoerg } 591*7330f729Sjoerg 592*7330f729Sjoerg if (getCodeGenOpts().CodeModel.size() > 0) { 593*7330f729Sjoerg unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel) 594*7330f729Sjoerg .Case("tiny", llvm::CodeModel::Tiny) 595*7330f729Sjoerg .Case("small", llvm::CodeModel::Small) 596*7330f729Sjoerg .Case("kernel", llvm::CodeModel::Kernel) 597*7330f729Sjoerg .Case("medium", llvm::CodeModel::Medium) 598*7330f729Sjoerg .Case("large", llvm::CodeModel::Large) 599*7330f729Sjoerg .Default(~0u); 600*7330f729Sjoerg if (CM != ~0u) { 601*7330f729Sjoerg llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM); 602*7330f729Sjoerg getModule().setCodeModel(codeModel); 603*7330f729Sjoerg } 604*7330f729Sjoerg } 605*7330f729Sjoerg 606*7330f729Sjoerg if (CodeGenOpts.NoPLT) 607*7330f729Sjoerg getModule().setRtLibUseGOT(); 608*7330f729Sjoerg 609*7330f729Sjoerg SimplifyPersonality(); 610*7330f729Sjoerg 611*7330f729Sjoerg if (getCodeGenOpts().EmitDeclMetadata) 612*7330f729Sjoerg EmitDeclMetadata(); 613*7330f729Sjoerg 614*7330f729Sjoerg if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 615*7330f729Sjoerg EmitCoverageFile(); 616*7330f729Sjoerg 617*7330f729Sjoerg if (DebugInfo) 618*7330f729Sjoerg DebugInfo->finalize(); 619*7330f729Sjoerg 620*7330f729Sjoerg if (getCodeGenOpts().EmitVersionIdentMetadata) 621*7330f729Sjoerg EmitVersionIdentMetadata(); 622*7330f729Sjoerg 623*7330f729Sjoerg if (!getCodeGenOpts().RecordCommandLine.empty()) 624*7330f729Sjoerg EmitCommandLineMetadata(); 625*7330f729Sjoerg 626*7330f729Sjoerg EmitTargetMetadata(); 627*7330f729Sjoerg } 628*7330f729Sjoerg 629*7330f729Sjoerg void CodeGenModule::EmitOpenCLMetadata() { 630*7330f729Sjoerg // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the 631*7330f729Sjoerg // opencl.ocl.version named metadata node. 632*7330f729Sjoerg // C++ is backwards compatible with OpenCL v2.0. 633*7330f729Sjoerg // FIXME: We might need to add CXX version at some point too? 634*7330f729Sjoerg auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion; 635*7330f729Sjoerg llvm::Metadata *OCLVerElts[] = { 636*7330f729Sjoerg llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 637*7330f729Sjoerg Int32Ty, Version / 100)), 638*7330f729Sjoerg llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 639*7330f729Sjoerg Int32Ty, (Version % 100) / 10))}; 640*7330f729Sjoerg llvm::NamedMDNode *OCLVerMD = 641*7330f729Sjoerg TheModule.getOrInsertNamedMetadata("opencl.ocl.version"); 642*7330f729Sjoerg llvm::LLVMContext &Ctx = TheModule.getContext(); 643*7330f729Sjoerg OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts)); 644*7330f729Sjoerg } 645*7330f729Sjoerg 646*7330f729Sjoerg void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 647*7330f729Sjoerg // Make sure that this type is translated. 648*7330f729Sjoerg Types.UpdateCompletedType(TD); 649*7330f729Sjoerg } 650*7330f729Sjoerg 651*7330f729Sjoerg void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 652*7330f729Sjoerg // Make sure that this type is translated. 653*7330f729Sjoerg Types.RefreshTypeCacheForClass(RD); 654*7330f729Sjoerg } 655*7330f729Sjoerg 656*7330f729Sjoerg llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) { 657*7330f729Sjoerg if (!TBAA) 658*7330f729Sjoerg return nullptr; 659*7330f729Sjoerg return TBAA->getTypeInfo(QTy); 660*7330f729Sjoerg } 661*7330f729Sjoerg 662*7330f729Sjoerg TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { 663*7330f729Sjoerg if (!TBAA) 664*7330f729Sjoerg return TBAAAccessInfo(); 665*7330f729Sjoerg return TBAA->getAccessInfo(AccessType); 666*7330f729Sjoerg } 667*7330f729Sjoerg 668*7330f729Sjoerg TBAAAccessInfo 669*7330f729Sjoerg CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) { 670*7330f729Sjoerg if (!TBAA) 671*7330f729Sjoerg return TBAAAccessInfo(); 672*7330f729Sjoerg return TBAA->getVTablePtrAccessInfo(VTablePtrType); 673*7330f729Sjoerg } 674*7330f729Sjoerg 675*7330f729Sjoerg llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 676*7330f729Sjoerg if (!TBAA) 677*7330f729Sjoerg return nullptr; 678*7330f729Sjoerg return TBAA->getTBAAStructInfo(QTy); 679*7330f729Sjoerg } 680*7330f729Sjoerg 681*7330f729Sjoerg llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { 682*7330f729Sjoerg if (!TBAA) 683*7330f729Sjoerg return nullptr; 684*7330f729Sjoerg return TBAA->getBaseTypeInfo(QTy); 685*7330f729Sjoerg } 686*7330f729Sjoerg 687*7330f729Sjoerg llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { 688*7330f729Sjoerg if (!TBAA) 689*7330f729Sjoerg return nullptr; 690*7330f729Sjoerg return TBAA->getAccessTagInfo(Info); 691*7330f729Sjoerg } 692*7330f729Sjoerg 693*7330f729Sjoerg TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 694*7330f729Sjoerg TBAAAccessInfo TargetInfo) { 695*7330f729Sjoerg if (!TBAA) 696*7330f729Sjoerg return TBAAAccessInfo(); 697*7330f729Sjoerg return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo); 698*7330f729Sjoerg } 699*7330f729Sjoerg 700*7330f729Sjoerg TBAAAccessInfo 701*7330f729Sjoerg CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, 702*7330f729Sjoerg TBAAAccessInfo InfoB) { 703*7330f729Sjoerg if (!TBAA) 704*7330f729Sjoerg return TBAAAccessInfo(); 705*7330f729Sjoerg return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB); 706*7330f729Sjoerg } 707*7330f729Sjoerg 708*7330f729Sjoerg TBAAAccessInfo 709*7330f729Sjoerg CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, 710*7330f729Sjoerg TBAAAccessInfo SrcInfo) { 711*7330f729Sjoerg if (!TBAA) 712*7330f729Sjoerg return TBAAAccessInfo(); 713*7330f729Sjoerg return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo); 714*7330f729Sjoerg } 715*7330f729Sjoerg 716*7330f729Sjoerg void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 717*7330f729Sjoerg TBAAAccessInfo TBAAInfo) { 718*7330f729Sjoerg if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo)) 719*7330f729Sjoerg Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag); 720*7330f729Sjoerg } 721*7330f729Sjoerg 722*7330f729Sjoerg void CodeGenModule::DecorateInstructionWithInvariantGroup( 723*7330f729Sjoerg llvm::Instruction *I, const CXXRecordDecl *RD) { 724*7330f729Sjoerg I->setMetadata(llvm::LLVMContext::MD_invariant_group, 725*7330f729Sjoerg llvm::MDNode::get(getLLVMContext(), {})); 726*7330f729Sjoerg } 727*7330f729Sjoerg 728*7330f729Sjoerg void CodeGenModule::Error(SourceLocation loc, StringRef message) { 729*7330f729Sjoerg unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 730*7330f729Sjoerg getDiags().Report(Context.getFullLoc(loc), diagID) << message; 731*7330f729Sjoerg } 732*7330f729Sjoerg 733*7330f729Sjoerg /// ErrorUnsupported - Print out an error that codegen doesn't support the 734*7330f729Sjoerg /// specified stmt yet. 735*7330f729Sjoerg void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 736*7330f729Sjoerg unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 737*7330f729Sjoerg "cannot compile this %0 yet"); 738*7330f729Sjoerg std::string Msg = Type; 739*7330f729Sjoerg getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID) 740*7330f729Sjoerg << Msg << S->getSourceRange(); 741*7330f729Sjoerg } 742*7330f729Sjoerg 743*7330f729Sjoerg /// ErrorUnsupported - Print out an error that codegen doesn't support the 744*7330f729Sjoerg /// specified decl yet. 745*7330f729Sjoerg void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 746*7330f729Sjoerg unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 747*7330f729Sjoerg "cannot compile this %0 yet"); 748*7330f729Sjoerg std::string Msg = Type; 749*7330f729Sjoerg getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 750*7330f729Sjoerg } 751*7330f729Sjoerg 752*7330f729Sjoerg llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 753*7330f729Sjoerg return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 754*7330f729Sjoerg } 755*7330f729Sjoerg 756*7330f729Sjoerg void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 757*7330f729Sjoerg const NamedDecl *D) const { 758*7330f729Sjoerg if (GV->hasDLLImportStorageClass()) 759*7330f729Sjoerg return; 760*7330f729Sjoerg // Internal definitions always have default visibility. 761*7330f729Sjoerg if (GV->hasLocalLinkage()) { 762*7330f729Sjoerg GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 763*7330f729Sjoerg return; 764*7330f729Sjoerg } 765*7330f729Sjoerg if (!D) 766*7330f729Sjoerg return; 767*7330f729Sjoerg // Set visibility for definitions, and for declarations if requested globally 768*7330f729Sjoerg // or set explicitly. 769*7330f729Sjoerg LinkageInfo LV = D->getLinkageAndVisibility(); 770*7330f729Sjoerg if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls || 771*7330f729Sjoerg !GV->isDeclarationForLinker()) 772*7330f729Sjoerg GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 773*7330f729Sjoerg } 774*7330f729Sjoerg 775*7330f729Sjoerg static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, 776*7330f729Sjoerg llvm::GlobalValue *GV) { 777*7330f729Sjoerg if (GV->hasLocalLinkage()) 778*7330f729Sjoerg return true; 779*7330f729Sjoerg 780*7330f729Sjoerg if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()) 781*7330f729Sjoerg return true; 782*7330f729Sjoerg 783*7330f729Sjoerg // DLLImport explicitly marks the GV as external. 784*7330f729Sjoerg if (GV->hasDLLImportStorageClass()) 785*7330f729Sjoerg return false; 786*7330f729Sjoerg 787*7330f729Sjoerg const llvm::Triple &TT = CGM.getTriple(); 788*7330f729Sjoerg if (TT.isWindowsGNUEnvironment()) { 789*7330f729Sjoerg // In MinGW, variables without DLLImport can still be automatically 790*7330f729Sjoerg // imported from a DLL by the linker; don't mark variables that 791*7330f729Sjoerg // potentially could come from another DLL as DSO local. 792*7330f729Sjoerg if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) && 793*7330f729Sjoerg !GV->isThreadLocal()) 794*7330f729Sjoerg return false; 795*7330f729Sjoerg } 796*7330f729Sjoerg 797*7330f729Sjoerg // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols 798*7330f729Sjoerg // remain unresolved in the link, they can be resolved to zero, which is 799*7330f729Sjoerg // outside the current DSO. 800*7330f729Sjoerg if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage()) 801*7330f729Sjoerg return false; 802*7330f729Sjoerg 803*7330f729Sjoerg // Every other GV is local on COFF. 804*7330f729Sjoerg // Make an exception for windows OS in the triple: Some firmware builds use 805*7330f729Sjoerg // *-win32-macho triples. This (accidentally?) produced windows relocations 806*7330f729Sjoerg // without GOT tables in older clang versions; Keep this behaviour. 807*7330f729Sjoerg // FIXME: even thread local variables? 808*7330f729Sjoerg if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO())) 809*7330f729Sjoerg return true; 810*7330f729Sjoerg 811*7330f729Sjoerg // Only handle COFF and ELF for now. 812*7330f729Sjoerg if (!TT.isOSBinFormatELF()) 813*7330f729Sjoerg return false; 814*7330f729Sjoerg 815*7330f729Sjoerg // If this is not an executable, don't assume anything is local. 816*7330f729Sjoerg const auto &CGOpts = CGM.getCodeGenOpts(); 817*7330f729Sjoerg llvm::Reloc::Model RM = CGOpts.RelocationModel; 818*7330f729Sjoerg const auto &LOpts = CGM.getLangOpts(); 819*7330f729Sjoerg if (RM != llvm::Reloc::Static && !LOpts.PIE && !LOpts.OpenMPIsDevice) 820*7330f729Sjoerg return false; 821*7330f729Sjoerg 822*7330f729Sjoerg // A definition cannot be preempted from an executable. 823*7330f729Sjoerg if (!GV->isDeclarationForLinker()) 824*7330f729Sjoerg return true; 825*7330f729Sjoerg 826*7330f729Sjoerg // Most PIC code sequences that assume that a symbol is local cannot produce a 827*7330f729Sjoerg // 0 if it turns out the symbol is undefined. While this is ABI and relocation 828*7330f729Sjoerg // depended, it seems worth it to handle it here. 829*7330f729Sjoerg if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage()) 830*7330f729Sjoerg return false; 831*7330f729Sjoerg 832*7330f729Sjoerg // PPC has no copy relocations and cannot use a plt entry as a symbol address. 833*7330f729Sjoerg llvm::Triple::ArchType Arch = TT.getArch(); 834*7330f729Sjoerg if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 || 835*7330f729Sjoerg Arch == llvm::Triple::ppc64le) 836*7330f729Sjoerg return false; 837*7330f729Sjoerg 838*7330f729Sjoerg // If we can use copy relocations we can assume it is local. 839*7330f729Sjoerg if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV)) 840*7330f729Sjoerg if (!Var->isThreadLocal() && 841*7330f729Sjoerg (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations)) 842*7330f729Sjoerg return true; 843*7330f729Sjoerg 844*7330f729Sjoerg // If we can use a plt entry as the symbol address we can assume it 845*7330f729Sjoerg // is local. 846*7330f729Sjoerg // FIXME: This should work for PIE, but the gold linker doesn't support it. 847*7330f729Sjoerg if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static) 848*7330f729Sjoerg return true; 849*7330f729Sjoerg 850*7330f729Sjoerg // Otherwise don't assue it is local. 851*7330f729Sjoerg return false; 852*7330f729Sjoerg } 853*7330f729Sjoerg 854*7330f729Sjoerg void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const { 855*7330f729Sjoerg GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV)); 856*7330f729Sjoerg } 857*7330f729Sjoerg 858*7330f729Sjoerg void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 859*7330f729Sjoerg GlobalDecl GD) const { 860*7330f729Sjoerg const auto *D = dyn_cast<NamedDecl>(GD.getDecl()); 861*7330f729Sjoerg // C++ destructors have a few C++ ABI specific special cases. 862*7330f729Sjoerg if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) { 863*7330f729Sjoerg getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType()); 864*7330f729Sjoerg return; 865*7330f729Sjoerg } 866*7330f729Sjoerg setDLLImportDLLExport(GV, D); 867*7330f729Sjoerg } 868*7330f729Sjoerg 869*7330f729Sjoerg void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 870*7330f729Sjoerg const NamedDecl *D) const { 871*7330f729Sjoerg if (D && D->isExternallyVisible()) { 872*7330f729Sjoerg if (D->hasAttr<DLLImportAttr>()) 873*7330f729Sjoerg GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 874*7330f729Sjoerg else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker()) 875*7330f729Sjoerg GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 876*7330f729Sjoerg } 877*7330f729Sjoerg } 878*7330f729Sjoerg 879*7330f729Sjoerg void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 880*7330f729Sjoerg GlobalDecl GD) const { 881*7330f729Sjoerg setDLLImportDLLExport(GV, GD); 882*7330f729Sjoerg setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl())); 883*7330f729Sjoerg } 884*7330f729Sjoerg 885*7330f729Sjoerg void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 886*7330f729Sjoerg const NamedDecl *D) const { 887*7330f729Sjoerg setDLLImportDLLExport(GV, D); 888*7330f729Sjoerg setGVPropertiesAux(GV, D); 889*7330f729Sjoerg } 890*7330f729Sjoerg 891*7330f729Sjoerg void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV, 892*7330f729Sjoerg const NamedDecl *D) const { 893*7330f729Sjoerg setGlobalVisibility(GV, D); 894*7330f729Sjoerg setDSOLocal(GV); 895*7330f729Sjoerg GV->setPartition(CodeGenOpts.SymbolPartition); 896*7330f729Sjoerg } 897*7330f729Sjoerg 898*7330f729Sjoerg static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 899*7330f729Sjoerg return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 900*7330f729Sjoerg .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 901*7330f729Sjoerg .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 902*7330f729Sjoerg .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 903*7330f729Sjoerg .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 904*7330f729Sjoerg } 905*7330f729Sjoerg 906*7330f729Sjoerg static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 907*7330f729Sjoerg CodeGenOptions::TLSModel M) { 908*7330f729Sjoerg switch (M) { 909*7330f729Sjoerg case CodeGenOptions::GeneralDynamicTLSModel: 910*7330f729Sjoerg return llvm::GlobalVariable::GeneralDynamicTLSModel; 911*7330f729Sjoerg case CodeGenOptions::LocalDynamicTLSModel: 912*7330f729Sjoerg return llvm::GlobalVariable::LocalDynamicTLSModel; 913*7330f729Sjoerg case CodeGenOptions::InitialExecTLSModel: 914*7330f729Sjoerg return llvm::GlobalVariable::InitialExecTLSModel; 915*7330f729Sjoerg case CodeGenOptions::LocalExecTLSModel: 916*7330f729Sjoerg return llvm::GlobalVariable::LocalExecTLSModel; 917*7330f729Sjoerg } 918*7330f729Sjoerg llvm_unreachable("Invalid TLS model!"); 919*7330f729Sjoerg } 920*7330f729Sjoerg 921*7330f729Sjoerg void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 922*7330f729Sjoerg assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 923*7330f729Sjoerg 924*7330f729Sjoerg llvm::GlobalValue::ThreadLocalMode TLM; 925*7330f729Sjoerg TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 926*7330f729Sjoerg 927*7330f729Sjoerg // Override the TLS model if it is explicitly specified. 928*7330f729Sjoerg if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 929*7330f729Sjoerg TLM = GetLLVMTLSModel(Attr->getModel()); 930*7330f729Sjoerg } 931*7330f729Sjoerg 932*7330f729Sjoerg GV->setThreadLocalMode(TLM); 933*7330f729Sjoerg } 934*7330f729Sjoerg 935*7330f729Sjoerg static std::string getCPUSpecificMangling(const CodeGenModule &CGM, 936*7330f729Sjoerg StringRef Name) { 937*7330f729Sjoerg const TargetInfo &Target = CGM.getTarget(); 938*7330f729Sjoerg return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str(); 939*7330f729Sjoerg } 940*7330f729Sjoerg 941*7330f729Sjoerg static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, 942*7330f729Sjoerg const CPUSpecificAttr *Attr, 943*7330f729Sjoerg unsigned CPUIndex, 944*7330f729Sjoerg raw_ostream &Out) { 945*7330f729Sjoerg // cpu_specific gets the current name, dispatch gets the resolver if IFunc is 946*7330f729Sjoerg // supported. 947*7330f729Sjoerg if (Attr) 948*7330f729Sjoerg Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName()); 949*7330f729Sjoerg else if (CGM.getTarget().supportsIFunc()) 950*7330f729Sjoerg Out << ".resolver"; 951*7330f729Sjoerg } 952*7330f729Sjoerg 953*7330f729Sjoerg static void AppendTargetMangling(const CodeGenModule &CGM, 954*7330f729Sjoerg const TargetAttr *Attr, raw_ostream &Out) { 955*7330f729Sjoerg if (Attr->isDefaultVersion()) 956*7330f729Sjoerg return; 957*7330f729Sjoerg 958*7330f729Sjoerg Out << '.'; 959*7330f729Sjoerg const TargetInfo &Target = CGM.getTarget(); 960*7330f729Sjoerg TargetAttr::ParsedTargetAttr Info = 961*7330f729Sjoerg Attr->parse([&Target](StringRef LHS, StringRef RHS) { 962*7330f729Sjoerg // Multiversioning doesn't allow "no-${feature}", so we can 963*7330f729Sjoerg // only have "+" prefixes here. 964*7330f729Sjoerg assert(LHS.startswith("+") && RHS.startswith("+") && 965*7330f729Sjoerg "Features should always have a prefix."); 966*7330f729Sjoerg return Target.multiVersionSortPriority(LHS.substr(1)) > 967*7330f729Sjoerg Target.multiVersionSortPriority(RHS.substr(1)); 968*7330f729Sjoerg }); 969*7330f729Sjoerg 970*7330f729Sjoerg bool IsFirst = true; 971*7330f729Sjoerg 972*7330f729Sjoerg if (!Info.Architecture.empty()) { 973*7330f729Sjoerg IsFirst = false; 974*7330f729Sjoerg Out << "arch_" << Info.Architecture; 975*7330f729Sjoerg } 976*7330f729Sjoerg 977*7330f729Sjoerg for (StringRef Feat : Info.Features) { 978*7330f729Sjoerg if (!IsFirst) 979*7330f729Sjoerg Out << '_'; 980*7330f729Sjoerg IsFirst = false; 981*7330f729Sjoerg Out << Feat.substr(1); 982*7330f729Sjoerg } 983*7330f729Sjoerg } 984*7330f729Sjoerg 985*7330f729Sjoerg static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD, 986*7330f729Sjoerg const NamedDecl *ND, 987*7330f729Sjoerg bool OmitMultiVersionMangling = false) { 988*7330f729Sjoerg SmallString<256> Buffer; 989*7330f729Sjoerg llvm::raw_svector_ostream Out(Buffer); 990*7330f729Sjoerg MangleContext &MC = CGM.getCXXABI().getMangleContext(); 991*7330f729Sjoerg if (MC.shouldMangleDeclName(ND)) { 992*7330f729Sjoerg llvm::raw_svector_ostream Out(Buffer); 993*7330f729Sjoerg if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) 994*7330f729Sjoerg MC.mangleCXXCtor(D, GD.getCtorType(), Out); 995*7330f729Sjoerg else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) 996*7330f729Sjoerg MC.mangleCXXDtor(D, GD.getDtorType(), Out); 997*7330f729Sjoerg else 998*7330f729Sjoerg MC.mangleName(ND, Out); 999*7330f729Sjoerg } else { 1000*7330f729Sjoerg IdentifierInfo *II = ND->getIdentifier(); 1001*7330f729Sjoerg assert(II && "Attempt to mangle unnamed decl."); 1002*7330f729Sjoerg const auto *FD = dyn_cast<FunctionDecl>(ND); 1003*7330f729Sjoerg 1004*7330f729Sjoerg if (FD && 1005*7330f729Sjoerg FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 1006*7330f729Sjoerg llvm::raw_svector_ostream Out(Buffer); 1007*7330f729Sjoerg Out << "__regcall3__" << II->getName(); 1008*7330f729Sjoerg } else { 1009*7330f729Sjoerg Out << II->getName(); 1010*7330f729Sjoerg } 1011*7330f729Sjoerg } 1012*7330f729Sjoerg 1013*7330f729Sjoerg if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 1014*7330f729Sjoerg if (FD->isMultiVersion() && !OmitMultiVersionMangling) { 1015*7330f729Sjoerg switch (FD->getMultiVersionKind()) { 1016*7330f729Sjoerg case MultiVersionKind::CPUDispatch: 1017*7330f729Sjoerg case MultiVersionKind::CPUSpecific: 1018*7330f729Sjoerg AppendCPUSpecificCPUDispatchMangling(CGM, 1019*7330f729Sjoerg FD->getAttr<CPUSpecificAttr>(), 1020*7330f729Sjoerg GD.getMultiVersionIndex(), Out); 1021*7330f729Sjoerg break; 1022*7330f729Sjoerg case MultiVersionKind::Target: 1023*7330f729Sjoerg AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out); 1024*7330f729Sjoerg break; 1025*7330f729Sjoerg case MultiVersionKind::None: 1026*7330f729Sjoerg llvm_unreachable("None multiversion type isn't valid here"); 1027*7330f729Sjoerg } 1028*7330f729Sjoerg } 1029*7330f729Sjoerg 1030*7330f729Sjoerg return Out.str(); 1031*7330f729Sjoerg } 1032*7330f729Sjoerg 1033*7330f729Sjoerg void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD, 1034*7330f729Sjoerg const FunctionDecl *FD) { 1035*7330f729Sjoerg if (!FD->isMultiVersion()) 1036*7330f729Sjoerg return; 1037*7330f729Sjoerg 1038*7330f729Sjoerg // Get the name of what this would be without the 'target' attribute. This 1039*7330f729Sjoerg // allows us to lookup the version that was emitted when this wasn't a 1040*7330f729Sjoerg // multiversion function. 1041*7330f729Sjoerg std::string NonTargetName = 1042*7330f729Sjoerg getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 1043*7330f729Sjoerg GlobalDecl OtherGD; 1044*7330f729Sjoerg if (lookupRepresentativeDecl(NonTargetName, OtherGD)) { 1045*7330f729Sjoerg assert(OtherGD.getCanonicalDecl() 1046*7330f729Sjoerg .getDecl() 1047*7330f729Sjoerg ->getAsFunction() 1048*7330f729Sjoerg ->isMultiVersion() && 1049*7330f729Sjoerg "Other GD should now be a multiversioned function"); 1050*7330f729Sjoerg // OtherFD is the version of this function that was mangled BEFORE 1051*7330f729Sjoerg // becoming a MultiVersion function. It potentially needs to be updated. 1052*7330f729Sjoerg const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl() 1053*7330f729Sjoerg .getDecl() 1054*7330f729Sjoerg ->getAsFunction() 1055*7330f729Sjoerg ->getMostRecentDecl(); 1056*7330f729Sjoerg std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD); 1057*7330f729Sjoerg // This is so that if the initial version was already the 'default' 1058*7330f729Sjoerg // version, we don't try to update it. 1059*7330f729Sjoerg if (OtherName != NonTargetName) { 1060*7330f729Sjoerg // Remove instead of erase, since others may have stored the StringRef 1061*7330f729Sjoerg // to this. 1062*7330f729Sjoerg const auto ExistingRecord = Manglings.find(NonTargetName); 1063*7330f729Sjoerg if (ExistingRecord != std::end(Manglings)) 1064*7330f729Sjoerg Manglings.remove(&(*ExistingRecord)); 1065*7330f729Sjoerg auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD)); 1066*7330f729Sjoerg MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first(); 1067*7330f729Sjoerg if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName)) 1068*7330f729Sjoerg Entry->setName(OtherName); 1069*7330f729Sjoerg } 1070*7330f729Sjoerg } 1071*7330f729Sjoerg } 1072*7330f729Sjoerg 1073*7330f729Sjoerg StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 1074*7330f729Sjoerg GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 1075*7330f729Sjoerg 1076*7330f729Sjoerg // Some ABIs don't have constructor variants. Make sure that base and 1077*7330f729Sjoerg // complete constructors get mangled the same. 1078*7330f729Sjoerg if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 1079*7330f729Sjoerg if (!getTarget().getCXXABI().hasConstructorVariants()) { 1080*7330f729Sjoerg CXXCtorType OrigCtorType = GD.getCtorType(); 1081*7330f729Sjoerg assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 1082*7330f729Sjoerg if (OrigCtorType == Ctor_Base) 1083*7330f729Sjoerg CanonicalGD = GlobalDecl(CD, Ctor_Complete); 1084*7330f729Sjoerg } 1085*7330f729Sjoerg } 1086*7330f729Sjoerg 1087*7330f729Sjoerg auto FoundName = MangledDeclNames.find(CanonicalGD); 1088*7330f729Sjoerg if (FoundName != MangledDeclNames.end()) 1089*7330f729Sjoerg return FoundName->second; 1090*7330f729Sjoerg 1091*7330f729Sjoerg // Keep the first result in the case of a mangling collision. 1092*7330f729Sjoerg const auto *ND = cast<NamedDecl>(GD.getDecl()); 1093*7330f729Sjoerg std::string MangledName = getMangledNameImpl(*this, GD, ND); 1094*7330f729Sjoerg 1095*7330f729Sjoerg // Adjust kernel stub mangling as we may need to be able to differentiate 1096*7330f729Sjoerg // them from the kernel itself (e.g., for HIP). 1097*7330f729Sjoerg if (auto *FD = dyn_cast<FunctionDecl>(GD.getDecl())) 1098*7330f729Sjoerg if (!getLangOpts().CUDAIsDevice && FD->hasAttr<CUDAGlobalAttr>()) 1099*7330f729Sjoerg MangledName = getCUDARuntime().getDeviceStubName(MangledName); 1100*7330f729Sjoerg 1101*7330f729Sjoerg auto Result = Manglings.insert(std::make_pair(MangledName, GD)); 1102*7330f729Sjoerg return MangledDeclNames[CanonicalGD] = Result.first->first(); 1103*7330f729Sjoerg } 1104*7330f729Sjoerg 1105*7330f729Sjoerg StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 1106*7330f729Sjoerg const BlockDecl *BD) { 1107*7330f729Sjoerg MangleContext &MangleCtx = getCXXABI().getMangleContext(); 1108*7330f729Sjoerg const Decl *D = GD.getDecl(); 1109*7330f729Sjoerg 1110*7330f729Sjoerg SmallString<256> Buffer; 1111*7330f729Sjoerg llvm::raw_svector_ostream Out(Buffer); 1112*7330f729Sjoerg if (!D) 1113*7330f729Sjoerg MangleCtx.mangleGlobalBlock(BD, 1114*7330f729Sjoerg dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 1115*7330f729Sjoerg else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 1116*7330f729Sjoerg MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 1117*7330f729Sjoerg else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 1118*7330f729Sjoerg MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 1119*7330f729Sjoerg else 1120*7330f729Sjoerg MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 1121*7330f729Sjoerg 1122*7330f729Sjoerg auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 1123*7330f729Sjoerg return Result.first->first(); 1124*7330f729Sjoerg } 1125*7330f729Sjoerg 1126*7330f729Sjoerg llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 1127*7330f729Sjoerg return getModule().getNamedValue(Name); 1128*7330f729Sjoerg } 1129*7330f729Sjoerg 1130*7330f729Sjoerg /// AddGlobalCtor - Add a function to the list that will be called before 1131*7330f729Sjoerg /// main() runs. 1132*7330f729Sjoerg void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 1133*7330f729Sjoerg llvm::Constant *AssociatedData) { 1134*7330f729Sjoerg // FIXME: Type coercion of void()* types. 1135*7330f729Sjoerg GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 1136*7330f729Sjoerg } 1137*7330f729Sjoerg 1138*7330f729Sjoerg /// AddGlobalDtor - Add a function to the list that will be called 1139*7330f729Sjoerg /// when the module is unloaded. 1140*7330f729Sjoerg void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) { 1141*7330f729Sjoerg if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) { 1142*7330f729Sjoerg DtorsUsingAtExit[Priority].push_back(Dtor); 1143*7330f729Sjoerg return; 1144*7330f729Sjoerg } 1145*7330f729Sjoerg 1146*7330f729Sjoerg // FIXME: Type coercion of void()* types. 1147*7330f729Sjoerg GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 1148*7330f729Sjoerg } 1149*7330f729Sjoerg 1150*7330f729Sjoerg void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 1151*7330f729Sjoerg if (Fns.empty()) return; 1152*7330f729Sjoerg 1153*7330f729Sjoerg // Ctor function type is void()*. 1154*7330f729Sjoerg llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 1155*7330f729Sjoerg llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy, 1156*7330f729Sjoerg TheModule.getDataLayout().getProgramAddressSpace()); 1157*7330f729Sjoerg 1158*7330f729Sjoerg // Get the type of a ctor entry, { i32, void ()*, i8* }. 1159*7330f729Sjoerg llvm::StructType *CtorStructTy = llvm::StructType::get( 1160*7330f729Sjoerg Int32Ty, CtorPFTy, VoidPtrTy); 1161*7330f729Sjoerg 1162*7330f729Sjoerg // Construct the constructor and destructor arrays. 1163*7330f729Sjoerg ConstantInitBuilder builder(*this); 1164*7330f729Sjoerg auto ctors = builder.beginArray(CtorStructTy); 1165*7330f729Sjoerg for (const auto &I : Fns) { 1166*7330f729Sjoerg auto ctor = ctors.beginStruct(CtorStructTy); 1167*7330f729Sjoerg ctor.addInt(Int32Ty, I.Priority); 1168*7330f729Sjoerg ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); 1169*7330f729Sjoerg if (I.AssociatedData) 1170*7330f729Sjoerg ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); 1171*7330f729Sjoerg else 1172*7330f729Sjoerg ctor.addNullPointer(VoidPtrTy); 1173*7330f729Sjoerg ctor.finishAndAddTo(ctors); 1174*7330f729Sjoerg } 1175*7330f729Sjoerg 1176*7330f729Sjoerg auto list = 1177*7330f729Sjoerg ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 1178*7330f729Sjoerg /*constant*/ false, 1179*7330f729Sjoerg llvm::GlobalValue::AppendingLinkage); 1180*7330f729Sjoerg 1181*7330f729Sjoerg // The LTO linker doesn't seem to like it when we set an alignment 1182*7330f729Sjoerg // on appending variables. Take it off as a workaround. 1183*7330f729Sjoerg list->setAlignment(llvm::None); 1184*7330f729Sjoerg 1185*7330f729Sjoerg Fns.clear(); 1186*7330f729Sjoerg } 1187*7330f729Sjoerg 1188*7330f729Sjoerg llvm::GlobalValue::LinkageTypes 1189*7330f729Sjoerg CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 1190*7330f729Sjoerg const auto *D = cast<FunctionDecl>(GD.getDecl()); 1191*7330f729Sjoerg 1192*7330f729Sjoerg GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 1193*7330f729Sjoerg 1194*7330f729Sjoerg if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D)) 1195*7330f729Sjoerg return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType()); 1196*7330f729Sjoerg 1197*7330f729Sjoerg if (isa<CXXConstructorDecl>(D) && 1198*7330f729Sjoerg cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 1199*7330f729Sjoerg Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1200*7330f729Sjoerg // Our approach to inheriting constructors is fundamentally different from 1201*7330f729Sjoerg // that used by the MS ABI, so keep our inheriting constructor thunks 1202*7330f729Sjoerg // internal rather than trying to pick an unambiguous mangling for them. 1203*7330f729Sjoerg return llvm::GlobalValue::InternalLinkage; 1204*7330f729Sjoerg } 1205*7330f729Sjoerg 1206*7330f729Sjoerg return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false); 1207*7330f729Sjoerg } 1208*7330f729Sjoerg 1209*7330f729Sjoerg llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 1210*7330f729Sjoerg llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 1211*7330f729Sjoerg if (!MDS) return nullptr; 1212*7330f729Sjoerg 1213*7330f729Sjoerg return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 1214*7330f729Sjoerg } 1215*7330f729Sjoerg 1216*7330f729Sjoerg void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD, 1217*7330f729Sjoerg const CGFunctionInfo &Info, 1218*7330f729Sjoerg llvm::Function *F) { 1219*7330f729Sjoerg unsigned CallingConv; 1220*7330f729Sjoerg llvm::AttributeList PAL; 1221*7330f729Sjoerg ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, false); 1222*7330f729Sjoerg F->setAttributes(PAL); 1223*7330f729Sjoerg F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 1224*7330f729Sjoerg } 1225*7330f729Sjoerg 1226*7330f729Sjoerg static void removeImageAccessQualifier(std::string& TyName) { 1227*7330f729Sjoerg std::string ReadOnlyQual("__read_only"); 1228*7330f729Sjoerg std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual); 1229*7330f729Sjoerg if (ReadOnlyPos != std::string::npos) 1230*7330f729Sjoerg // "+ 1" for the space after access qualifier. 1231*7330f729Sjoerg TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1); 1232*7330f729Sjoerg else { 1233*7330f729Sjoerg std::string WriteOnlyQual("__write_only"); 1234*7330f729Sjoerg std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual); 1235*7330f729Sjoerg if (WriteOnlyPos != std::string::npos) 1236*7330f729Sjoerg TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1); 1237*7330f729Sjoerg else { 1238*7330f729Sjoerg std::string ReadWriteQual("__read_write"); 1239*7330f729Sjoerg std::string::size_type ReadWritePos = TyName.find(ReadWriteQual); 1240*7330f729Sjoerg if (ReadWritePos != std::string::npos) 1241*7330f729Sjoerg TyName.erase(ReadWritePos, ReadWriteQual.size() + 1); 1242*7330f729Sjoerg } 1243*7330f729Sjoerg } 1244*7330f729Sjoerg } 1245*7330f729Sjoerg 1246*7330f729Sjoerg // Returns the address space id that should be produced to the 1247*7330f729Sjoerg // kernel_arg_addr_space metadata. This is always fixed to the ids 1248*7330f729Sjoerg // as specified in the SPIR 2.0 specification in order to differentiate 1249*7330f729Sjoerg // for example in clGetKernelArgInfo() implementation between the address 1250*7330f729Sjoerg // spaces with targets without unique mapping to the OpenCL address spaces 1251*7330f729Sjoerg // (basically all single AS CPUs). 1252*7330f729Sjoerg static unsigned ArgInfoAddressSpace(LangAS AS) { 1253*7330f729Sjoerg switch (AS) { 1254*7330f729Sjoerg case LangAS::opencl_global: return 1; 1255*7330f729Sjoerg case LangAS::opencl_constant: return 2; 1256*7330f729Sjoerg case LangAS::opencl_local: return 3; 1257*7330f729Sjoerg case LangAS::opencl_generic: return 4; // Not in SPIR 2.0 specs. 1258*7330f729Sjoerg default: 1259*7330f729Sjoerg return 0; // Assume private. 1260*7330f729Sjoerg } 1261*7330f729Sjoerg } 1262*7330f729Sjoerg 1263*7330f729Sjoerg void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn, 1264*7330f729Sjoerg const FunctionDecl *FD, 1265*7330f729Sjoerg CodeGenFunction *CGF) { 1266*7330f729Sjoerg assert(((FD && CGF) || (!FD && !CGF)) && 1267*7330f729Sjoerg "Incorrect use - FD and CGF should either be both null or not!"); 1268*7330f729Sjoerg // Create MDNodes that represent the kernel arg metadata. 1269*7330f729Sjoerg // Each MDNode is a list in the form of "key", N number of values which is 1270*7330f729Sjoerg // the same number of values as their are kernel arguments. 1271*7330f729Sjoerg 1272*7330f729Sjoerg const PrintingPolicy &Policy = Context.getPrintingPolicy(); 1273*7330f729Sjoerg 1274*7330f729Sjoerg // MDNode for the kernel argument address space qualifiers. 1275*7330f729Sjoerg SmallVector<llvm::Metadata *, 8> addressQuals; 1276*7330f729Sjoerg 1277*7330f729Sjoerg // MDNode for the kernel argument access qualifiers (images only). 1278*7330f729Sjoerg SmallVector<llvm::Metadata *, 8> accessQuals; 1279*7330f729Sjoerg 1280*7330f729Sjoerg // MDNode for the kernel argument type names. 1281*7330f729Sjoerg SmallVector<llvm::Metadata *, 8> argTypeNames; 1282*7330f729Sjoerg 1283*7330f729Sjoerg // MDNode for the kernel argument base type names. 1284*7330f729Sjoerg SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 1285*7330f729Sjoerg 1286*7330f729Sjoerg // MDNode for the kernel argument type qualifiers. 1287*7330f729Sjoerg SmallVector<llvm::Metadata *, 8> argTypeQuals; 1288*7330f729Sjoerg 1289*7330f729Sjoerg // MDNode for the kernel argument names. 1290*7330f729Sjoerg SmallVector<llvm::Metadata *, 8> argNames; 1291*7330f729Sjoerg 1292*7330f729Sjoerg if (FD && CGF) 1293*7330f729Sjoerg for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 1294*7330f729Sjoerg const ParmVarDecl *parm = FD->getParamDecl(i); 1295*7330f729Sjoerg QualType ty = parm->getType(); 1296*7330f729Sjoerg std::string typeQuals; 1297*7330f729Sjoerg 1298*7330f729Sjoerg if (ty->isPointerType()) { 1299*7330f729Sjoerg QualType pointeeTy = ty->getPointeeType(); 1300*7330f729Sjoerg 1301*7330f729Sjoerg // Get address qualifier. 1302*7330f729Sjoerg addressQuals.push_back( 1303*7330f729Sjoerg llvm::ConstantAsMetadata::get(CGF->Builder.getInt32( 1304*7330f729Sjoerg ArgInfoAddressSpace(pointeeTy.getAddressSpace())))); 1305*7330f729Sjoerg 1306*7330f729Sjoerg // Get argument type name. 1307*7330f729Sjoerg std::string typeName = 1308*7330f729Sjoerg pointeeTy.getUnqualifiedType().getAsString(Policy) + "*"; 1309*7330f729Sjoerg 1310*7330f729Sjoerg // Turn "unsigned type" to "utype" 1311*7330f729Sjoerg std::string::size_type pos = typeName.find("unsigned"); 1312*7330f729Sjoerg if (pointeeTy.isCanonical() && pos != std::string::npos) 1313*7330f729Sjoerg typeName.erase(pos + 1, 8); 1314*7330f729Sjoerg 1315*7330f729Sjoerg argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 1316*7330f729Sjoerg 1317*7330f729Sjoerg std::string baseTypeName = 1318*7330f729Sjoerg pointeeTy.getUnqualifiedType().getCanonicalType().getAsString( 1319*7330f729Sjoerg Policy) + 1320*7330f729Sjoerg "*"; 1321*7330f729Sjoerg 1322*7330f729Sjoerg // Turn "unsigned type" to "utype" 1323*7330f729Sjoerg pos = baseTypeName.find("unsigned"); 1324*7330f729Sjoerg if (pos != std::string::npos) 1325*7330f729Sjoerg baseTypeName.erase(pos + 1, 8); 1326*7330f729Sjoerg 1327*7330f729Sjoerg argBaseTypeNames.push_back( 1328*7330f729Sjoerg llvm::MDString::get(VMContext, baseTypeName)); 1329*7330f729Sjoerg 1330*7330f729Sjoerg // Get argument type qualifiers: 1331*7330f729Sjoerg if (ty.isRestrictQualified()) 1332*7330f729Sjoerg typeQuals = "restrict"; 1333*7330f729Sjoerg if (pointeeTy.isConstQualified() || 1334*7330f729Sjoerg (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 1335*7330f729Sjoerg typeQuals += typeQuals.empty() ? "const" : " const"; 1336*7330f729Sjoerg if (pointeeTy.isVolatileQualified()) 1337*7330f729Sjoerg typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 1338*7330f729Sjoerg } else { 1339*7330f729Sjoerg uint32_t AddrSpc = 0; 1340*7330f729Sjoerg bool isPipe = ty->isPipeType(); 1341*7330f729Sjoerg if (ty->isImageType() || isPipe) 1342*7330f729Sjoerg AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global); 1343*7330f729Sjoerg 1344*7330f729Sjoerg addressQuals.push_back( 1345*7330f729Sjoerg llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc))); 1346*7330f729Sjoerg 1347*7330f729Sjoerg // Get argument type name. 1348*7330f729Sjoerg std::string typeName; 1349*7330f729Sjoerg if (isPipe) 1350*7330f729Sjoerg typeName = ty.getCanonicalType() 1351*7330f729Sjoerg ->getAs<PipeType>() 1352*7330f729Sjoerg ->getElementType() 1353*7330f729Sjoerg .getAsString(Policy); 1354*7330f729Sjoerg else 1355*7330f729Sjoerg typeName = ty.getUnqualifiedType().getAsString(Policy); 1356*7330f729Sjoerg 1357*7330f729Sjoerg // Turn "unsigned type" to "utype" 1358*7330f729Sjoerg std::string::size_type pos = typeName.find("unsigned"); 1359*7330f729Sjoerg if (ty.isCanonical() && pos != std::string::npos) 1360*7330f729Sjoerg typeName.erase(pos + 1, 8); 1361*7330f729Sjoerg 1362*7330f729Sjoerg std::string baseTypeName; 1363*7330f729Sjoerg if (isPipe) 1364*7330f729Sjoerg baseTypeName = ty.getCanonicalType() 1365*7330f729Sjoerg ->getAs<PipeType>() 1366*7330f729Sjoerg ->getElementType() 1367*7330f729Sjoerg .getCanonicalType() 1368*7330f729Sjoerg .getAsString(Policy); 1369*7330f729Sjoerg else 1370*7330f729Sjoerg baseTypeName = 1371*7330f729Sjoerg ty.getUnqualifiedType().getCanonicalType().getAsString(Policy); 1372*7330f729Sjoerg 1373*7330f729Sjoerg // Remove access qualifiers on images 1374*7330f729Sjoerg // (as they are inseparable from type in clang implementation, 1375*7330f729Sjoerg // but OpenCL spec provides a special query to get access qualifier 1376*7330f729Sjoerg // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): 1377*7330f729Sjoerg if (ty->isImageType()) { 1378*7330f729Sjoerg removeImageAccessQualifier(typeName); 1379*7330f729Sjoerg removeImageAccessQualifier(baseTypeName); 1380*7330f729Sjoerg } 1381*7330f729Sjoerg 1382*7330f729Sjoerg argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 1383*7330f729Sjoerg 1384*7330f729Sjoerg // Turn "unsigned type" to "utype" 1385*7330f729Sjoerg pos = baseTypeName.find("unsigned"); 1386*7330f729Sjoerg if (pos != std::string::npos) 1387*7330f729Sjoerg baseTypeName.erase(pos + 1, 8); 1388*7330f729Sjoerg 1389*7330f729Sjoerg argBaseTypeNames.push_back( 1390*7330f729Sjoerg llvm::MDString::get(VMContext, baseTypeName)); 1391*7330f729Sjoerg 1392*7330f729Sjoerg if (isPipe) 1393*7330f729Sjoerg typeQuals = "pipe"; 1394*7330f729Sjoerg } 1395*7330f729Sjoerg 1396*7330f729Sjoerg argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals)); 1397*7330f729Sjoerg 1398*7330f729Sjoerg // Get image and pipe access qualifier: 1399*7330f729Sjoerg if (ty->isImageType() || ty->isPipeType()) { 1400*7330f729Sjoerg const Decl *PDecl = parm; 1401*7330f729Sjoerg if (auto *TD = dyn_cast<TypedefType>(ty)) 1402*7330f729Sjoerg PDecl = TD->getDecl(); 1403*7330f729Sjoerg const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>(); 1404*7330f729Sjoerg if (A && A->isWriteOnly()) 1405*7330f729Sjoerg accessQuals.push_back(llvm::MDString::get(VMContext, "write_only")); 1406*7330f729Sjoerg else if (A && A->isReadWrite()) 1407*7330f729Sjoerg accessQuals.push_back(llvm::MDString::get(VMContext, "read_write")); 1408*7330f729Sjoerg else 1409*7330f729Sjoerg accessQuals.push_back(llvm::MDString::get(VMContext, "read_only")); 1410*7330f729Sjoerg } else 1411*7330f729Sjoerg accessQuals.push_back(llvm::MDString::get(VMContext, "none")); 1412*7330f729Sjoerg 1413*7330f729Sjoerg // Get argument name. 1414*7330f729Sjoerg argNames.push_back(llvm::MDString::get(VMContext, parm->getName())); 1415*7330f729Sjoerg } 1416*7330f729Sjoerg 1417*7330f729Sjoerg Fn->setMetadata("kernel_arg_addr_space", 1418*7330f729Sjoerg llvm::MDNode::get(VMContext, addressQuals)); 1419*7330f729Sjoerg Fn->setMetadata("kernel_arg_access_qual", 1420*7330f729Sjoerg llvm::MDNode::get(VMContext, accessQuals)); 1421*7330f729Sjoerg Fn->setMetadata("kernel_arg_type", 1422*7330f729Sjoerg llvm::MDNode::get(VMContext, argTypeNames)); 1423*7330f729Sjoerg Fn->setMetadata("kernel_arg_base_type", 1424*7330f729Sjoerg llvm::MDNode::get(VMContext, argBaseTypeNames)); 1425*7330f729Sjoerg Fn->setMetadata("kernel_arg_type_qual", 1426*7330f729Sjoerg llvm::MDNode::get(VMContext, argTypeQuals)); 1427*7330f729Sjoerg if (getCodeGenOpts().EmitOpenCLArgMetadata) 1428*7330f729Sjoerg Fn->setMetadata("kernel_arg_name", 1429*7330f729Sjoerg llvm::MDNode::get(VMContext, argNames)); 1430*7330f729Sjoerg } 1431*7330f729Sjoerg 1432*7330f729Sjoerg /// Determines whether the language options require us to model 1433*7330f729Sjoerg /// unwind exceptions. We treat -fexceptions as mandating this 1434*7330f729Sjoerg /// except under the fragile ObjC ABI with only ObjC exceptions 1435*7330f729Sjoerg /// enabled. This means, for example, that C with -fexceptions 1436*7330f729Sjoerg /// enables this. 1437*7330f729Sjoerg static bool hasUnwindExceptions(const LangOptions &LangOpts) { 1438*7330f729Sjoerg // If exceptions are completely disabled, obviously this is false. 1439*7330f729Sjoerg if (!LangOpts.Exceptions) return false; 1440*7330f729Sjoerg 1441*7330f729Sjoerg // If C++ exceptions are enabled, this is true. 1442*7330f729Sjoerg if (LangOpts.CXXExceptions) return true; 1443*7330f729Sjoerg 1444*7330f729Sjoerg // If ObjC exceptions are enabled, this depends on the ABI. 1445*7330f729Sjoerg if (LangOpts.ObjCExceptions) { 1446*7330f729Sjoerg return LangOpts.ObjCRuntime.hasUnwindExceptions(); 1447*7330f729Sjoerg } 1448*7330f729Sjoerg 1449*7330f729Sjoerg return true; 1450*7330f729Sjoerg } 1451*7330f729Sjoerg 1452*7330f729Sjoerg static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, 1453*7330f729Sjoerg const CXXMethodDecl *MD) { 1454*7330f729Sjoerg // Check that the type metadata can ever actually be used by a call. 1455*7330f729Sjoerg if (!CGM.getCodeGenOpts().LTOUnit || 1456*7330f729Sjoerg !CGM.HasHiddenLTOVisibility(MD->getParent())) 1457*7330f729Sjoerg return false; 1458*7330f729Sjoerg 1459*7330f729Sjoerg // Only functions whose address can be taken with a member function pointer 1460*7330f729Sjoerg // need this sort of type metadata. 1461*7330f729Sjoerg return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) && 1462*7330f729Sjoerg !isa<CXXDestructorDecl>(MD); 1463*7330f729Sjoerg } 1464*7330f729Sjoerg 1465*7330f729Sjoerg std::vector<const CXXRecordDecl *> 1466*7330f729Sjoerg CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) { 1467*7330f729Sjoerg llvm::SetVector<const CXXRecordDecl *> MostBases; 1468*7330f729Sjoerg 1469*7330f729Sjoerg std::function<void (const CXXRecordDecl *)> CollectMostBases; 1470*7330f729Sjoerg CollectMostBases = [&](const CXXRecordDecl *RD) { 1471*7330f729Sjoerg if (RD->getNumBases() == 0) 1472*7330f729Sjoerg MostBases.insert(RD); 1473*7330f729Sjoerg for (const CXXBaseSpecifier &B : RD->bases()) 1474*7330f729Sjoerg CollectMostBases(B.getType()->getAsCXXRecordDecl()); 1475*7330f729Sjoerg }; 1476*7330f729Sjoerg CollectMostBases(RD); 1477*7330f729Sjoerg return MostBases.takeVector(); 1478*7330f729Sjoerg } 1479*7330f729Sjoerg 1480*7330f729Sjoerg void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 1481*7330f729Sjoerg llvm::Function *F) { 1482*7330f729Sjoerg llvm::AttrBuilder B; 1483*7330f729Sjoerg 1484*7330f729Sjoerg if (CodeGenOpts.UnwindTables) 1485*7330f729Sjoerg B.addAttribute(llvm::Attribute::UWTable); 1486*7330f729Sjoerg 1487*7330f729Sjoerg if (!hasUnwindExceptions(LangOpts)) 1488*7330f729Sjoerg B.addAttribute(llvm::Attribute::NoUnwind); 1489*7330f729Sjoerg 1490*7330f729Sjoerg if (!D || !D->hasAttr<NoStackProtectorAttr>()) { 1491*7330f729Sjoerg if (LangOpts.getStackProtector() == LangOptions::SSPOn) 1492*7330f729Sjoerg B.addAttribute(llvm::Attribute::StackProtect); 1493*7330f729Sjoerg else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 1494*7330f729Sjoerg B.addAttribute(llvm::Attribute::StackProtectStrong); 1495*7330f729Sjoerg else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 1496*7330f729Sjoerg B.addAttribute(llvm::Attribute::StackProtectReq); 1497*7330f729Sjoerg } 1498*7330f729Sjoerg 1499*7330f729Sjoerg if (!D) { 1500*7330f729Sjoerg // If we don't have a declaration to control inlining, the function isn't 1501*7330f729Sjoerg // explicitly marked as alwaysinline for semantic reasons, and inlining is 1502*7330f729Sjoerg // disabled, mark the function as noinline. 1503*7330f729Sjoerg if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 1504*7330f729Sjoerg CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 1505*7330f729Sjoerg B.addAttribute(llvm::Attribute::NoInline); 1506*7330f729Sjoerg 1507*7330f729Sjoerg F->addAttributes(llvm::AttributeList::FunctionIndex, B); 1508*7330f729Sjoerg return; 1509*7330f729Sjoerg } 1510*7330f729Sjoerg 1511*7330f729Sjoerg // Track whether we need to add the optnone LLVM attribute, 1512*7330f729Sjoerg // starting with the default for this optimization level. 1513*7330f729Sjoerg bool ShouldAddOptNone = 1514*7330f729Sjoerg !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 1515*7330f729Sjoerg // We can't add optnone in the following cases, it won't pass the verifier. 1516*7330f729Sjoerg ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 1517*7330f729Sjoerg ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline); 1518*7330f729Sjoerg ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 1519*7330f729Sjoerg 1520*7330f729Sjoerg if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) { 1521*7330f729Sjoerg B.addAttribute(llvm::Attribute::OptimizeNone); 1522*7330f729Sjoerg 1523*7330f729Sjoerg // OptimizeNone implies noinline; we should not be inlining such functions. 1524*7330f729Sjoerg B.addAttribute(llvm::Attribute::NoInline); 1525*7330f729Sjoerg assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 1526*7330f729Sjoerg "OptimizeNone and AlwaysInline on same function!"); 1527*7330f729Sjoerg 1528*7330f729Sjoerg // We still need to handle naked functions even though optnone subsumes 1529*7330f729Sjoerg // much of their semantics. 1530*7330f729Sjoerg if (D->hasAttr<NakedAttr>()) 1531*7330f729Sjoerg B.addAttribute(llvm::Attribute::Naked); 1532*7330f729Sjoerg 1533*7330f729Sjoerg // OptimizeNone wins over OptimizeForSize and MinSize. 1534*7330f729Sjoerg F->removeFnAttr(llvm::Attribute::OptimizeForSize); 1535*7330f729Sjoerg F->removeFnAttr(llvm::Attribute::MinSize); 1536*7330f729Sjoerg } else if (D->hasAttr<NakedAttr>()) { 1537*7330f729Sjoerg // Naked implies noinline: we should not be inlining such functions. 1538*7330f729Sjoerg B.addAttribute(llvm::Attribute::Naked); 1539*7330f729Sjoerg B.addAttribute(llvm::Attribute::NoInline); 1540*7330f729Sjoerg } else if (D->hasAttr<NoDuplicateAttr>()) { 1541*7330f729Sjoerg B.addAttribute(llvm::Attribute::NoDuplicate); 1542*7330f729Sjoerg } else if (D->hasAttr<NoInlineAttr>()) { 1543*7330f729Sjoerg B.addAttribute(llvm::Attribute::NoInline); 1544*7330f729Sjoerg } else if (D->hasAttr<AlwaysInlineAttr>() && 1545*7330f729Sjoerg !F->hasFnAttribute(llvm::Attribute::NoInline)) { 1546*7330f729Sjoerg // (noinline wins over always_inline, and we can't specify both in IR) 1547*7330f729Sjoerg B.addAttribute(llvm::Attribute::AlwaysInline); 1548*7330f729Sjoerg } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 1549*7330f729Sjoerg // If we're not inlining, then force everything that isn't always_inline to 1550*7330f729Sjoerg // carry an explicit noinline attribute. 1551*7330f729Sjoerg if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 1552*7330f729Sjoerg B.addAttribute(llvm::Attribute::NoInline); 1553*7330f729Sjoerg } else { 1554*7330f729Sjoerg // Otherwise, propagate the inline hint attribute and potentially use its 1555*7330f729Sjoerg // absence to mark things as noinline. 1556*7330f729Sjoerg if (auto *FD = dyn_cast<FunctionDecl>(D)) { 1557*7330f729Sjoerg // Search function and template pattern redeclarations for inline. 1558*7330f729Sjoerg auto CheckForInline = [](const FunctionDecl *FD) { 1559*7330f729Sjoerg auto CheckRedeclForInline = [](const FunctionDecl *Redecl) { 1560*7330f729Sjoerg return Redecl->isInlineSpecified(); 1561*7330f729Sjoerg }; 1562*7330f729Sjoerg if (any_of(FD->redecls(), CheckRedeclForInline)) 1563*7330f729Sjoerg return true; 1564*7330f729Sjoerg const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(); 1565*7330f729Sjoerg if (!Pattern) 1566*7330f729Sjoerg return false; 1567*7330f729Sjoerg return any_of(Pattern->redecls(), CheckRedeclForInline); 1568*7330f729Sjoerg }; 1569*7330f729Sjoerg if (CheckForInline(FD)) { 1570*7330f729Sjoerg B.addAttribute(llvm::Attribute::InlineHint); 1571*7330f729Sjoerg } else if (CodeGenOpts.getInlining() == 1572*7330f729Sjoerg CodeGenOptions::OnlyHintInlining && 1573*7330f729Sjoerg !FD->isInlined() && 1574*7330f729Sjoerg !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1575*7330f729Sjoerg B.addAttribute(llvm::Attribute::NoInline); 1576*7330f729Sjoerg } 1577*7330f729Sjoerg } 1578*7330f729Sjoerg } 1579*7330f729Sjoerg 1580*7330f729Sjoerg // Add other optimization related attributes if we are optimizing this 1581*7330f729Sjoerg // function. 1582*7330f729Sjoerg if (!D->hasAttr<OptimizeNoneAttr>()) { 1583*7330f729Sjoerg if (D->hasAttr<ColdAttr>()) { 1584*7330f729Sjoerg if (!ShouldAddOptNone) 1585*7330f729Sjoerg B.addAttribute(llvm::Attribute::OptimizeForSize); 1586*7330f729Sjoerg B.addAttribute(llvm::Attribute::Cold); 1587*7330f729Sjoerg } 1588*7330f729Sjoerg 1589*7330f729Sjoerg if (D->hasAttr<MinSizeAttr>()) 1590*7330f729Sjoerg B.addAttribute(llvm::Attribute::MinSize); 1591*7330f729Sjoerg } 1592*7330f729Sjoerg 1593*7330f729Sjoerg F->addAttributes(llvm::AttributeList::FunctionIndex, B); 1594*7330f729Sjoerg 1595*7330f729Sjoerg unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 1596*7330f729Sjoerg if (alignment) 1597*7330f729Sjoerg F->setAlignment(llvm::Align(alignment)); 1598*7330f729Sjoerg 1599*7330f729Sjoerg if (!D->hasAttr<AlignedAttr>()) 1600*7330f729Sjoerg if (LangOpts.FunctionAlignment) 1601*7330f729Sjoerg F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment)); 1602*7330f729Sjoerg 1603*7330f729Sjoerg // Some C++ ABIs require 2-byte alignment for member functions, in order to 1604*7330f729Sjoerg // reserve a bit for differentiating between virtual and non-virtual member 1605*7330f729Sjoerg // functions. If the current target's C++ ABI requires this and this is a 1606*7330f729Sjoerg // member function, set its alignment accordingly. 1607*7330f729Sjoerg if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 1608*7330f729Sjoerg if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 1609*7330f729Sjoerg F->setAlignment(llvm::Align(2)); 1610*7330f729Sjoerg } 1611*7330f729Sjoerg 1612*7330f729Sjoerg // In the cross-dso CFI mode with canonical jump tables, we want !type 1613*7330f729Sjoerg // attributes on definitions only. 1614*7330f729Sjoerg if (CodeGenOpts.SanitizeCfiCrossDso && 1615*7330f729Sjoerg CodeGenOpts.SanitizeCfiCanonicalJumpTables) { 1616*7330f729Sjoerg if (auto *FD = dyn_cast<FunctionDecl>(D)) { 1617*7330f729Sjoerg // Skip available_externally functions. They won't be codegen'ed in the 1618*7330f729Sjoerg // current module anyway. 1619*7330f729Sjoerg if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally) 1620*7330f729Sjoerg CreateFunctionTypeMetadataForIcall(FD, F); 1621*7330f729Sjoerg } 1622*7330f729Sjoerg } 1623*7330f729Sjoerg 1624*7330f729Sjoerg // Emit type metadata on member functions for member function pointer checks. 1625*7330f729Sjoerg // These are only ever necessary on definitions; we're guaranteed that the 1626*7330f729Sjoerg // definition will be present in the LTO unit as a result of LTO visibility. 1627*7330f729Sjoerg auto *MD = dyn_cast<CXXMethodDecl>(D); 1628*7330f729Sjoerg if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) { 1629*7330f729Sjoerg for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) { 1630*7330f729Sjoerg llvm::Metadata *Id = 1631*7330f729Sjoerg CreateMetadataIdentifierForType(Context.getMemberPointerType( 1632*7330f729Sjoerg MD->getType(), Context.getRecordType(Base).getTypePtr())); 1633*7330f729Sjoerg F->addTypeMetadata(0, Id); 1634*7330f729Sjoerg } 1635*7330f729Sjoerg } 1636*7330f729Sjoerg } 1637*7330f729Sjoerg 1638*7330f729Sjoerg void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) { 1639*7330f729Sjoerg const Decl *D = GD.getDecl(); 1640*7330f729Sjoerg if (dyn_cast_or_null<NamedDecl>(D)) 1641*7330f729Sjoerg setGVProperties(GV, GD); 1642*7330f729Sjoerg else 1643*7330f729Sjoerg GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 1644*7330f729Sjoerg 1645*7330f729Sjoerg if (D && D->hasAttr<UsedAttr>()) 1646*7330f729Sjoerg addUsedGlobal(GV); 1647*7330f729Sjoerg 1648*7330f729Sjoerg if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) { 1649*7330f729Sjoerg const auto *VD = cast<VarDecl>(D); 1650*7330f729Sjoerg if (VD->getType().isConstQualified() && 1651*7330f729Sjoerg VD->getStorageDuration() == SD_Static) 1652*7330f729Sjoerg addUsedGlobal(GV); 1653*7330f729Sjoerg } 1654*7330f729Sjoerg } 1655*7330f729Sjoerg 1656*7330f729Sjoerg bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD, 1657*7330f729Sjoerg llvm::AttrBuilder &Attrs) { 1658*7330f729Sjoerg // Add target-cpu and target-features attributes to functions. If 1659*7330f729Sjoerg // we have a decl for the function and it has a target attribute then 1660*7330f729Sjoerg // parse that and add it to the feature set. 1661*7330f729Sjoerg StringRef TargetCPU = getTarget().getTargetOpts().CPU; 1662*7330f729Sjoerg std::vector<std::string> Features; 1663*7330f729Sjoerg const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl()); 1664*7330f729Sjoerg FD = FD ? FD->getMostRecentDecl() : FD; 1665*7330f729Sjoerg const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr; 1666*7330f729Sjoerg const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr; 1667*7330f729Sjoerg bool AddedAttr = false; 1668*7330f729Sjoerg if (TD || SD) { 1669*7330f729Sjoerg llvm::StringMap<bool> FeatureMap; 1670*7330f729Sjoerg getFunctionFeatureMap(FeatureMap, GD); 1671*7330f729Sjoerg 1672*7330f729Sjoerg // Produce the canonical string for this set of features. 1673*7330f729Sjoerg for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap) 1674*7330f729Sjoerg Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str()); 1675*7330f729Sjoerg 1676*7330f729Sjoerg // Now add the target-cpu and target-features to the function. 1677*7330f729Sjoerg // While we populated the feature map above, we still need to 1678*7330f729Sjoerg // get and parse the target attribute so we can get the cpu for 1679*7330f729Sjoerg // the function. 1680*7330f729Sjoerg if (TD) { 1681*7330f729Sjoerg TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); 1682*7330f729Sjoerg if (ParsedAttr.Architecture != "" && 1683*7330f729Sjoerg getTarget().isValidCPUName(ParsedAttr.Architecture)) 1684*7330f729Sjoerg TargetCPU = ParsedAttr.Architecture; 1685*7330f729Sjoerg } 1686*7330f729Sjoerg } else { 1687*7330f729Sjoerg // Otherwise just add the existing target cpu and target features to the 1688*7330f729Sjoerg // function. 1689*7330f729Sjoerg Features = getTarget().getTargetOpts().Features; 1690*7330f729Sjoerg } 1691*7330f729Sjoerg 1692*7330f729Sjoerg if (TargetCPU != "") { 1693*7330f729Sjoerg Attrs.addAttribute("target-cpu", TargetCPU); 1694*7330f729Sjoerg AddedAttr = true; 1695*7330f729Sjoerg } 1696*7330f729Sjoerg if (!Features.empty()) { 1697*7330f729Sjoerg llvm::sort(Features); 1698*7330f729Sjoerg Attrs.addAttribute("target-features", llvm::join(Features, ",")); 1699*7330f729Sjoerg AddedAttr = true; 1700*7330f729Sjoerg } 1701*7330f729Sjoerg 1702*7330f729Sjoerg return AddedAttr; 1703*7330f729Sjoerg } 1704*7330f729Sjoerg 1705*7330f729Sjoerg void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, 1706*7330f729Sjoerg llvm::GlobalObject *GO) { 1707*7330f729Sjoerg const Decl *D = GD.getDecl(); 1708*7330f729Sjoerg SetCommonAttributes(GD, GO); 1709*7330f729Sjoerg 1710*7330f729Sjoerg if (D) { 1711*7330f729Sjoerg if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 1712*7330f729Sjoerg if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 1713*7330f729Sjoerg GV->addAttribute("bss-section", SA->getName()); 1714*7330f729Sjoerg if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 1715*7330f729Sjoerg GV->addAttribute("data-section", SA->getName()); 1716*7330f729Sjoerg if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 1717*7330f729Sjoerg GV->addAttribute("rodata-section", SA->getName()); 1718*7330f729Sjoerg if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) 1719*7330f729Sjoerg GV->addAttribute("relro-section", SA->getName()); 1720*7330f729Sjoerg } 1721*7330f729Sjoerg 1722*7330f729Sjoerg if (auto *F = dyn_cast<llvm::Function>(GO)) { 1723*7330f729Sjoerg if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 1724*7330f729Sjoerg if (!D->getAttr<SectionAttr>()) 1725*7330f729Sjoerg F->addFnAttr("implicit-section-name", SA->getName()); 1726*7330f729Sjoerg 1727*7330f729Sjoerg llvm::AttrBuilder Attrs; 1728*7330f729Sjoerg if (GetCPUAndFeaturesAttributes(GD, Attrs)) { 1729*7330f729Sjoerg // We know that GetCPUAndFeaturesAttributes will always have the 1730*7330f729Sjoerg // newest set, since it has the newest possible FunctionDecl, so the 1731*7330f729Sjoerg // new ones should replace the old. 1732*7330f729Sjoerg F->removeFnAttr("target-cpu"); 1733*7330f729Sjoerg F->removeFnAttr("target-features"); 1734*7330f729Sjoerg F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs); 1735*7330f729Sjoerg } 1736*7330f729Sjoerg } 1737*7330f729Sjoerg 1738*7330f729Sjoerg if (const auto *CSA = D->getAttr<CodeSegAttr>()) 1739*7330f729Sjoerg GO->setSection(CSA->getName()); 1740*7330f729Sjoerg else if (const auto *SA = D->getAttr<SectionAttr>()) 1741*7330f729Sjoerg GO->setSection(SA->getName()); 1742*7330f729Sjoerg } 1743*7330f729Sjoerg 1744*7330f729Sjoerg getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 1745*7330f729Sjoerg } 1746*7330f729Sjoerg 1747*7330f729Sjoerg void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, 1748*7330f729Sjoerg llvm::Function *F, 1749*7330f729Sjoerg const CGFunctionInfo &FI) { 1750*7330f729Sjoerg const Decl *D = GD.getDecl(); 1751*7330f729Sjoerg SetLLVMFunctionAttributes(GD, FI, F); 1752*7330f729Sjoerg SetLLVMFunctionAttributesForDefinition(D, F); 1753*7330f729Sjoerg 1754*7330f729Sjoerg F->setLinkage(llvm::Function::InternalLinkage); 1755*7330f729Sjoerg 1756*7330f729Sjoerg setNonAliasAttributes(GD, F); 1757*7330f729Sjoerg } 1758*7330f729Sjoerg 1759*7330f729Sjoerg static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { 1760*7330f729Sjoerg // Set linkage and visibility in case we never see a definition. 1761*7330f729Sjoerg LinkageInfo LV = ND->getLinkageAndVisibility(); 1762*7330f729Sjoerg // Don't set internal linkage on declarations. 1763*7330f729Sjoerg // "extern_weak" is overloaded in LLVM; we probably should have 1764*7330f729Sjoerg // separate linkage types for this. 1765*7330f729Sjoerg if (isExternallyVisible(LV.getLinkage()) && 1766*7330f729Sjoerg (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) 1767*7330f729Sjoerg GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 1768*7330f729Sjoerg } 1769*7330f729Sjoerg 1770*7330f729Sjoerg void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 1771*7330f729Sjoerg llvm::Function *F) { 1772*7330f729Sjoerg // Only if we are checking indirect calls. 1773*7330f729Sjoerg if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 1774*7330f729Sjoerg return; 1775*7330f729Sjoerg 1776*7330f729Sjoerg // Non-static class methods are handled via vtable or member function pointer 1777*7330f729Sjoerg // checks elsewhere. 1778*7330f729Sjoerg if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 1779*7330f729Sjoerg return; 1780*7330f729Sjoerg 1781*7330f729Sjoerg llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 1782*7330f729Sjoerg F->addTypeMetadata(0, MD); 1783*7330f729Sjoerg F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); 1784*7330f729Sjoerg 1785*7330f729Sjoerg // Emit a hash-based bit set entry for cross-DSO calls. 1786*7330f729Sjoerg if (CodeGenOpts.SanitizeCfiCrossDso) 1787*7330f729Sjoerg if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 1788*7330f729Sjoerg F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 1789*7330f729Sjoerg } 1790*7330f729Sjoerg 1791*7330f729Sjoerg void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 1792*7330f729Sjoerg bool IsIncompleteFunction, 1793*7330f729Sjoerg bool IsThunk) { 1794*7330f729Sjoerg 1795*7330f729Sjoerg if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 1796*7330f729Sjoerg // If this is an intrinsic function, set the function's attributes 1797*7330f729Sjoerg // to the intrinsic's attributes. 1798*7330f729Sjoerg F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 1799*7330f729Sjoerg return; 1800*7330f729Sjoerg } 1801*7330f729Sjoerg 1802*7330f729Sjoerg const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1803*7330f729Sjoerg 1804*7330f729Sjoerg if (!IsIncompleteFunction) 1805*7330f729Sjoerg SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F); 1806*7330f729Sjoerg 1807*7330f729Sjoerg // Add the Returned attribute for "this", except for iOS 5 and earlier 1808*7330f729Sjoerg // where substantial code, including the libstdc++ dylib, was compiled with 1809*7330f729Sjoerg // GCC and does not actually return "this". 1810*7330f729Sjoerg if (!IsThunk && getCXXABI().HasThisReturn(GD) && 1811*7330f729Sjoerg !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 1812*7330f729Sjoerg assert(!F->arg_empty() && 1813*7330f729Sjoerg F->arg_begin()->getType() 1814*7330f729Sjoerg ->canLosslesslyBitCastTo(F->getReturnType()) && 1815*7330f729Sjoerg "unexpected this return"); 1816*7330f729Sjoerg F->addAttribute(1, llvm::Attribute::Returned); 1817*7330f729Sjoerg } 1818*7330f729Sjoerg 1819*7330f729Sjoerg // Only a few attributes are set on declarations; these may later be 1820*7330f729Sjoerg // overridden by a definition. 1821*7330f729Sjoerg 1822*7330f729Sjoerg setLinkageForGV(F, FD); 1823*7330f729Sjoerg setGVProperties(F, FD); 1824*7330f729Sjoerg 1825*7330f729Sjoerg // Setup target-specific attributes. 1826*7330f729Sjoerg if (!IsIncompleteFunction && F->isDeclaration()) 1827*7330f729Sjoerg getTargetCodeGenInfo().setTargetAttributes(FD, F, *this); 1828*7330f729Sjoerg 1829*7330f729Sjoerg if (const auto *CSA = FD->getAttr<CodeSegAttr>()) 1830*7330f729Sjoerg F->setSection(CSA->getName()); 1831*7330f729Sjoerg else if (const auto *SA = FD->getAttr<SectionAttr>()) 1832*7330f729Sjoerg F->setSection(SA->getName()); 1833*7330f729Sjoerg 1834*7330f729Sjoerg if (FD->isReplaceableGlobalAllocationFunction()) { 1835*7330f729Sjoerg // A replaceable global allocation function does not act like a builtin by 1836*7330f729Sjoerg // default, only if it is invoked by a new-expression or delete-expression. 1837*7330f729Sjoerg F->addAttribute(llvm::AttributeList::FunctionIndex, 1838*7330f729Sjoerg llvm::Attribute::NoBuiltin); 1839*7330f729Sjoerg 1840*7330f729Sjoerg // A sane operator new returns a non-aliasing pointer. 1841*7330f729Sjoerg // FIXME: Also add NonNull attribute to the return value 1842*7330f729Sjoerg // for the non-nothrow forms? 1843*7330f729Sjoerg auto Kind = FD->getDeclName().getCXXOverloadedOperator(); 1844*7330f729Sjoerg if (getCodeGenOpts().AssumeSaneOperatorNew && 1845*7330f729Sjoerg (Kind == OO_New || Kind == OO_Array_New)) 1846*7330f729Sjoerg F->addAttribute(llvm::AttributeList::ReturnIndex, 1847*7330f729Sjoerg llvm::Attribute::NoAlias); 1848*7330f729Sjoerg } 1849*7330f729Sjoerg 1850*7330f729Sjoerg if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 1851*7330f729Sjoerg F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1852*7330f729Sjoerg else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 1853*7330f729Sjoerg if (MD->isVirtual()) 1854*7330f729Sjoerg F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1855*7330f729Sjoerg 1856*7330f729Sjoerg // Don't emit entries for function declarations in the cross-DSO mode. This 1857*7330f729Sjoerg // is handled with better precision by the receiving DSO. But if jump tables 1858*7330f729Sjoerg // are non-canonical then we need type metadata in order to produce the local 1859*7330f729Sjoerg // jump table. 1860*7330f729Sjoerg if (!CodeGenOpts.SanitizeCfiCrossDso || 1861*7330f729Sjoerg !CodeGenOpts.SanitizeCfiCanonicalJumpTables) 1862*7330f729Sjoerg CreateFunctionTypeMetadataForIcall(FD, F); 1863*7330f729Sjoerg 1864*7330f729Sjoerg if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 1865*7330f729Sjoerg getOpenMPRuntime().emitDeclareSimdFunction(FD, F); 1866*7330f729Sjoerg 1867*7330f729Sjoerg if (const auto *CB = FD->getAttr<CallbackAttr>()) { 1868*7330f729Sjoerg // Annotate the callback behavior as metadata: 1869*7330f729Sjoerg // - The callback callee (as argument number). 1870*7330f729Sjoerg // - The callback payloads (as argument numbers). 1871*7330f729Sjoerg llvm::LLVMContext &Ctx = F->getContext(); 1872*7330f729Sjoerg llvm::MDBuilder MDB(Ctx); 1873*7330f729Sjoerg 1874*7330f729Sjoerg // The payload indices are all but the first one in the encoding. The first 1875*7330f729Sjoerg // identifies the callback callee. 1876*7330f729Sjoerg int CalleeIdx = *CB->encoding_begin(); 1877*7330f729Sjoerg ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); 1878*7330f729Sjoerg F->addMetadata(llvm::LLVMContext::MD_callback, 1879*7330f729Sjoerg *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( 1880*7330f729Sjoerg CalleeIdx, PayloadIndices, 1881*7330f729Sjoerg /* VarArgsArePassed */ false)})); 1882*7330f729Sjoerg } 1883*7330f729Sjoerg } 1884*7330f729Sjoerg 1885*7330f729Sjoerg void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 1886*7330f729Sjoerg assert(!GV->isDeclaration() && 1887*7330f729Sjoerg "Only globals with definition can force usage."); 1888*7330f729Sjoerg LLVMUsed.emplace_back(GV); 1889*7330f729Sjoerg } 1890*7330f729Sjoerg 1891*7330f729Sjoerg void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 1892*7330f729Sjoerg assert(!GV->isDeclaration() && 1893*7330f729Sjoerg "Only globals with definition can force usage."); 1894*7330f729Sjoerg LLVMCompilerUsed.emplace_back(GV); 1895*7330f729Sjoerg } 1896*7330f729Sjoerg 1897*7330f729Sjoerg static void emitUsed(CodeGenModule &CGM, StringRef Name, 1898*7330f729Sjoerg std::vector<llvm::WeakTrackingVH> &List) { 1899*7330f729Sjoerg // Don't create llvm.used if there is no need. 1900*7330f729Sjoerg if (List.empty()) 1901*7330f729Sjoerg return; 1902*7330f729Sjoerg 1903*7330f729Sjoerg // Convert List to what ConstantArray needs. 1904*7330f729Sjoerg SmallVector<llvm::Constant*, 8> UsedArray; 1905*7330f729Sjoerg UsedArray.resize(List.size()); 1906*7330f729Sjoerg for (unsigned i = 0, e = List.size(); i != e; ++i) { 1907*7330f729Sjoerg UsedArray[i] = 1908*7330f729Sjoerg llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 1909*7330f729Sjoerg cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 1910*7330f729Sjoerg } 1911*7330f729Sjoerg 1912*7330f729Sjoerg if (UsedArray.empty()) 1913*7330f729Sjoerg return; 1914*7330f729Sjoerg llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 1915*7330f729Sjoerg 1916*7330f729Sjoerg auto *GV = new llvm::GlobalVariable( 1917*7330f729Sjoerg CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 1918*7330f729Sjoerg llvm::ConstantArray::get(ATy, UsedArray), Name); 1919*7330f729Sjoerg 1920*7330f729Sjoerg GV->setSection("llvm.metadata"); 1921*7330f729Sjoerg } 1922*7330f729Sjoerg 1923*7330f729Sjoerg void CodeGenModule::emitLLVMUsed() { 1924*7330f729Sjoerg emitUsed(*this, "llvm.used", LLVMUsed); 1925*7330f729Sjoerg emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 1926*7330f729Sjoerg } 1927*7330f729Sjoerg 1928*7330f729Sjoerg void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 1929*7330f729Sjoerg auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 1930*7330f729Sjoerg LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1931*7330f729Sjoerg } 1932*7330f729Sjoerg 1933*7330f729Sjoerg void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 1934*7330f729Sjoerg llvm::SmallString<32> Opt; 1935*7330f729Sjoerg getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 1936*7330f729Sjoerg auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1937*7330f729Sjoerg LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1938*7330f729Sjoerg } 1939*7330f729Sjoerg 1940*7330f729Sjoerg void CodeGenModule::AddDependentLib(StringRef Lib) { 1941*7330f729Sjoerg auto &C = getLLVMContext(); 1942*7330f729Sjoerg if (getTarget().getTriple().isOSBinFormatELF()) { 1943*7330f729Sjoerg ELFDependentLibraries.push_back( 1944*7330f729Sjoerg llvm::MDNode::get(C, llvm::MDString::get(C, Lib))); 1945*7330f729Sjoerg return; 1946*7330f729Sjoerg } 1947*7330f729Sjoerg 1948*7330f729Sjoerg llvm::SmallString<24> Opt; 1949*7330f729Sjoerg getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 1950*7330f729Sjoerg auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1951*7330f729Sjoerg LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts)); 1952*7330f729Sjoerg } 1953*7330f729Sjoerg 1954*7330f729Sjoerg /// Add link options implied by the given module, including modules 1955*7330f729Sjoerg /// it depends on, using a postorder walk. 1956*7330f729Sjoerg static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 1957*7330f729Sjoerg SmallVectorImpl<llvm::MDNode *> &Metadata, 1958*7330f729Sjoerg llvm::SmallPtrSet<Module *, 16> &Visited) { 1959*7330f729Sjoerg // Import this module's parent. 1960*7330f729Sjoerg if (Mod->Parent && Visited.insert(Mod->Parent).second) { 1961*7330f729Sjoerg addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 1962*7330f729Sjoerg } 1963*7330f729Sjoerg 1964*7330f729Sjoerg // Import this module's dependencies. 1965*7330f729Sjoerg for (unsigned I = Mod->Imports.size(); I > 0; --I) { 1966*7330f729Sjoerg if (Visited.insert(Mod->Imports[I - 1]).second) 1967*7330f729Sjoerg addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 1968*7330f729Sjoerg } 1969*7330f729Sjoerg 1970*7330f729Sjoerg // Add linker options to link against the libraries/frameworks 1971*7330f729Sjoerg // described by this module. 1972*7330f729Sjoerg llvm::LLVMContext &Context = CGM.getLLVMContext(); 1973*7330f729Sjoerg bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); 1974*7330f729Sjoerg 1975*7330f729Sjoerg // For modules that use export_as for linking, use that module 1976*7330f729Sjoerg // name instead. 1977*7330f729Sjoerg if (Mod->UseExportAsModuleLinkName) 1978*7330f729Sjoerg return; 1979*7330f729Sjoerg 1980*7330f729Sjoerg for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 1981*7330f729Sjoerg // Link against a framework. Frameworks are currently Darwin only, so we 1982*7330f729Sjoerg // don't to ask TargetCodeGenInfo for the spelling of the linker option. 1983*7330f729Sjoerg if (Mod->LinkLibraries[I-1].IsFramework) { 1984*7330f729Sjoerg llvm::Metadata *Args[2] = { 1985*7330f729Sjoerg llvm::MDString::get(Context, "-framework"), 1986*7330f729Sjoerg llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 1987*7330f729Sjoerg 1988*7330f729Sjoerg Metadata.push_back(llvm::MDNode::get(Context, Args)); 1989*7330f729Sjoerg continue; 1990*7330f729Sjoerg } 1991*7330f729Sjoerg 1992*7330f729Sjoerg // Link against a library. 1993*7330f729Sjoerg if (IsELF) { 1994*7330f729Sjoerg llvm::Metadata *Args[2] = { 1995*7330f729Sjoerg llvm::MDString::get(Context, "lib"), 1996*7330f729Sjoerg llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library), 1997*7330f729Sjoerg }; 1998*7330f729Sjoerg Metadata.push_back(llvm::MDNode::get(Context, Args)); 1999*7330f729Sjoerg } else { 2000*7330f729Sjoerg llvm::SmallString<24> Opt; 2001*7330f729Sjoerg CGM.getTargetCodeGenInfo().getDependentLibraryOption( 2002*7330f729Sjoerg Mod->LinkLibraries[I - 1].Library, Opt); 2003*7330f729Sjoerg auto *OptString = llvm::MDString::get(Context, Opt); 2004*7330f729Sjoerg Metadata.push_back(llvm::MDNode::get(Context, OptString)); 2005*7330f729Sjoerg } 2006*7330f729Sjoerg } 2007*7330f729Sjoerg } 2008*7330f729Sjoerg 2009*7330f729Sjoerg void CodeGenModule::EmitModuleLinkOptions() { 2010*7330f729Sjoerg // Collect the set of all of the modules we want to visit to emit link 2011*7330f729Sjoerg // options, which is essentially the imported modules and all of their 2012*7330f729Sjoerg // non-explicit child modules. 2013*7330f729Sjoerg llvm::SetVector<clang::Module *> LinkModules; 2014*7330f729Sjoerg llvm::SmallPtrSet<clang::Module *, 16> Visited; 2015*7330f729Sjoerg SmallVector<clang::Module *, 16> Stack; 2016*7330f729Sjoerg 2017*7330f729Sjoerg // Seed the stack with imported modules. 2018*7330f729Sjoerg for (Module *M : ImportedModules) { 2019*7330f729Sjoerg // Do not add any link flags when an implementation TU of a module imports 2020*7330f729Sjoerg // a header of that same module. 2021*7330f729Sjoerg if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 2022*7330f729Sjoerg !getLangOpts().isCompilingModule()) 2023*7330f729Sjoerg continue; 2024*7330f729Sjoerg if (Visited.insert(M).second) 2025*7330f729Sjoerg Stack.push_back(M); 2026*7330f729Sjoerg } 2027*7330f729Sjoerg 2028*7330f729Sjoerg // Find all of the modules to import, making a little effort to prune 2029*7330f729Sjoerg // non-leaf modules. 2030*7330f729Sjoerg while (!Stack.empty()) { 2031*7330f729Sjoerg clang::Module *Mod = Stack.pop_back_val(); 2032*7330f729Sjoerg 2033*7330f729Sjoerg bool AnyChildren = false; 2034*7330f729Sjoerg 2035*7330f729Sjoerg // Visit the submodules of this module. 2036*7330f729Sjoerg for (const auto &SM : Mod->submodules()) { 2037*7330f729Sjoerg // Skip explicit children; they need to be explicitly imported to be 2038*7330f729Sjoerg // linked against. 2039*7330f729Sjoerg if (SM->IsExplicit) 2040*7330f729Sjoerg continue; 2041*7330f729Sjoerg 2042*7330f729Sjoerg if (Visited.insert(SM).second) { 2043*7330f729Sjoerg Stack.push_back(SM); 2044*7330f729Sjoerg AnyChildren = true; 2045*7330f729Sjoerg } 2046*7330f729Sjoerg } 2047*7330f729Sjoerg 2048*7330f729Sjoerg // We didn't find any children, so add this module to the list of 2049*7330f729Sjoerg // modules to link against. 2050*7330f729Sjoerg if (!AnyChildren) { 2051*7330f729Sjoerg LinkModules.insert(Mod); 2052*7330f729Sjoerg } 2053*7330f729Sjoerg } 2054*7330f729Sjoerg 2055*7330f729Sjoerg // Add link options for all of the imported modules in reverse topological 2056*7330f729Sjoerg // order. We don't do anything to try to order import link flags with respect 2057*7330f729Sjoerg // to linker options inserted by things like #pragma comment(). 2058*7330f729Sjoerg SmallVector<llvm::MDNode *, 16> MetadataArgs; 2059*7330f729Sjoerg Visited.clear(); 2060*7330f729Sjoerg for (Module *M : LinkModules) 2061*7330f729Sjoerg if (Visited.insert(M).second) 2062*7330f729Sjoerg addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 2063*7330f729Sjoerg std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 2064*7330f729Sjoerg LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 2065*7330f729Sjoerg 2066*7330f729Sjoerg // Add the linker options metadata flag. 2067*7330f729Sjoerg auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 2068*7330f729Sjoerg for (auto *MD : LinkerOptionsMetadata) 2069*7330f729Sjoerg NMD->addOperand(MD); 2070*7330f729Sjoerg } 2071*7330f729Sjoerg 2072*7330f729Sjoerg void CodeGenModule::EmitDeferred() { 2073*7330f729Sjoerg // Emit deferred declare target declarations. 2074*7330f729Sjoerg if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 2075*7330f729Sjoerg getOpenMPRuntime().emitDeferredTargetDecls(); 2076*7330f729Sjoerg 2077*7330f729Sjoerg // Emit code for any potentially referenced deferred decls. Since a 2078*7330f729Sjoerg // previously unused static decl may become used during the generation of code 2079*7330f729Sjoerg // for a static function, iterate until no changes are made. 2080*7330f729Sjoerg 2081*7330f729Sjoerg if (!DeferredVTables.empty()) { 2082*7330f729Sjoerg EmitDeferredVTables(); 2083*7330f729Sjoerg 2084*7330f729Sjoerg // Emitting a vtable doesn't directly cause more vtables to 2085*7330f729Sjoerg // become deferred, although it can cause functions to be 2086*7330f729Sjoerg // emitted that then need those vtables. 2087*7330f729Sjoerg assert(DeferredVTables.empty()); 2088*7330f729Sjoerg } 2089*7330f729Sjoerg 2090*7330f729Sjoerg // Stop if we're out of both deferred vtables and deferred declarations. 2091*7330f729Sjoerg if (DeferredDeclsToEmit.empty()) 2092*7330f729Sjoerg return; 2093*7330f729Sjoerg 2094*7330f729Sjoerg // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 2095*7330f729Sjoerg // work, it will not interfere with this. 2096*7330f729Sjoerg std::vector<GlobalDecl> CurDeclsToEmit; 2097*7330f729Sjoerg CurDeclsToEmit.swap(DeferredDeclsToEmit); 2098*7330f729Sjoerg 2099*7330f729Sjoerg for (GlobalDecl &D : CurDeclsToEmit) { 2100*7330f729Sjoerg // We should call GetAddrOfGlobal with IsForDefinition set to true in order 2101*7330f729Sjoerg // to get GlobalValue with exactly the type we need, not something that 2102*7330f729Sjoerg // might had been created for another decl with the same mangled name but 2103*7330f729Sjoerg // different type. 2104*7330f729Sjoerg llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 2105*7330f729Sjoerg GetAddrOfGlobal(D, ForDefinition)); 2106*7330f729Sjoerg 2107*7330f729Sjoerg // In case of different address spaces, we may still get a cast, even with 2108*7330f729Sjoerg // IsForDefinition equal to true. Query mangled names table to get 2109*7330f729Sjoerg // GlobalValue. 2110*7330f729Sjoerg if (!GV) 2111*7330f729Sjoerg GV = GetGlobalValue(getMangledName(D)); 2112*7330f729Sjoerg 2113*7330f729Sjoerg // Make sure GetGlobalValue returned non-null. 2114*7330f729Sjoerg assert(GV); 2115*7330f729Sjoerg 2116*7330f729Sjoerg // Check to see if we've already emitted this. This is necessary 2117*7330f729Sjoerg // for a couple of reasons: first, decls can end up in the 2118*7330f729Sjoerg // deferred-decls queue multiple times, and second, decls can end 2119*7330f729Sjoerg // up with definitions in unusual ways (e.g. by an extern inline 2120*7330f729Sjoerg // function acquiring a strong function redefinition). Just 2121*7330f729Sjoerg // ignore these cases. 2122*7330f729Sjoerg if (!GV->isDeclaration()) 2123*7330f729Sjoerg continue; 2124*7330f729Sjoerg 2125*7330f729Sjoerg // If this is OpenMP, check if it is legal to emit this global normally. 2126*7330f729Sjoerg if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D)) 2127*7330f729Sjoerg continue; 2128*7330f729Sjoerg 2129*7330f729Sjoerg // Otherwise, emit the definition and move on to the next one. 2130*7330f729Sjoerg EmitGlobalDefinition(D, GV); 2131*7330f729Sjoerg 2132*7330f729Sjoerg // If we found out that we need to emit more decls, do that recursively. 2133*7330f729Sjoerg // This has the advantage that the decls are emitted in a DFS and related 2134*7330f729Sjoerg // ones are close together, which is convenient for testing. 2135*7330f729Sjoerg if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 2136*7330f729Sjoerg EmitDeferred(); 2137*7330f729Sjoerg assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 2138*7330f729Sjoerg } 2139*7330f729Sjoerg } 2140*7330f729Sjoerg } 2141*7330f729Sjoerg 2142*7330f729Sjoerg void CodeGenModule::EmitVTablesOpportunistically() { 2143*7330f729Sjoerg // Try to emit external vtables as available_externally if they have emitted 2144*7330f729Sjoerg // all inlined virtual functions. It runs after EmitDeferred() and therefore 2145*7330f729Sjoerg // is not allowed to create new references to things that need to be emitted 2146*7330f729Sjoerg // lazily. Note that it also uses fact that we eagerly emitting RTTI. 2147*7330f729Sjoerg 2148*7330f729Sjoerg assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 2149*7330f729Sjoerg && "Only emit opportunistic vtables with optimizations"); 2150*7330f729Sjoerg 2151*7330f729Sjoerg for (const CXXRecordDecl *RD : OpportunisticVTables) { 2152*7330f729Sjoerg assert(getVTables().isVTableExternal(RD) && 2153*7330f729Sjoerg "This queue should only contain external vtables"); 2154*7330f729Sjoerg if (getCXXABI().canSpeculativelyEmitVTable(RD)) 2155*7330f729Sjoerg VTables.GenerateClassData(RD); 2156*7330f729Sjoerg } 2157*7330f729Sjoerg OpportunisticVTables.clear(); 2158*7330f729Sjoerg } 2159*7330f729Sjoerg 2160*7330f729Sjoerg void CodeGenModule::EmitGlobalAnnotations() { 2161*7330f729Sjoerg if (Annotations.empty()) 2162*7330f729Sjoerg return; 2163*7330f729Sjoerg 2164*7330f729Sjoerg // Create a new global variable for the ConstantStruct in the Module. 2165*7330f729Sjoerg llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 2166*7330f729Sjoerg Annotations[0]->getType(), Annotations.size()), Annotations); 2167*7330f729Sjoerg auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 2168*7330f729Sjoerg llvm::GlobalValue::AppendingLinkage, 2169*7330f729Sjoerg Array, "llvm.global.annotations"); 2170*7330f729Sjoerg gv->setSection(AnnotationSection); 2171*7330f729Sjoerg } 2172*7330f729Sjoerg 2173*7330f729Sjoerg llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 2174*7330f729Sjoerg llvm::Constant *&AStr = AnnotationStrings[Str]; 2175*7330f729Sjoerg if (AStr) 2176*7330f729Sjoerg return AStr; 2177*7330f729Sjoerg 2178*7330f729Sjoerg // Not found yet, create a new global. 2179*7330f729Sjoerg llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 2180*7330f729Sjoerg auto *gv = 2181*7330f729Sjoerg new llvm::GlobalVariable(getModule(), s->getType(), true, 2182*7330f729Sjoerg llvm::GlobalValue::PrivateLinkage, s, ".str"); 2183*7330f729Sjoerg gv->setSection(AnnotationSection); 2184*7330f729Sjoerg gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2185*7330f729Sjoerg AStr = gv; 2186*7330f729Sjoerg return gv; 2187*7330f729Sjoerg } 2188*7330f729Sjoerg 2189*7330f729Sjoerg llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 2190*7330f729Sjoerg SourceManager &SM = getContext().getSourceManager(); 2191*7330f729Sjoerg PresumedLoc PLoc = SM.getPresumedLoc(Loc); 2192*7330f729Sjoerg if (PLoc.isValid()) 2193*7330f729Sjoerg return EmitAnnotationString(PLoc.getFilename()); 2194*7330f729Sjoerg return EmitAnnotationString(SM.getBufferName(Loc)); 2195*7330f729Sjoerg } 2196*7330f729Sjoerg 2197*7330f729Sjoerg llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 2198*7330f729Sjoerg SourceManager &SM = getContext().getSourceManager(); 2199*7330f729Sjoerg PresumedLoc PLoc = SM.getPresumedLoc(L); 2200*7330f729Sjoerg unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 2201*7330f729Sjoerg SM.getExpansionLineNumber(L); 2202*7330f729Sjoerg return llvm::ConstantInt::get(Int32Ty, LineNo); 2203*7330f729Sjoerg } 2204*7330f729Sjoerg 2205*7330f729Sjoerg llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 2206*7330f729Sjoerg const AnnotateAttr *AA, 2207*7330f729Sjoerg SourceLocation L) { 2208*7330f729Sjoerg // Get the globals for file name, annotation, and the line number. 2209*7330f729Sjoerg llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 2210*7330f729Sjoerg *UnitGV = EmitAnnotationUnit(L), 2211*7330f729Sjoerg *LineNoCst = EmitAnnotationLineNo(L); 2212*7330f729Sjoerg 2213*7330f729Sjoerg // Create the ConstantStruct for the global annotation. 2214*7330f729Sjoerg llvm::Constant *Fields[4] = { 2215*7330f729Sjoerg llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 2216*7330f729Sjoerg llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 2217*7330f729Sjoerg llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 2218*7330f729Sjoerg LineNoCst 2219*7330f729Sjoerg }; 2220*7330f729Sjoerg return llvm::ConstantStruct::getAnon(Fields); 2221*7330f729Sjoerg } 2222*7330f729Sjoerg 2223*7330f729Sjoerg void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 2224*7330f729Sjoerg llvm::GlobalValue *GV) { 2225*7330f729Sjoerg assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2226*7330f729Sjoerg // Get the struct elements for these annotations. 2227*7330f729Sjoerg for (const auto *I : D->specific_attrs<AnnotateAttr>()) 2228*7330f729Sjoerg Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 2229*7330f729Sjoerg } 2230*7330f729Sjoerg 2231*7330f729Sjoerg bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind, 2232*7330f729Sjoerg llvm::Function *Fn, 2233*7330f729Sjoerg SourceLocation Loc) const { 2234*7330f729Sjoerg const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 2235*7330f729Sjoerg // Blacklist by function name. 2236*7330f729Sjoerg if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName())) 2237*7330f729Sjoerg return true; 2238*7330f729Sjoerg // Blacklist by location. 2239*7330f729Sjoerg if (Loc.isValid()) 2240*7330f729Sjoerg return SanitizerBL.isBlacklistedLocation(Kind, Loc); 2241*7330f729Sjoerg // If location is unknown, this may be a compiler-generated function. Assume 2242*7330f729Sjoerg // it's located in the main file. 2243*7330f729Sjoerg auto &SM = Context.getSourceManager(); 2244*7330f729Sjoerg if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 2245*7330f729Sjoerg return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName()); 2246*7330f729Sjoerg } 2247*7330f729Sjoerg return false; 2248*7330f729Sjoerg } 2249*7330f729Sjoerg 2250*7330f729Sjoerg bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 2251*7330f729Sjoerg SourceLocation Loc, QualType Ty, 2252*7330f729Sjoerg StringRef Category) const { 2253*7330f729Sjoerg // For now globals can be blacklisted only in ASan and KASan. 2254*7330f729Sjoerg const SanitizerMask EnabledAsanMask = 2255*7330f729Sjoerg LangOpts.Sanitize.Mask & 2256*7330f729Sjoerg (SanitizerKind::Address | SanitizerKind::KernelAddress | 2257*7330f729Sjoerg SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress | 2258*7330f729Sjoerg SanitizerKind::MemTag); 2259*7330f729Sjoerg if (!EnabledAsanMask) 2260*7330f729Sjoerg return false; 2261*7330f729Sjoerg const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 2262*7330f729Sjoerg if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category)) 2263*7330f729Sjoerg return true; 2264*7330f729Sjoerg if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category)) 2265*7330f729Sjoerg return true; 2266*7330f729Sjoerg // Check global type. 2267*7330f729Sjoerg if (!Ty.isNull()) { 2268*7330f729Sjoerg // Drill down the array types: if global variable of a fixed type is 2269*7330f729Sjoerg // blacklisted, we also don't instrument arrays of them. 2270*7330f729Sjoerg while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 2271*7330f729Sjoerg Ty = AT->getElementType(); 2272*7330f729Sjoerg Ty = Ty.getCanonicalType().getUnqualifiedType(); 2273*7330f729Sjoerg // We allow to blacklist only record types (classes, structs etc.) 2274*7330f729Sjoerg if (Ty->isRecordType()) { 2275*7330f729Sjoerg std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 2276*7330f729Sjoerg if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category)) 2277*7330f729Sjoerg return true; 2278*7330f729Sjoerg } 2279*7330f729Sjoerg } 2280*7330f729Sjoerg return false; 2281*7330f729Sjoerg } 2282*7330f729Sjoerg 2283*7330f729Sjoerg bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 2284*7330f729Sjoerg StringRef Category) const { 2285*7330f729Sjoerg const auto &XRayFilter = getContext().getXRayFilter(); 2286*7330f729Sjoerg using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 2287*7330f729Sjoerg auto Attr = ImbueAttr::NONE; 2288*7330f729Sjoerg if (Loc.isValid()) 2289*7330f729Sjoerg Attr = XRayFilter.shouldImbueLocation(Loc, Category); 2290*7330f729Sjoerg if (Attr == ImbueAttr::NONE) 2291*7330f729Sjoerg Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 2292*7330f729Sjoerg switch (Attr) { 2293*7330f729Sjoerg case ImbueAttr::NONE: 2294*7330f729Sjoerg return false; 2295*7330f729Sjoerg case ImbueAttr::ALWAYS: 2296*7330f729Sjoerg Fn->addFnAttr("function-instrument", "xray-always"); 2297*7330f729Sjoerg break; 2298*7330f729Sjoerg case ImbueAttr::ALWAYS_ARG1: 2299*7330f729Sjoerg Fn->addFnAttr("function-instrument", "xray-always"); 2300*7330f729Sjoerg Fn->addFnAttr("xray-log-args", "1"); 2301*7330f729Sjoerg break; 2302*7330f729Sjoerg case ImbueAttr::NEVER: 2303*7330f729Sjoerg Fn->addFnAttr("function-instrument", "xray-never"); 2304*7330f729Sjoerg break; 2305*7330f729Sjoerg } 2306*7330f729Sjoerg return true; 2307*7330f729Sjoerg } 2308*7330f729Sjoerg 2309*7330f729Sjoerg bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 2310*7330f729Sjoerg // Never defer when EmitAllDecls is specified. 2311*7330f729Sjoerg if (LangOpts.EmitAllDecls) 2312*7330f729Sjoerg return true; 2313*7330f729Sjoerg 2314*7330f729Sjoerg if (CodeGenOpts.KeepStaticConsts) { 2315*7330f729Sjoerg const auto *VD = dyn_cast<VarDecl>(Global); 2316*7330f729Sjoerg if (VD && VD->getType().isConstQualified() && 2317*7330f729Sjoerg VD->getStorageDuration() == SD_Static) 2318*7330f729Sjoerg return true; 2319*7330f729Sjoerg } 2320*7330f729Sjoerg 2321*7330f729Sjoerg return getContext().DeclMustBeEmitted(Global); 2322*7330f729Sjoerg } 2323*7330f729Sjoerg 2324*7330f729Sjoerg bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 2325*7330f729Sjoerg if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 2326*7330f729Sjoerg if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 2327*7330f729Sjoerg // Implicit template instantiations may change linkage if they are later 2328*7330f729Sjoerg // explicitly instantiated, so they should not be emitted eagerly. 2329*7330f729Sjoerg return false; 2330*7330f729Sjoerg // In OpenMP 5.0 function may be marked as device_type(nohost) and we should 2331*7330f729Sjoerg // not emit them eagerly unless we sure that the function must be emitted on 2332*7330f729Sjoerg // the host. 2333*7330f729Sjoerg if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd && 2334*7330f729Sjoerg !LangOpts.OpenMPIsDevice && 2335*7330f729Sjoerg !OMPDeclareTargetDeclAttr::getDeviceType(FD) && 2336*7330f729Sjoerg !FD->isUsed(/*CheckUsedAttr=*/false) && !FD->isReferenced()) 2337*7330f729Sjoerg return false; 2338*7330f729Sjoerg } 2339*7330f729Sjoerg if (const auto *VD = dyn_cast<VarDecl>(Global)) 2340*7330f729Sjoerg if (Context.getInlineVariableDefinitionKind(VD) == 2341*7330f729Sjoerg ASTContext::InlineVariableDefinitionKind::WeakUnknown) 2342*7330f729Sjoerg // A definition of an inline constexpr static data member may change 2343*7330f729Sjoerg // linkage later if it's redeclared outside the class. 2344*7330f729Sjoerg return false; 2345*7330f729Sjoerg // If OpenMP is enabled and threadprivates must be generated like TLS, delay 2346*7330f729Sjoerg // codegen for global variables, because they may be marked as threadprivate. 2347*7330f729Sjoerg if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 2348*7330f729Sjoerg getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) && 2349*7330f729Sjoerg !isTypeConstant(Global->getType(), false) && 2350*7330f729Sjoerg !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)) 2351*7330f729Sjoerg return false; 2352*7330f729Sjoerg 2353*7330f729Sjoerg return true; 2354*7330f729Sjoerg } 2355*7330f729Sjoerg 2356*7330f729Sjoerg ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor( 2357*7330f729Sjoerg const CXXUuidofExpr* E) { 2358*7330f729Sjoerg // Sema has verified that IIDSource has a __declspec(uuid()), and that its 2359*7330f729Sjoerg // well-formed. 2360*7330f729Sjoerg StringRef Uuid = E->getUuidStr(); 2361*7330f729Sjoerg std::string Name = "_GUID_" + Uuid.lower(); 2362*7330f729Sjoerg std::replace(Name.begin(), Name.end(), '-', '_'); 2363*7330f729Sjoerg 2364*7330f729Sjoerg // The UUID descriptor should be pointer aligned. 2365*7330f729Sjoerg CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 2366*7330f729Sjoerg 2367*7330f729Sjoerg // Look for an existing global. 2368*7330f729Sjoerg if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 2369*7330f729Sjoerg return ConstantAddress(GV, Alignment); 2370*7330f729Sjoerg 2371*7330f729Sjoerg llvm::Constant *Init = EmitUuidofInitializer(Uuid); 2372*7330f729Sjoerg assert(Init && "failed to initialize as constant"); 2373*7330f729Sjoerg 2374*7330f729Sjoerg auto *GV = new llvm::GlobalVariable( 2375*7330f729Sjoerg getModule(), Init->getType(), 2376*7330f729Sjoerg /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 2377*7330f729Sjoerg if (supportsCOMDAT()) 2378*7330f729Sjoerg GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 2379*7330f729Sjoerg setDSOLocal(GV); 2380*7330f729Sjoerg return ConstantAddress(GV, Alignment); 2381*7330f729Sjoerg } 2382*7330f729Sjoerg 2383*7330f729Sjoerg ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 2384*7330f729Sjoerg const AliasAttr *AA = VD->getAttr<AliasAttr>(); 2385*7330f729Sjoerg assert(AA && "No alias?"); 2386*7330f729Sjoerg 2387*7330f729Sjoerg CharUnits Alignment = getContext().getDeclAlign(VD); 2388*7330f729Sjoerg llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 2389*7330f729Sjoerg 2390*7330f729Sjoerg // See if there is already something with the target's name in the module. 2391*7330f729Sjoerg llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 2392*7330f729Sjoerg if (Entry) { 2393*7330f729Sjoerg unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 2394*7330f729Sjoerg auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 2395*7330f729Sjoerg return ConstantAddress(Ptr, Alignment); 2396*7330f729Sjoerg } 2397*7330f729Sjoerg 2398*7330f729Sjoerg llvm::Constant *Aliasee; 2399*7330f729Sjoerg if (isa<llvm::FunctionType>(DeclTy)) 2400*7330f729Sjoerg Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 2401*7330f729Sjoerg GlobalDecl(cast<FunctionDecl>(VD)), 2402*7330f729Sjoerg /*ForVTable=*/false); 2403*7330f729Sjoerg else 2404*7330f729Sjoerg Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 2405*7330f729Sjoerg llvm::PointerType::getUnqual(DeclTy), 2406*7330f729Sjoerg nullptr); 2407*7330f729Sjoerg 2408*7330f729Sjoerg auto *F = cast<llvm::GlobalValue>(Aliasee); 2409*7330f729Sjoerg F->setLinkage(llvm::Function::ExternalWeakLinkage); 2410*7330f729Sjoerg WeakRefReferences.insert(F); 2411*7330f729Sjoerg 2412*7330f729Sjoerg return ConstantAddress(Aliasee, Alignment); 2413*7330f729Sjoerg } 2414*7330f729Sjoerg 2415*7330f729Sjoerg void CodeGenModule::EmitGlobal(GlobalDecl GD) { 2416*7330f729Sjoerg const auto *Global = cast<ValueDecl>(GD.getDecl()); 2417*7330f729Sjoerg 2418*7330f729Sjoerg // Weak references don't produce any output by themselves. 2419*7330f729Sjoerg if (Global->hasAttr<WeakRefAttr>()) 2420*7330f729Sjoerg return; 2421*7330f729Sjoerg 2422*7330f729Sjoerg // If this is an alias definition (which otherwise looks like a declaration) 2423*7330f729Sjoerg // emit it now. 2424*7330f729Sjoerg if (Global->hasAttr<AliasAttr>()) 2425*7330f729Sjoerg return EmitAliasDefinition(GD); 2426*7330f729Sjoerg 2427*7330f729Sjoerg // IFunc like an alias whose value is resolved at runtime by calling resolver. 2428*7330f729Sjoerg if (Global->hasAttr<IFuncAttr>()) 2429*7330f729Sjoerg return emitIFuncDefinition(GD); 2430*7330f729Sjoerg 2431*7330f729Sjoerg // If this is a cpu_dispatch multiversion function, emit the resolver. 2432*7330f729Sjoerg if (Global->hasAttr<CPUDispatchAttr>()) 2433*7330f729Sjoerg return emitCPUDispatchDefinition(GD); 2434*7330f729Sjoerg 2435*7330f729Sjoerg // If this is CUDA, be selective about which declarations we emit. 2436*7330f729Sjoerg if (LangOpts.CUDA) { 2437*7330f729Sjoerg if (LangOpts.CUDAIsDevice) { 2438*7330f729Sjoerg if (!Global->hasAttr<CUDADeviceAttr>() && 2439*7330f729Sjoerg !Global->hasAttr<CUDAGlobalAttr>() && 2440*7330f729Sjoerg !Global->hasAttr<CUDAConstantAttr>() && 2441*7330f729Sjoerg !Global->hasAttr<CUDASharedAttr>() && 2442*7330f729Sjoerg !(LangOpts.HIP && Global->hasAttr<HIPPinnedShadowAttr>())) 2443*7330f729Sjoerg return; 2444*7330f729Sjoerg } else { 2445*7330f729Sjoerg // We need to emit host-side 'shadows' for all global 2446*7330f729Sjoerg // device-side variables because the CUDA runtime needs their 2447*7330f729Sjoerg // size and host-side address in order to provide access to 2448*7330f729Sjoerg // their device-side incarnations. 2449*7330f729Sjoerg 2450*7330f729Sjoerg // So device-only functions are the only things we skip. 2451*7330f729Sjoerg if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 2452*7330f729Sjoerg Global->hasAttr<CUDADeviceAttr>()) 2453*7330f729Sjoerg return; 2454*7330f729Sjoerg 2455*7330f729Sjoerg assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 2456*7330f729Sjoerg "Expected Variable or Function"); 2457*7330f729Sjoerg } 2458*7330f729Sjoerg } 2459*7330f729Sjoerg 2460*7330f729Sjoerg if (LangOpts.OpenMP) { 2461*7330f729Sjoerg // If this is OpenMP, check if it is legal to emit this global normally. 2462*7330f729Sjoerg if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 2463*7330f729Sjoerg return; 2464*7330f729Sjoerg if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 2465*7330f729Sjoerg if (MustBeEmitted(Global)) 2466*7330f729Sjoerg EmitOMPDeclareReduction(DRD); 2467*7330f729Sjoerg return; 2468*7330f729Sjoerg } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) { 2469*7330f729Sjoerg if (MustBeEmitted(Global)) 2470*7330f729Sjoerg EmitOMPDeclareMapper(DMD); 2471*7330f729Sjoerg return; 2472*7330f729Sjoerg } 2473*7330f729Sjoerg } 2474*7330f729Sjoerg 2475*7330f729Sjoerg // Ignore declarations, they will be emitted on their first use. 2476*7330f729Sjoerg if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 2477*7330f729Sjoerg // Forward declarations are emitted lazily on first use. 2478*7330f729Sjoerg if (!FD->doesThisDeclarationHaveABody()) { 2479*7330f729Sjoerg if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 2480*7330f729Sjoerg return; 2481*7330f729Sjoerg 2482*7330f729Sjoerg StringRef MangledName = getMangledName(GD); 2483*7330f729Sjoerg 2484*7330f729Sjoerg // Compute the function info and LLVM type. 2485*7330f729Sjoerg const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2486*7330f729Sjoerg llvm::Type *Ty = getTypes().GetFunctionType(FI); 2487*7330f729Sjoerg 2488*7330f729Sjoerg GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 2489*7330f729Sjoerg /*DontDefer=*/false); 2490*7330f729Sjoerg return; 2491*7330f729Sjoerg } 2492*7330f729Sjoerg } else { 2493*7330f729Sjoerg const auto *VD = cast<VarDecl>(Global); 2494*7330f729Sjoerg assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 2495*7330f729Sjoerg if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 2496*7330f729Sjoerg !Context.isMSStaticDataMemberInlineDefinition(VD)) { 2497*7330f729Sjoerg if (LangOpts.OpenMP) { 2498*7330f729Sjoerg // Emit declaration of the must-be-emitted declare target variable. 2499*7330f729Sjoerg if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 2500*7330f729Sjoerg OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 2501*7330f729Sjoerg bool UnifiedMemoryEnabled = 2502*7330f729Sjoerg getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); 2503*7330f729Sjoerg if (*Res == OMPDeclareTargetDeclAttr::MT_To && 2504*7330f729Sjoerg !UnifiedMemoryEnabled) { 2505*7330f729Sjoerg (void)GetAddrOfGlobalVar(VD); 2506*7330f729Sjoerg } else { 2507*7330f729Sjoerg assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || 2508*7330f729Sjoerg (*Res == OMPDeclareTargetDeclAttr::MT_To && 2509*7330f729Sjoerg UnifiedMemoryEnabled)) && 2510*7330f729Sjoerg "Link clause or to clause with unified memory expected."); 2511*7330f729Sjoerg (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); 2512*7330f729Sjoerg } 2513*7330f729Sjoerg 2514*7330f729Sjoerg return; 2515*7330f729Sjoerg } 2516*7330f729Sjoerg } 2517*7330f729Sjoerg // If this declaration may have caused an inline variable definition to 2518*7330f729Sjoerg // change linkage, make sure that it's emitted. 2519*7330f729Sjoerg if (Context.getInlineVariableDefinitionKind(VD) == 2520*7330f729Sjoerg ASTContext::InlineVariableDefinitionKind::Strong) 2521*7330f729Sjoerg GetAddrOfGlobalVar(VD); 2522*7330f729Sjoerg return; 2523*7330f729Sjoerg } 2524*7330f729Sjoerg } 2525*7330f729Sjoerg 2526*7330f729Sjoerg // Defer code generation to first use when possible, e.g. if this is an inline 2527*7330f729Sjoerg // function. If the global must always be emitted, do it eagerly if possible 2528*7330f729Sjoerg // to benefit from cache locality. 2529*7330f729Sjoerg if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 2530*7330f729Sjoerg // Emit the definition if it can't be deferred. 2531*7330f729Sjoerg EmitGlobalDefinition(GD); 2532*7330f729Sjoerg return; 2533*7330f729Sjoerg } 2534*7330f729Sjoerg 2535*7330f729Sjoerg // Check if this must be emitted as declare variant. 2536*7330f729Sjoerg if (LangOpts.OpenMP && isa<FunctionDecl>(Global) && OpenMPRuntime && 2537*7330f729Sjoerg OpenMPRuntime->emitDeclareVariant(GD, /*IsForDefinition=*/false)) 2538*7330f729Sjoerg return; 2539*7330f729Sjoerg 2540*7330f729Sjoerg // If we're deferring emission of a C++ variable with an 2541*7330f729Sjoerg // initializer, remember the order in which it appeared in the file. 2542*7330f729Sjoerg if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 2543*7330f729Sjoerg cast<VarDecl>(Global)->hasInit()) { 2544*7330f729Sjoerg DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 2545*7330f729Sjoerg CXXGlobalInits.push_back(nullptr); 2546*7330f729Sjoerg } 2547*7330f729Sjoerg 2548*7330f729Sjoerg StringRef MangledName = getMangledName(GD); 2549*7330f729Sjoerg if (GetGlobalValue(MangledName) != nullptr) { 2550*7330f729Sjoerg // The value has already been used and should therefore be emitted. 2551*7330f729Sjoerg addDeferredDeclToEmit(GD); 2552*7330f729Sjoerg } else if (MustBeEmitted(Global)) { 2553*7330f729Sjoerg // The value must be emitted, but cannot be emitted eagerly. 2554*7330f729Sjoerg assert(!MayBeEmittedEagerly(Global)); 2555*7330f729Sjoerg addDeferredDeclToEmit(GD); 2556*7330f729Sjoerg } else { 2557*7330f729Sjoerg // Otherwise, remember that we saw a deferred decl with this name. The 2558*7330f729Sjoerg // first use of the mangled name will cause it to move into 2559*7330f729Sjoerg // DeferredDeclsToEmit. 2560*7330f729Sjoerg DeferredDecls[MangledName] = GD; 2561*7330f729Sjoerg } 2562*7330f729Sjoerg } 2563*7330f729Sjoerg 2564*7330f729Sjoerg // Check if T is a class type with a destructor that's not dllimport. 2565*7330f729Sjoerg static bool HasNonDllImportDtor(QualType T) { 2566*7330f729Sjoerg if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 2567*7330f729Sjoerg if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2568*7330f729Sjoerg if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 2569*7330f729Sjoerg return true; 2570*7330f729Sjoerg 2571*7330f729Sjoerg return false; 2572*7330f729Sjoerg } 2573*7330f729Sjoerg 2574*7330f729Sjoerg namespace { 2575*7330f729Sjoerg struct FunctionIsDirectlyRecursive 2576*7330f729Sjoerg : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> { 2577*7330f729Sjoerg const StringRef Name; 2578*7330f729Sjoerg const Builtin::Context &BI; 2579*7330f729Sjoerg FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) 2580*7330f729Sjoerg : Name(N), BI(C) {} 2581*7330f729Sjoerg 2582*7330f729Sjoerg bool VisitCallExpr(const CallExpr *E) { 2583*7330f729Sjoerg const FunctionDecl *FD = E->getDirectCallee(); 2584*7330f729Sjoerg if (!FD) 2585*7330f729Sjoerg return false; 2586*7330f729Sjoerg AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 2587*7330f729Sjoerg if (Attr && Name == Attr->getLabel()) 2588*7330f729Sjoerg return true; 2589*7330f729Sjoerg unsigned BuiltinID = FD->getBuiltinID(); 2590*7330f729Sjoerg if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 2591*7330f729Sjoerg return false; 2592*7330f729Sjoerg StringRef BuiltinName = BI.getName(BuiltinID); 2593*7330f729Sjoerg if (BuiltinName.startswith("__builtin_") && 2594*7330f729Sjoerg Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 2595*7330f729Sjoerg return true; 2596*7330f729Sjoerg } 2597*7330f729Sjoerg return false; 2598*7330f729Sjoerg } 2599*7330f729Sjoerg 2600*7330f729Sjoerg bool VisitStmt(const Stmt *S) { 2601*7330f729Sjoerg for (const Stmt *Child : S->children()) 2602*7330f729Sjoerg if (Child && this->Visit(Child)) 2603*7330f729Sjoerg return true; 2604*7330f729Sjoerg return false; 2605*7330f729Sjoerg } 2606*7330f729Sjoerg }; 2607*7330f729Sjoerg 2608*7330f729Sjoerg // Make sure we're not referencing non-imported vars or functions. 2609*7330f729Sjoerg struct DLLImportFunctionVisitor 2610*7330f729Sjoerg : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 2611*7330f729Sjoerg bool SafeToInline = true; 2612*7330f729Sjoerg 2613*7330f729Sjoerg bool shouldVisitImplicitCode() const { return true; } 2614*7330f729Sjoerg 2615*7330f729Sjoerg bool VisitVarDecl(VarDecl *VD) { 2616*7330f729Sjoerg if (VD->getTLSKind()) { 2617*7330f729Sjoerg // A thread-local variable cannot be imported. 2618*7330f729Sjoerg SafeToInline = false; 2619*7330f729Sjoerg return SafeToInline; 2620*7330f729Sjoerg } 2621*7330f729Sjoerg 2622*7330f729Sjoerg // A variable definition might imply a destructor call. 2623*7330f729Sjoerg if (VD->isThisDeclarationADefinition()) 2624*7330f729Sjoerg SafeToInline = !HasNonDllImportDtor(VD->getType()); 2625*7330f729Sjoerg 2626*7330f729Sjoerg return SafeToInline; 2627*7330f729Sjoerg } 2628*7330f729Sjoerg 2629*7330f729Sjoerg bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 2630*7330f729Sjoerg if (const auto *D = E->getTemporary()->getDestructor()) 2631*7330f729Sjoerg SafeToInline = D->hasAttr<DLLImportAttr>(); 2632*7330f729Sjoerg return SafeToInline; 2633*7330f729Sjoerg } 2634*7330f729Sjoerg 2635*7330f729Sjoerg bool VisitDeclRefExpr(DeclRefExpr *E) { 2636*7330f729Sjoerg ValueDecl *VD = E->getDecl(); 2637*7330f729Sjoerg if (isa<FunctionDecl>(VD)) 2638*7330f729Sjoerg SafeToInline = VD->hasAttr<DLLImportAttr>(); 2639*7330f729Sjoerg else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 2640*7330f729Sjoerg SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 2641*7330f729Sjoerg return SafeToInline; 2642*7330f729Sjoerg } 2643*7330f729Sjoerg 2644*7330f729Sjoerg bool VisitCXXConstructExpr(CXXConstructExpr *E) { 2645*7330f729Sjoerg SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 2646*7330f729Sjoerg return SafeToInline; 2647*7330f729Sjoerg } 2648*7330f729Sjoerg 2649*7330f729Sjoerg bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2650*7330f729Sjoerg CXXMethodDecl *M = E->getMethodDecl(); 2651*7330f729Sjoerg if (!M) { 2652*7330f729Sjoerg // Call through a pointer to member function. This is safe to inline. 2653*7330f729Sjoerg SafeToInline = true; 2654*7330f729Sjoerg } else { 2655*7330f729Sjoerg SafeToInline = M->hasAttr<DLLImportAttr>(); 2656*7330f729Sjoerg } 2657*7330f729Sjoerg return SafeToInline; 2658*7330f729Sjoerg } 2659*7330f729Sjoerg 2660*7330f729Sjoerg bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 2661*7330f729Sjoerg SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 2662*7330f729Sjoerg return SafeToInline; 2663*7330f729Sjoerg } 2664*7330f729Sjoerg 2665*7330f729Sjoerg bool VisitCXXNewExpr(CXXNewExpr *E) { 2666*7330f729Sjoerg SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 2667*7330f729Sjoerg return SafeToInline; 2668*7330f729Sjoerg } 2669*7330f729Sjoerg }; 2670*7330f729Sjoerg } 2671*7330f729Sjoerg 2672*7330f729Sjoerg // isTriviallyRecursive - Check if this function calls another 2673*7330f729Sjoerg // decl that, because of the asm attribute or the other decl being a builtin, 2674*7330f729Sjoerg // ends up pointing to itself. 2675*7330f729Sjoerg bool 2676*7330f729Sjoerg CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 2677*7330f729Sjoerg StringRef Name; 2678*7330f729Sjoerg if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 2679*7330f729Sjoerg // asm labels are a special kind of mangling we have to support. 2680*7330f729Sjoerg AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 2681*7330f729Sjoerg if (!Attr) 2682*7330f729Sjoerg return false; 2683*7330f729Sjoerg Name = Attr->getLabel(); 2684*7330f729Sjoerg } else { 2685*7330f729Sjoerg Name = FD->getName(); 2686*7330f729Sjoerg } 2687*7330f729Sjoerg 2688*7330f729Sjoerg FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 2689*7330f729Sjoerg const Stmt *Body = FD->getBody(); 2690*7330f729Sjoerg return Body ? Walker.Visit(Body) : false; 2691*7330f729Sjoerg } 2692*7330f729Sjoerg 2693*7330f729Sjoerg bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 2694*7330f729Sjoerg if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 2695*7330f729Sjoerg return true; 2696*7330f729Sjoerg const auto *F = cast<FunctionDecl>(GD.getDecl()); 2697*7330f729Sjoerg if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 2698*7330f729Sjoerg return false; 2699*7330f729Sjoerg 2700*7330f729Sjoerg if (F->hasAttr<DLLImportAttr>()) { 2701*7330f729Sjoerg // Check whether it would be safe to inline this dllimport function. 2702*7330f729Sjoerg DLLImportFunctionVisitor Visitor; 2703*7330f729Sjoerg Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 2704*7330f729Sjoerg if (!Visitor.SafeToInline) 2705*7330f729Sjoerg return false; 2706*7330f729Sjoerg 2707*7330f729Sjoerg if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 2708*7330f729Sjoerg // Implicit destructor invocations aren't captured in the AST, so the 2709*7330f729Sjoerg // check above can't see them. Check for them manually here. 2710*7330f729Sjoerg for (const Decl *Member : Dtor->getParent()->decls()) 2711*7330f729Sjoerg if (isa<FieldDecl>(Member)) 2712*7330f729Sjoerg if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 2713*7330f729Sjoerg return false; 2714*7330f729Sjoerg for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 2715*7330f729Sjoerg if (HasNonDllImportDtor(B.getType())) 2716*7330f729Sjoerg return false; 2717*7330f729Sjoerg } 2718*7330f729Sjoerg } 2719*7330f729Sjoerg 2720*7330f729Sjoerg // PR9614. Avoid cases where the source code is lying to us. An available 2721*7330f729Sjoerg // externally function should have an equivalent function somewhere else, 2722*7330f729Sjoerg // but a function that calls itself is clearly not equivalent to the real 2723*7330f729Sjoerg // implementation. 2724*7330f729Sjoerg // This happens in glibc's btowc and in some configure checks. 2725*7330f729Sjoerg return !isTriviallyRecursive(F); 2726*7330f729Sjoerg } 2727*7330f729Sjoerg 2728*7330f729Sjoerg bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 2729*7330f729Sjoerg return CodeGenOpts.OptimizationLevel > 0; 2730*7330f729Sjoerg } 2731*7330f729Sjoerg 2732*7330f729Sjoerg void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, 2733*7330f729Sjoerg llvm::GlobalValue *GV) { 2734*7330f729Sjoerg const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2735*7330f729Sjoerg 2736*7330f729Sjoerg if (FD->isCPUSpecificMultiVersion()) { 2737*7330f729Sjoerg auto *Spec = FD->getAttr<CPUSpecificAttr>(); 2738*7330f729Sjoerg for (unsigned I = 0; I < Spec->cpus_size(); ++I) 2739*7330f729Sjoerg EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 2740*7330f729Sjoerg // Requires multiple emits. 2741*7330f729Sjoerg } else 2742*7330f729Sjoerg EmitGlobalFunctionDefinition(GD, GV); 2743*7330f729Sjoerg } 2744*7330f729Sjoerg 2745*7330f729Sjoerg void CodeGenModule::emitOpenMPDeviceFunctionRedefinition( 2746*7330f729Sjoerg GlobalDecl OldGD, GlobalDecl NewGD, llvm::GlobalValue *GV) { 2747*7330f729Sjoerg assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 2748*7330f729Sjoerg OpenMPRuntime && "Expected OpenMP device mode."); 2749*7330f729Sjoerg const auto *D = cast<FunctionDecl>(OldGD.getDecl()); 2750*7330f729Sjoerg 2751*7330f729Sjoerg // Compute the function info and LLVM type. 2752*7330f729Sjoerg const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(OldGD); 2753*7330f729Sjoerg llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2754*7330f729Sjoerg 2755*7330f729Sjoerg // Get or create the prototype for the function. 2756*7330f729Sjoerg if (!GV || (GV->getType()->getElementType() != Ty)) { 2757*7330f729Sjoerg GV = cast<llvm::GlobalValue>(GetOrCreateLLVMFunction( 2758*7330f729Sjoerg getMangledName(OldGD), Ty, GlobalDecl(), /*ForVTable=*/false, 2759*7330f729Sjoerg /*DontDefer=*/true, /*IsThunk=*/false, llvm::AttributeList(), 2760*7330f729Sjoerg ForDefinition)); 2761*7330f729Sjoerg SetFunctionAttributes(OldGD, cast<llvm::Function>(GV), 2762*7330f729Sjoerg /*IsIncompleteFunction=*/false, 2763*7330f729Sjoerg /*IsThunk=*/false); 2764*7330f729Sjoerg } 2765*7330f729Sjoerg // We need to set linkage and visibility on the function before 2766*7330f729Sjoerg // generating code for it because various parts of IR generation 2767*7330f729Sjoerg // want to propagate this information down (e.g. to local static 2768*7330f729Sjoerg // declarations). 2769*7330f729Sjoerg auto *Fn = cast<llvm::Function>(GV); 2770*7330f729Sjoerg setFunctionLinkage(OldGD, Fn); 2771*7330f729Sjoerg 2772*7330f729Sjoerg // FIXME: this is redundant with part of 2773*7330f729Sjoerg // setFunctionDefinitionAttributes 2774*7330f729Sjoerg setGVProperties(Fn, OldGD); 2775*7330f729Sjoerg 2776*7330f729Sjoerg MaybeHandleStaticInExternC(D, Fn); 2777*7330f729Sjoerg 2778*7330f729Sjoerg maybeSetTrivialComdat(*D, *Fn); 2779*7330f729Sjoerg 2780*7330f729Sjoerg CodeGenFunction(*this).GenerateCode(NewGD, Fn, FI); 2781*7330f729Sjoerg 2782*7330f729Sjoerg setNonAliasAttributes(OldGD, Fn); 2783*7330f729Sjoerg SetLLVMFunctionAttributesForDefinition(D, Fn); 2784*7330f729Sjoerg 2785*7330f729Sjoerg if (D->hasAttr<AnnotateAttr>()) 2786*7330f729Sjoerg AddGlobalAnnotations(D, Fn); 2787*7330f729Sjoerg } 2788*7330f729Sjoerg 2789*7330f729Sjoerg void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 2790*7330f729Sjoerg const auto *D = cast<ValueDecl>(GD.getDecl()); 2791*7330f729Sjoerg 2792*7330f729Sjoerg PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 2793*7330f729Sjoerg Context.getSourceManager(), 2794*7330f729Sjoerg "Generating code for declaration"); 2795*7330f729Sjoerg 2796*7330f729Sjoerg if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 2797*7330f729Sjoerg // At -O0, don't generate IR for functions with available_externally 2798*7330f729Sjoerg // linkage. 2799*7330f729Sjoerg if (!shouldEmitFunction(GD)) 2800*7330f729Sjoerg return; 2801*7330f729Sjoerg 2802*7330f729Sjoerg llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() { 2803*7330f729Sjoerg std::string Name; 2804*7330f729Sjoerg llvm::raw_string_ostream OS(Name); 2805*7330f729Sjoerg FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(), 2806*7330f729Sjoerg /*Qualified=*/true); 2807*7330f729Sjoerg return Name; 2808*7330f729Sjoerg }); 2809*7330f729Sjoerg 2810*7330f729Sjoerg if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 2811*7330f729Sjoerg // Make sure to emit the definition(s) before we emit the thunks. 2812*7330f729Sjoerg // This is necessary for the generation of certain thunks. 2813*7330f729Sjoerg if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method)) 2814*7330f729Sjoerg ABI->emitCXXStructor(GD); 2815*7330f729Sjoerg else if (FD->isMultiVersion()) 2816*7330f729Sjoerg EmitMultiVersionFunctionDefinition(GD, GV); 2817*7330f729Sjoerg else 2818*7330f729Sjoerg EmitGlobalFunctionDefinition(GD, GV); 2819*7330f729Sjoerg 2820*7330f729Sjoerg if (Method->isVirtual()) 2821*7330f729Sjoerg getVTables().EmitThunks(GD); 2822*7330f729Sjoerg 2823*7330f729Sjoerg return; 2824*7330f729Sjoerg } 2825*7330f729Sjoerg 2826*7330f729Sjoerg if (FD->isMultiVersion()) 2827*7330f729Sjoerg return EmitMultiVersionFunctionDefinition(GD, GV); 2828*7330f729Sjoerg return EmitGlobalFunctionDefinition(GD, GV); 2829*7330f729Sjoerg } 2830*7330f729Sjoerg 2831*7330f729Sjoerg if (const auto *VD = dyn_cast<VarDecl>(D)) 2832*7330f729Sjoerg return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 2833*7330f729Sjoerg 2834*7330f729Sjoerg llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 2835*7330f729Sjoerg } 2836*7330f729Sjoerg 2837*7330f729Sjoerg static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2838*7330f729Sjoerg llvm::Function *NewFn); 2839*7330f729Sjoerg 2840*7330f729Sjoerg static unsigned 2841*7330f729Sjoerg TargetMVPriority(const TargetInfo &TI, 2842*7330f729Sjoerg const CodeGenFunction::MultiVersionResolverOption &RO) { 2843*7330f729Sjoerg unsigned Priority = 0; 2844*7330f729Sjoerg for (StringRef Feat : RO.Conditions.Features) 2845*7330f729Sjoerg Priority = std::max(Priority, TI.multiVersionSortPriority(Feat)); 2846*7330f729Sjoerg 2847*7330f729Sjoerg if (!RO.Conditions.Architecture.empty()) 2848*7330f729Sjoerg Priority = std::max( 2849*7330f729Sjoerg Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture)); 2850*7330f729Sjoerg return Priority; 2851*7330f729Sjoerg } 2852*7330f729Sjoerg 2853*7330f729Sjoerg void CodeGenModule::emitMultiVersionFunctions() { 2854*7330f729Sjoerg for (GlobalDecl GD : MultiVersionFuncs) { 2855*7330f729Sjoerg SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 2856*7330f729Sjoerg const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 2857*7330f729Sjoerg getContext().forEachMultiversionedFunctionVersion( 2858*7330f729Sjoerg FD, [this, &GD, &Options](const FunctionDecl *CurFD) { 2859*7330f729Sjoerg GlobalDecl CurGD{ 2860*7330f729Sjoerg (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; 2861*7330f729Sjoerg StringRef MangledName = getMangledName(CurGD); 2862*7330f729Sjoerg llvm::Constant *Func = GetGlobalValue(MangledName); 2863*7330f729Sjoerg if (!Func) { 2864*7330f729Sjoerg if (CurFD->isDefined()) { 2865*7330f729Sjoerg EmitGlobalFunctionDefinition(CurGD, nullptr); 2866*7330f729Sjoerg Func = GetGlobalValue(MangledName); 2867*7330f729Sjoerg } else { 2868*7330f729Sjoerg const CGFunctionInfo &FI = 2869*7330f729Sjoerg getTypes().arrangeGlobalDeclaration(GD); 2870*7330f729Sjoerg llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 2871*7330f729Sjoerg Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 2872*7330f729Sjoerg /*DontDefer=*/false, ForDefinition); 2873*7330f729Sjoerg } 2874*7330f729Sjoerg assert(Func && "This should have just been created"); 2875*7330f729Sjoerg } 2876*7330f729Sjoerg 2877*7330f729Sjoerg const auto *TA = CurFD->getAttr<TargetAttr>(); 2878*7330f729Sjoerg llvm::SmallVector<StringRef, 8> Feats; 2879*7330f729Sjoerg TA->getAddedFeatures(Feats); 2880*7330f729Sjoerg 2881*7330f729Sjoerg Options.emplace_back(cast<llvm::Function>(Func), 2882*7330f729Sjoerg TA->getArchitecture(), Feats); 2883*7330f729Sjoerg }); 2884*7330f729Sjoerg 2885*7330f729Sjoerg llvm::Function *ResolverFunc; 2886*7330f729Sjoerg const TargetInfo &TI = getTarget(); 2887*7330f729Sjoerg 2888*7330f729Sjoerg if (TI.supportsIFunc() || FD->isTargetMultiVersion()) { 2889*7330f729Sjoerg ResolverFunc = cast<llvm::Function>( 2890*7330f729Sjoerg GetGlobalValue((getMangledName(GD) + ".resolver").str())); 2891*7330f729Sjoerg ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage); 2892*7330f729Sjoerg } else { 2893*7330f729Sjoerg ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD))); 2894*7330f729Sjoerg } 2895*7330f729Sjoerg 2896*7330f729Sjoerg if (supportsCOMDAT()) 2897*7330f729Sjoerg ResolverFunc->setComdat( 2898*7330f729Sjoerg getModule().getOrInsertComdat(ResolverFunc->getName())); 2899*7330f729Sjoerg 2900*7330f729Sjoerg llvm::stable_sort( 2901*7330f729Sjoerg Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 2902*7330f729Sjoerg const CodeGenFunction::MultiVersionResolverOption &RHS) { 2903*7330f729Sjoerg return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 2904*7330f729Sjoerg }); 2905*7330f729Sjoerg CodeGenFunction CGF(*this); 2906*7330f729Sjoerg CGF.EmitMultiVersionResolver(ResolverFunc, Options); 2907*7330f729Sjoerg } 2908*7330f729Sjoerg } 2909*7330f729Sjoerg 2910*7330f729Sjoerg void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { 2911*7330f729Sjoerg const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2912*7330f729Sjoerg assert(FD && "Not a FunctionDecl?"); 2913*7330f729Sjoerg const auto *DD = FD->getAttr<CPUDispatchAttr>(); 2914*7330f729Sjoerg assert(DD && "Not a cpu_dispatch Function?"); 2915*7330f729Sjoerg llvm::Type *DeclTy = getTypes().ConvertType(FD->getType()); 2916*7330f729Sjoerg 2917*7330f729Sjoerg if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 2918*7330f729Sjoerg const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD); 2919*7330f729Sjoerg DeclTy = getTypes().GetFunctionType(FInfo); 2920*7330f729Sjoerg } 2921*7330f729Sjoerg 2922*7330f729Sjoerg StringRef ResolverName = getMangledName(GD); 2923*7330f729Sjoerg 2924*7330f729Sjoerg llvm::Type *ResolverType; 2925*7330f729Sjoerg GlobalDecl ResolverGD; 2926*7330f729Sjoerg if (getTarget().supportsIFunc()) 2927*7330f729Sjoerg ResolverType = llvm::FunctionType::get( 2928*7330f729Sjoerg llvm::PointerType::get(DeclTy, 2929*7330f729Sjoerg Context.getTargetAddressSpace(FD->getType())), 2930*7330f729Sjoerg false); 2931*7330f729Sjoerg else { 2932*7330f729Sjoerg ResolverType = DeclTy; 2933*7330f729Sjoerg ResolverGD = GD; 2934*7330f729Sjoerg } 2935*7330f729Sjoerg 2936*7330f729Sjoerg auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction( 2937*7330f729Sjoerg ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false)); 2938*7330f729Sjoerg ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage); 2939*7330f729Sjoerg if (supportsCOMDAT()) 2940*7330f729Sjoerg ResolverFunc->setComdat( 2941*7330f729Sjoerg getModule().getOrInsertComdat(ResolverFunc->getName())); 2942*7330f729Sjoerg 2943*7330f729Sjoerg SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 2944*7330f729Sjoerg const TargetInfo &Target = getTarget(); 2945*7330f729Sjoerg unsigned Index = 0; 2946*7330f729Sjoerg for (const IdentifierInfo *II : DD->cpus()) { 2947*7330f729Sjoerg // Get the name of the target function so we can look it up/create it. 2948*7330f729Sjoerg std::string MangledName = getMangledNameImpl(*this, GD, FD, true) + 2949*7330f729Sjoerg getCPUSpecificMangling(*this, II->getName()); 2950*7330f729Sjoerg 2951*7330f729Sjoerg llvm::Constant *Func = GetGlobalValue(MangledName); 2952*7330f729Sjoerg 2953*7330f729Sjoerg if (!Func) { 2954*7330f729Sjoerg GlobalDecl ExistingDecl = Manglings.lookup(MangledName); 2955*7330f729Sjoerg if (ExistingDecl.getDecl() && 2956*7330f729Sjoerg ExistingDecl.getDecl()->getAsFunction()->isDefined()) { 2957*7330f729Sjoerg EmitGlobalFunctionDefinition(ExistingDecl, nullptr); 2958*7330f729Sjoerg Func = GetGlobalValue(MangledName); 2959*7330f729Sjoerg } else { 2960*7330f729Sjoerg if (!ExistingDecl.getDecl()) 2961*7330f729Sjoerg ExistingDecl = GD.getWithMultiVersionIndex(Index); 2962*7330f729Sjoerg 2963*7330f729Sjoerg Func = GetOrCreateLLVMFunction( 2964*7330f729Sjoerg MangledName, DeclTy, ExistingDecl, 2965*7330f729Sjoerg /*ForVTable=*/false, /*DontDefer=*/true, 2966*7330f729Sjoerg /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 2967*7330f729Sjoerg } 2968*7330f729Sjoerg } 2969*7330f729Sjoerg 2970*7330f729Sjoerg llvm::SmallVector<StringRef, 32> Features; 2971*7330f729Sjoerg Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features); 2972*7330f729Sjoerg llvm::transform(Features, Features.begin(), 2973*7330f729Sjoerg [](StringRef Str) { return Str.substr(1); }); 2974*7330f729Sjoerg Features.erase(std::remove_if( 2975*7330f729Sjoerg Features.begin(), Features.end(), [&Target](StringRef Feat) { 2976*7330f729Sjoerg return !Target.validateCpuSupports(Feat); 2977*7330f729Sjoerg }), Features.end()); 2978*7330f729Sjoerg Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features); 2979*7330f729Sjoerg ++Index; 2980*7330f729Sjoerg } 2981*7330f729Sjoerg 2982*7330f729Sjoerg llvm::sort( 2983*7330f729Sjoerg Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS, 2984*7330f729Sjoerg const CodeGenFunction::MultiVersionResolverOption &RHS) { 2985*7330f729Sjoerg return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) > 2986*7330f729Sjoerg CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features); 2987*7330f729Sjoerg }); 2988*7330f729Sjoerg 2989*7330f729Sjoerg // If the list contains multiple 'default' versions, such as when it contains 2990*7330f729Sjoerg // 'pentium' and 'generic', don't emit the call to the generic one (since we 2991*7330f729Sjoerg // always run on at least a 'pentium'). We do this by deleting the 'least 2992*7330f729Sjoerg // advanced' (read, lowest mangling letter). 2993*7330f729Sjoerg while (Options.size() > 1 && 2994*7330f729Sjoerg CodeGenFunction::GetX86CpuSupportsMask( 2995*7330f729Sjoerg (Options.end() - 2)->Conditions.Features) == 0) { 2996*7330f729Sjoerg StringRef LHSName = (Options.end() - 2)->Function->getName(); 2997*7330f729Sjoerg StringRef RHSName = (Options.end() - 1)->Function->getName(); 2998*7330f729Sjoerg if (LHSName.compare(RHSName) < 0) 2999*7330f729Sjoerg Options.erase(Options.end() - 2); 3000*7330f729Sjoerg else 3001*7330f729Sjoerg Options.erase(Options.end() - 1); 3002*7330f729Sjoerg } 3003*7330f729Sjoerg 3004*7330f729Sjoerg CodeGenFunction CGF(*this); 3005*7330f729Sjoerg CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3006*7330f729Sjoerg 3007*7330f729Sjoerg if (getTarget().supportsIFunc()) { 3008*7330f729Sjoerg std::string AliasName = getMangledNameImpl( 3009*7330f729Sjoerg *this, GD, FD, /*OmitMultiVersionMangling=*/true); 3010*7330f729Sjoerg llvm::Constant *AliasFunc = GetGlobalValue(AliasName); 3011*7330f729Sjoerg if (!AliasFunc) { 3012*7330f729Sjoerg auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction( 3013*7330f729Sjoerg AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true, 3014*7330f729Sjoerg /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition)); 3015*7330f729Sjoerg auto *GA = llvm::GlobalAlias::create( 3016*7330f729Sjoerg DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule()); 3017*7330f729Sjoerg GA->setLinkage(llvm::Function::WeakODRLinkage); 3018*7330f729Sjoerg SetCommonAttributes(GD, GA); 3019*7330f729Sjoerg } 3020*7330f729Sjoerg } 3021*7330f729Sjoerg } 3022*7330f729Sjoerg 3023*7330f729Sjoerg /// If a dispatcher for the specified mangled name is not in the module, create 3024*7330f729Sjoerg /// and return an llvm Function with the specified type. 3025*7330f729Sjoerg llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver( 3026*7330f729Sjoerg GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) { 3027*7330f729Sjoerg std::string MangledName = 3028*7330f729Sjoerg getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 3029*7330f729Sjoerg 3030*7330f729Sjoerg // Holds the name of the resolver, in ifunc mode this is the ifunc (which has 3031*7330f729Sjoerg // a separate resolver). 3032*7330f729Sjoerg std::string ResolverName = MangledName; 3033*7330f729Sjoerg if (getTarget().supportsIFunc()) 3034*7330f729Sjoerg ResolverName += ".ifunc"; 3035*7330f729Sjoerg else if (FD->isTargetMultiVersion()) 3036*7330f729Sjoerg ResolverName += ".resolver"; 3037*7330f729Sjoerg 3038*7330f729Sjoerg // If this already exists, just return that one. 3039*7330f729Sjoerg if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName)) 3040*7330f729Sjoerg return ResolverGV; 3041*7330f729Sjoerg 3042*7330f729Sjoerg // Since this is the first time we've created this IFunc, make sure 3043*7330f729Sjoerg // that we put this multiversioned function into the list to be 3044*7330f729Sjoerg // replaced later if necessary (target multiversioning only). 3045*7330f729Sjoerg if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion()) 3046*7330f729Sjoerg MultiVersionFuncs.push_back(GD); 3047*7330f729Sjoerg 3048*7330f729Sjoerg if (getTarget().supportsIFunc()) { 3049*7330f729Sjoerg llvm::Type *ResolverType = llvm::FunctionType::get( 3050*7330f729Sjoerg llvm::PointerType::get( 3051*7330f729Sjoerg DeclTy, getContext().getTargetAddressSpace(FD->getType())), 3052*7330f729Sjoerg false); 3053*7330f729Sjoerg llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3054*7330f729Sjoerg MangledName + ".resolver", ResolverType, GlobalDecl{}, 3055*7330f729Sjoerg /*ForVTable=*/false); 3056*7330f729Sjoerg llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create( 3057*7330f729Sjoerg DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule()); 3058*7330f729Sjoerg GIF->setName(ResolverName); 3059*7330f729Sjoerg SetCommonAttributes(FD, GIF); 3060*7330f729Sjoerg 3061*7330f729Sjoerg return GIF; 3062*7330f729Sjoerg } 3063*7330f729Sjoerg 3064*7330f729Sjoerg llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3065*7330f729Sjoerg ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false); 3066*7330f729Sjoerg assert(isa<llvm::GlobalValue>(Resolver) && 3067*7330f729Sjoerg "Resolver should be created for the first time"); 3068*7330f729Sjoerg SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver)); 3069*7330f729Sjoerg return Resolver; 3070*7330f729Sjoerg } 3071*7330f729Sjoerg 3072*7330f729Sjoerg /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 3073*7330f729Sjoerg /// module, create and return an llvm Function with the specified type. If there 3074*7330f729Sjoerg /// is something in the module with the specified name, return it potentially 3075*7330f729Sjoerg /// bitcasted to the right type. 3076*7330f729Sjoerg /// 3077*7330f729Sjoerg /// If D is non-null, it specifies a decl that correspond to this. This is used 3078*7330f729Sjoerg /// to set the attributes on the function when it is first created. 3079*7330f729Sjoerg llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 3080*7330f729Sjoerg StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 3081*7330f729Sjoerg bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 3082*7330f729Sjoerg ForDefinition_t IsForDefinition) { 3083*7330f729Sjoerg const Decl *D = GD.getDecl(); 3084*7330f729Sjoerg 3085*7330f729Sjoerg // Any attempts to use a MultiVersion function should result in retrieving 3086*7330f729Sjoerg // the iFunc instead. Name Mangling will handle the rest of the changes. 3087*7330f729Sjoerg if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) { 3088*7330f729Sjoerg // For the device mark the function as one that should be emitted. 3089*7330f729Sjoerg if (getLangOpts().OpenMPIsDevice && OpenMPRuntime && 3090*7330f729Sjoerg !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && 3091*7330f729Sjoerg !DontDefer && !IsForDefinition) { 3092*7330f729Sjoerg if (const FunctionDecl *FDDef = FD->getDefinition()) { 3093*7330f729Sjoerg GlobalDecl GDDef; 3094*7330f729Sjoerg if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef)) 3095*7330f729Sjoerg GDDef = GlobalDecl(CD, GD.getCtorType()); 3096*7330f729Sjoerg else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef)) 3097*7330f729Sjoerg GDDef = GlobalDecl(DD, GD.getDtorType()); 3098*7330f729Sjoerg else 3099*7330f729Sjoerg GDDef = GlobalDecl(FDDef); 3100*7330f729Sjoerg EmitGlobal(GDDef); 3101*7330f729Sjoerg } 3102*7330f729Sjoerg } 3103*7330f729Sjoerg // Check if this must be emitted as declare variant and emit reference to 3104*7330f729Sjoerg // the the declare variant function. 3105*7330f729Sjoerg if (LangOpts.OpenMP && OpenMPRuntime) 3106*7330f729Sjoerg (void)OpenMPRuntime->emitDeclareVariant(GD, /*IsForDefinition=*/true); 3107*7330f729Sjoerg 3108*7330f729Sjoerg if (FD->isMultiVersion()) { 3109*7330f729Sjoerg const auto *TA = FD->getAttr<TargetAttr>(); 3110*7330f729Sjoerg if (TA && TA->isDefaultVersion()) 3111*7330f729Sjoerg UpdateMultiVersionNames(GD, FD); 3112*7330f729Sjoerg if (!IsForDefinition) 3113*7330f729Sjoerg return GetOrCreateMultiVersionResolver(GD, Ty, FD); 3114*7330f729Sjoerg } 3115*7330f729Sjoerg } 3116*7330f729Sjoerg 3117*7330f729Sjoerg // Lookup the entry, lazily creating it if necessary. 3118*7330f729Sjoerg llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3119*7330f729Sjoerg if (Entry) { 3120*7330f729Sjoerg if (WeakRefReferences.erase(Entry)) { 3121*7330f729Sjoerg const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 3122*7330f729Sjoerg if (FD && !FD->hasAttr<WeakAttr>()) 3123*7330f729Sjoerg Entry->setLinkage(llvm::Function::ExternalLinkage); 3124*7330f729Sjoerg } 3125*7330f729Sjoerg 3126*7330f729Sjoerg // Handle dropped DLL attributes. 3127*7330f729Sjoerg if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) { 3128*7330f729Sjoerg Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 3129*7330f729Sjoerg setDSOLocal(Entry); 3130*7330f729Sjoerg } 3131*7330f729Sjoerg 3132*7330f729Sjoerg // If there are two attempts to define the same mangled name, issue an 3133*7330f729Sjoerg // error. 3134*7330f729Sjoerg if (IsForDefinition && !Entry->isDeclaration()) { 3135*7330f729Sjoerg GlobalDecl OtherGD; 3136*7330f729Sjoerg // Check that GD is not yet in DiagnosedConflictingDefinitions is required 3137*7330f729Sjoerg // to make sure that we issue an error only once. 3138*7330f729Sjoerg if (lookupRepresentativeDecl(MangledName, OtherGD) && 3139*7330f729Sjoerg (GD.getCanonicalDecl().getDecl() != 3140*7330f729Sjoerg OtherGD.getCanonicalDecl().getDecl()) && 3141*7330f729Sjoerg DiagnosedConflictingDefinitions.insert(GD).second) { 3142*7330f729Sjoerg getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 3143*7330f729Sjoerg << MangledName; 3144*7330f729Sjoerg getDiags().Report(OtherGD.getDecl()->getLocation(), 3145*7330f729Sjoerg diag::note_previous_definition); 3146*7330f729Sjoerg } 3147*7330f729Sjoerg } 3148*7330f729Sjoerg 3149*7330f729Sjoerg if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 3150*7330f729Sjoerg (Entry->getType()->getElementType() == Ty)) { 3151*7330f729Sjoerg return Entry; 3152*7330f729Sjoerg } 3153*7330f729Sjoerg 3154*7330f729Sjoerg // Make sure the result is of the correct type. 3155*7330f729Sjoerg // (If function is requested for a definition, we always need to create a new 3156*7330f729Sjoerg // function, not just return a bitcast.) 3157*7330f729Sjoerg if (!IsForDefinition) 3158*7330f729Sjoerg return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 3159*7330f729Sjoerg } 3160*7330f729Sjoerg 3161*7330f729Sjoerg // This function doesn't have a complete type (for example, the return 3162*7330f729Sjoerg // type is an incomplete struct). Use a fake type instead, and make 3163*7330f729Sjoerg // sure not to try to set attributes. 3164*7330f729Sjoerg bool IsIncompleteFunction = false; 3165*7330f729Sjoerg 3166*7330f729Sjoerg llvm::FunctionType *FTy; 3167*7330f729Sjoerg if (isa<llvm::FunctionType>(Ty)) { 3168*7330f729Sjoerg FTy = cast<llvm::FunctionType>(Ty); 3169*7330f729Sjoerg } else { 3170*7330f729Sjoerg FTy = llvm::FunctionType::get(VoidTy, false); 3171*7330f729Sjoerg IsIncompleteFunction = true; 3172*7330f729Sjoerg } 3173*7330f729Sjoerg 3174*7330f729Sjoerg llvm::Function *F = 3175*7330f729Sjoerg llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 3176*7330f729Sjoerg Entry ? StringRef() : MangledName, &getModule()); 3177*7330f729Sjoerg 3178*7330f729Sjoerg // If we already created a function with the same mangled name (but different 3179*7330f729Sjoerg // type) before, take its name and add it to the list of functions to be 3180*7330f729Sjoerg // replaced with F at the end of CodeGen. 3181*7330f729Sjoerg // 3182*7330f729Sjoerg // This happens if there is a prototype for a function (e.g. "int f()") and 3183*7330f729Sjoerg // then a definition of a different type (e.g. "int f(int x)"). 3184*7330f729Sjoerg if (Entry) { 3185*7330f729Sjoerg F->takeName(Entry); 3186*7330f729Sjoerg 3187*7330f729Sjoerg // This might be an implementation of a function without a prototype, in 3188*7330f729Sjoerg // which case, try to do special replacement of calls which match the new 3189*7330f729Sjoerg // prototype. The really key thing here is that we also potentially drop 3190*7330f729Sjoerg // arguments from the call site so as to make a direct call, which makes the 3191*7330f729Sjoerg // inliner happier and suppresses a number of optimizer warnings (!) about 3192*7330f729Sjoerg // dropping arguments. 3193*7330f729Sjoerg if (!Entry->use_empty()) { 3194*7330f729Sjoerg ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 3195*7330f729Sjoerg Entry->removeDeadConstantUsers(); 3196*7330f729Sjoerg } 3197*7330f729Sjoerg 3198*7330f729Sjoerg llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 3199*7330f729Sjoerg F, Entry->getType()->getElementType()->getPointerTo()); 3200*7330f729Sjoerg addGlobalValReplacement(Entry, BC); 3201*7330f729Sjoerg } 3202*7330f729Sjoerg 3203*7330f729Sjoerg assert(F->getName() == MangledName && "name was uniqued!"); 3204*7330f729Sjoerg if (D) 3205*7330f729Sjoerg SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 3206*7330f729Sjoerg if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) { 3207*7330f729Sjoerg llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex); 3208*7330f729Sjoerg F->addAttributes(llvm::AttributeList::FunctionIndex, B); 3209*7330f729Sjoerg } 3210*7330f729Sjoerg 3211*7330f729Sjoerg if (!DontDefer) { 3212*7330f729Sjoerg // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 3213*7330f729Sjoerg // each other bottoming out with the base dtor. Therefore we emit non-base 3214*7330f729Sjoerg // dtors on usage, even if there is no dtor definition in the TU. 3215*7330f729Sjoerg if (D && isa<CXXDestructorDecl>(D) && 3216*7330f729Sjoerg getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 3217*7330f729Sjoerg GD.getDtorType())) 3218*7330f729Sjoerg addDeferredDeclToEmit(GD); 3219*7330f729Sjoerg 3220*7330f729Sjoerg // This is the first use or definition of a mangled name. If there is a 3221*7330f729Sjoerg // deferred decl with this name, remember that we need to emit it at the end 3222*7330f729Sjoerg // of the file. 3223*7330f729Sjoerg auto DDI = DeferredDecls.find(MangledName); 3224*7330f729Sjoerg if (DDI != DeferredDecls.end()) { 3225*7330f729Sjoerg // Move the potentially referenced deferred decl to the 3226*7330f729Sjoerg // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 3227*7330f729Sjoerg // don't need it anymore). 3228*7330f729Sjoerg addDeferredDeclToEmit(DDI->second); 3229*7330f729Sjoerg DeferredDecls.erase(DDI); 3230*7330f729Sjoerg 3231*7330f729Sjoerg // Otherwise, there are cases we have to worry about where we're 3232*7330f729Sjoerg // using a declaration for which we must emit a definition but where 3233*7330f729Sjoerg // we might not find a top-level definition: 3234*7330f729Sjoerg // - member functions defined inline in their classes 3235*7330f729Sjoerg // - friend functions defined inline in some class 3236*7330f729Sjoerg // - special member functions with implicit definitions 3237*7330f729Sjoerg // If we ever change our AST traversal to walk into class methods, 3238*7330f729Sjoerg // this will be unnecessary. 3239*7330f729Sjoerg // 3240*7330f729Sjoerg // We also don't emit a definition for a function if it's going to be an 3241*7330f729Sjoerg // entry in a vtable, unless it's already marked as used. 3242*7330f729Sjoerg } else if (getLangOpts().CPlusPlus && D) { 3243*7330f729Sjoerg // Look for a declaration that's lexically in a record. 3244*7330f729Sjoerg for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 3245*7330f729Sjoerg FD = FD->getPreviousDecl()) { 3246*7330f729Sjoerg if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 3247*7330f729Sjoerg if (FD->doesThisDeclarationHaveABody()) { 3248*7330f729Sjoerg addDeferredDeclToEmit(GD.getWithDecl(FD)); 3249*7330f729Sjoerg break; 3250*7330f729Sjoerg } 3251*7330f729Sjoerg } 3252*7330f729Sjoerg } 3253*7330f729Sjoerg } 3254*7330f729Sjoerg } 3255*7330f729Sjoerg 3256*7330f729Sjoerg // Make sure the result is of the requested type. 3257*7330f729Sjoerg if (!IsIncompleteFunction) { 3258*7330f729Sjoerg assert(F->getType()->getElementType() == Ty); 3259*7330f729Sjoerg return F; 3260*7330f729Sjoerg } 3261*7330f729Sjoerg 3262*7330f729Sjoerg llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 3263*7330f729Sjoerg return llvm::ConstantExpr::getBitCast(F, PTy); 3264*7330f729Sjoerg } 3265*7330f729Sjoerg 3266*7330f729Sjoerg /// GetAddrOfFunction - Return the address of the given function. If Ty is 3267*7330f729Sjoerg /// non-null, then this function will use the specified type if it has to 3268*7330f729Sjoerg /// create it (this occurs when we see a definition of the function). 3269*7330f729Sjoerg llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 3270*7330f729Sjoerg llvm::Type *Ty, 3271*7330f729Sjoerg bool ForVTable, 3272*7330f729Sjoerg bool DontDefer, 3273*7330f729Sjoerg ForDefinition_t IsForDefinition) { 3274*7330f729Sjoerg // If there was no specific requested type, just convert it now. 3275*7330f729Sjoerg if (!Ty) { 3276*7330f729Sjoerg const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3277*7330f729Sjoerg Ty = getTypes().ConvertType(FD->getType()); 3278*7330f729Sjoerg } 3279*7330f729Sjoerg 3280*7330f729Sjoerg // Devirtualized destructor calls may come through here instead of via 3281*7330f729Sjoerg // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead 3282*7330f729Sjoerg // of the complete destructor when necessary. 3283*7330f729Sjoerg if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) { 3284*7330f729Sjoerg if (getTarget().getCXXABI().isMicrosoft() && 3285*7330f729Sjoerg GD.getDtorType() == Dtor_Complete && 3286*7330f729Sjoerg DD->getParent()->getNumVBases() == 0) 3287*7330f729Sjoerg GD = GlobalDecl(DD, Dtor_Base); 3288*7330f729Sjoerg } 3289*7330f729Sjoerg 3290*7330f729Sjoerg StringRef MangledName = getMangledName(GD); 3291*7330f729Sjoerg return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 3292*7330f729Sjoerg /*IsThunk=*/false, llvm::AttributeList(), 3293*7330f729Sjoerg IsForDefinition); 3294*7330f729Sjoerg } 3295*7330f729Sjoerg 3296*7330f729Sjoerg static const FunctionDecl * 3297*7330f729Sjoerg GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 3298*7330f729Sjoerg TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 3299*7330f729Sjoerg DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 3300*7330f729Sjoerg 3301*7330f729Sjoerg IdentifierInfo &CII = C.Idents.get(Name); 3302*7330f729Sjoerg for (const auto &Result : DC->lookup(&CII)) 3303*7330f729Sjoerg if (const auto FD = dyn_cast<FunctionDecl>(Result)) 3304*7330f729Sjoerg return FD; 3305*7330f729Sjoerg 3306*7330f729Sjoerg if (!C.getLangOpts().CPlusPlus) 3307*7330f729Sjoerg return nullptr; 3308*7330f729Sjoerg 3309*7330f729Sjoerg // Demangle the premangled name from getTerminateFn() 3310*7330f729Sjoerg IdentifierInfo &CXXII = 3311*7330f729Sjoerg (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") 3312*7330f729Sjoerg ? C.Idents.get("terminate") 3313*7330f729Sjoerg : C.Idents.get(Name); 3314*7330f729Sjoerg 3315*7330f729Sjoerg for (const auto &N : {"__cxxabiv1", "std"}) { 3316*7330f729Sjoerg IdentifierInfo &NS = C.Idents.get(N); 3317*7330f729Sjoerg for (const auto &Result : DC->lookup(&NS)) { 3318*7330f729Sjoerg NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 3319*7330f729Sjoerg if (auto LSD = dyn_cast<LinkageSpecDecl>(Result)) 3320*7330f729Sjoerg for (const auto &Result : LSD->lookup(&NS)) 3321*7330f729Sjoerg if ((ND = dyn_cast<NamespaceDecl>(Result))) 3322*7330f729Sjoerg break; 3323*7330f729Sjoerg 3324*7330f729Sjoerg if (ND) 3325*7330f729Sjoerg for (const auto &Result : ND->lookup(&CXXII)) 3326*7330f729Sjoerg if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 3327*7330f729Sjoerg return FD; 3328*7330f729Sjoerg } 3329*7330f729Sjoerg } 3330*7330f729Sjoerg 3331*7330f729Sjoerg return nullptr; 3332*7330f729Sjoerg } 3333*7330f729Sjoerg 3334*7330f729Sjoerg /// CreateRuntimeFunction - Create a new runtime function with the specified 3335*7330f729Sjoerg /// type and name. 3336*7330f729Sjoerg llvm::FunctionCallee 3337*7330f729Sjoerg CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 3338*7330f729Sjoerg llvm::AttributeList ExtraAttrs, bool Local, 3339*7330f729Sjoerg bool AssumeConvergent) { 3340*7330f729Sjoerg if (AssumeConvergent) { 3341*7330f729Sjoerg ExtraAttrs = 3342*7330f729Sjoerg ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex, 3343*7330f729Sjoerg llvm::Attribute::Convergent); 3344*7330f729Sjoerg } 3345*7330f729Sjoerg 3346*7330f729Sjoerg llvm::Constant *C = 3347*7330f729Sjoerg GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 3348*7330f729Sjoerg /*DontDefer=*/false, /*IsThunk=*/false, 3349*7330f729Sjoerg ExtraAttrs); 3350*7330f729Sjoerg 3351*7330f729Sjoerg if (auto *F = dyn_cast<llvm::Function>(C)) { 3352*7330f729Sjoerg if (F->empty()) { 3353*7330f729Sjoerg F->setCallingConv(getRuntimeCC()); 3354*7330f729Sjoerg 3355*7330f729Sjoerg // In Windows Itanium environments, try to mark runtime functions 3356*7330f729Sjoerg // dllimport. For Mingw and MSVC, don't. We don't really know if the user 3357*7330f729Sjoerg // will link their standard library statically or dynamically. Marking 3358*7330f729Sjoerg // functions imported when they are not imported can cause linker errors 3359*7330f729Sjoerg // and warnings. 3360*7330f729Sjoerg if (!Local && getTriple().isWindowsItaniumEnvironment() && 3361*7330f729Sjoerg !getCodeGenOpts().LTOVisibilityPublicStd) { 3362*7330f729Sjoerg const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 3363*7330f729Sjoerg if (!FD || FD->hasAttr<DLLImportAttr>()) { 3364*7330f729Sjoerg F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3365*7330f729Sjoerg F->setLinkage(llvm::GlobalValue::ExternalLinkage); 3366*7330f729Sjoerg } 3367*7330f729Sjoerg } 3368*7330f729Sjoerg setDSOLocal(F); 3369*7330f729Sjoerg } 3370*7330f729Sjoerg } 3371*7330f729Sjoerg 3372*7330f729Sjoerg return {FTy, C}; 3373*7330f729Sjoerg } 3374*7330f729Sjoerg 3375*7330f729Sjoerg /// isTypeConstant - Determine whether an object of this type can be emitted 3376*7330f729Sjoerg /// as a constant. 3377*7330f729Sjoerg /// 3378*7330f729Sjoerg /// If ExcludeCtor is true, the duration when the object's constructor runs 3379*7330f729Sjoerg /// will not be considered. The caller will need to verify that the object is 3380*7330f729Sjoerg /// not written to during its construction. 3381*7330f729Sjoerg bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 3382*7330f729Sjoerg if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 3383*7330f729Sjoerg return false; 3384*7330f729Sjoerg 3385*7330f729Sjoerg if (Context.getLangOpts().CPlusPlus) { 3386*7330f729Sjoerg if (const CXXRecordDecl *Record 3387*7330f729Sjoerg = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 3388*7330f729Sjoerg return ExcludeCtor && !Record->hasMutableFields() && 3389*7330f729Sjoerg Record->hasTrivialDestructor(); 3390*7330f729Sjoerg } 3391*7330f729Sjoerg 3392*7330f729Sjoerg return true; 3393*7330f729Sjoerg } 3394*7330f729Sjoerg 3395*7330f729Sjoerg /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 3396*7330f729Sjoerg /// create and return an llvm GlobalVariable with the specified type. If there 3397*7330f729Sjoerg /// is something in the module with the specified name, return it potentially 3398*7330f729Sjoerg /// bitcasted to the right type. 3399*7330f729Sjoerg /// 3400*7330f729Sjoerg /// If D is non-null, it specifies a decl that correspond to this. This is used 3401*7330f729Sjoerg /// to set the attributes on the global when it is first created. 3402*7330f729Sjoerg /// 3403*7330f729Sjoerg /// If IsForDefinition is true, it is guaranteed that an actual global with 3404*7330f729Sjoerg /// type Ty will be returned, not conversion of a variable with the same 3405*7330f729Sjoerg /// mangled name but some other type. 3406*7330f729Sjoerg llvm::Constant * 3407*7330f729Sjoerg CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 3408*7330f729Sjoerg llvm::PointerType *Ty, 3409*7330f729Sjoerg const VarDecl *D, 3410*7330f729Sjoerg ForDefinition_t IsForDefinition) { 3411*7330f729Sjoerg // Lookup the entry, lazily creating it if necessary. 3412*7330f729Sjoerg llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3413*7330f729Sjoerg if (Entry) { 3414*7330f729Sjoerg if (WeakRefReferences.erase(Entry)) { 3415*7330f729Sjoerg if (D && !D->hasAttr<WeakAttr>()) 3416*7330f729Sjoerg Entry->setLinkage(llvm::Function::ExternalLinkage); 3417*7330f729Sjoerg } 3418*7330f729Sjoerg 3419*7330f729Sjoerg // Handle dropped DLL attributes. 3420*7330f729Sjoerg if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 3421*7330f729Sjoerg Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 3422*7330f729Sjoerg 3423*7330f729Sjoerg if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) 3424*7330f729Sjoerg getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); 3425*7330f729Sjoerg 3426*7330f729Sjoerg if (Entry->getType() == Ty) 3427*7330f729Sjoerg return Entry; 3428*7330f729Sjoerg 3429*7330f729Sjoerg // If there are two attempts to define the same mangled name, issue an 3430*7330f729Sjoerg // error. 3431*7330f729Sjoerg if (IsForDefinition && !Entry->isDeclaration()) { 3432*7330f729Sjoerg GlobalDecl OtherGD; 3433*7330f729Sjoerg const VarDecl *OtherD; 3434*7330f729Sjoerg 3435*7330f729Sjoerg // Check that D is not yet in DiagnosedConflictingDefinitions is required 3436*7330f729Sjoerg // to make sure that we issue an error only once. 3437*7330f729Sjoerg if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 3438*7330f729Sjoerg (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 3439*7330f729Sjoerg (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 3440*7330f729Sjoerg OtherD->hasInit() && 3441*7330f729Sjoerg DiagnosedConflictingDefinitions.insert(D).second) { 3442*7330f729Sjoerg getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 3443*7330f729Sjoerg << MangledName; 3444*7330f729Sjoerg getDiags().Report(OtherGD.getDecl()->getLocation(), 3445*7330f729Sjoerg diag::note_previous_definition); 3446*7330f729Sjoerg } 3447*7330f729Sjoerg } 3448*7330f729Sjoerg 3449*7330f729Sjoerg // Make sure the result is of the correct type. 3450*7330f729Sjoerg if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 3451*7330f729Sjoerg return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 3452*7330f729Sjoerg 3453*7330f729Sjoerg // (If global is requested for a definition, we always need to create a new 3454*7330f729Sjoerg // global, not just return a bitcast.) 3455*7330f729Sjoerg if (!IsForDefinition) 3456*7330f729Sjoerg return llvm::ConstantExpr::getBitCast(Entry, Ty); 3457*7330f729Sjoerg } 3458*7330f729Sjoerg 3459*7330f729Sjoerg auto AddrSpace = GetGlobalVarAddressSpace(D); 3460*7330f729Sjoerg auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace); 3461*7330f729Sjoerg 3462*7330f729Sjoerg auto *GV = new llvm::GlobalVariable( 3463*7330f729Sjoerg getModule(), Ty->getElementType(), false, 3464*7330f729Sjoerg llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 3465*7330f729Sjoerg llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace); 3466*7330f729Sjoerg 3467*7330f729Sjoerg // If we already created a global with the same mangled name (but different 3468*7330f729Sjoerg // type) before, take its name and remove it from its parent. 3469*7330f729Sjoerg if (Entry) { 3470*7330f729Sjoerg GV->takeName(Entry); 3471*7330f729Sjoerg 3472*7330f729Sjoerg if (!Entry->use_empty()) { 3473*7330f729Sjoerg llvm::Constant *NewPtrForOldDecl = 3474*7330f729Sjoerg llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 3475*7330f729Sjoerg Entry->replaceAllUsesWith(NewPtrForOldDecl); 3476*7330f729Sjoerg } 3477*7330f729Sjoerg 3478*7330f729Sjoerg Entry->eraseFromParent(); 3479*7330f729Sjoerg } 3480*7330f729Sjoerg 3481*7330f729Sjoerg // This is the first use or definition of a mangled name. If there is a 3482*7330f729Sjoerg // deferred decl with this name, remember that we need to emit it at the end 3483*7330f729Sjoerg // of the file. 3484*7330f729Sjoerg auto DDI = DeferredDecls.find(MangledName); 3485*7330f729Sjoerg if (DDI != DeferredDecls.end()) { 3486*7330f729Sjoerg // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 3487*7330f729Sjoerg // list, and remove it from DeferredDecls (since we don't need it anymore). 3488*7330f729Sjoerg addDeferredDeclToEmit(DDI->second); 3489*7330f729Sjoerg DeferredDecls.erase(DDI); 3490*7330f729Sjoerg } 3491*7330f729Sjoerg 3492*7330f729Sjoerg // Handle things which are present even on external declarations. 3493*7330f729Sjoerg if (D) { 3494*7330f729Sjoerg if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) 3495*7330f729Sjoerg getOpenMPRuntime().registerTargetGlobalVariable(D, GV); 3496*7330f729Sjoerg 3497*7330f729Sjoerg // FIXME: This code is overly simple and should be merged with other global 3498*7330f729Sjoerg // handling. 3499*7330f729Sjoerg GV->setConstant(isTypeConstant(D->getType(), false)); 3500*7330f729Sjoerg 3501*7330f729Sjoerg GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 3502*7330f729Sjoerg 3503*7330f729Sjoerg setLinkageForGV(GV, D); 3504*7330f729Sjoerg 3505*7330f729Sjoerg if (D->getTLSKind()) { 3506*7330f729Sjoerg if (D->getTLSKind() == VarDecl::TLS_Dynamic) 3507*7330f729Sjoerg CXXThreadLocals.push_back(D); 3508*7330f729Sjoerg setTLSMode(GV, *D); 3509*7330f729Sjoerg } 3510*7330f729Sjoerg 3511*7330f729Sjoerg setGVProperties(GV, D); 3512*7330f729Sjoerg 3513*7330f729Sjoerg // If required by the ABI, treat declarations of static data members with 3514*7330f729Sjoerg // inline initializers as definitions. 3515*7330f729Sjoerg if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 3516*7330f729Sjoerg EmitGlobalVarDefinition(D); 3517*7330f729Sjoerg } 3518*7330f729Sjoerg 3519*7330f729Sjoerg // Emit section information for extern variables. 3520*7330f729Sjoerg if (D->hasExternalStorage()) { 3521*7330f729Sjoerg if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 3522*7330f729Sjoerg GV->setSection(SA->getName()); 3523*7330f729Sjoerg } 3524*7330f729Sjoerg 3525*7330f729Sjoerg // Handle XCore specific ABI requirements. 3526*7330f729Sjoerg if (getTriple().getArch() == llvm::Triple::xcore && 3527*7330f729Sjoerg D->getLanguageLinkage() == CLanguageLinkage && 3528*7330f729Sjoerg D->getType().isConstant(Context) && 3529*7330f729Sjoerg isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 3530*7330f729Sjoerg GV->setSection(".cp.rodata"); 3531*7330f729Sjoerg 3532*7330f729Sjoerg // Check if we a have a const declaration with an initializer, we may be 3533*7330f729Sjoerg // able to emit it as available_externally to expose it's value to the 3534*7330f729Sjoerg // optimizer. 3535*7330f729Sjoerg if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 3536*7330f729Sjoerg D->getType().isConstQualified() && !GV->hasInitializer() && 3537*7330f729Sjoerg !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 3538*7330f729Sjoerg const auto *Record = 3539*7330f729Sjoerg Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 3540*7330f729Sjoerg bool HasMutableFields = Record && Record->hasMutableFields(); 3541*7330f729Sjoerg if (!HasMutableFields) { 3542*7330f729Sjoerg const VarDecl *InitDecl; 3543*7330f729Sjoerg const Expr *InitExpr = D->getAnyInitializer(InitDecl); 3544*7330f729Sjoerg if (InitExpr) { 3545*7330f729Sjoerg ConstantEmitter emitter(*this); 3546*7330f729Sjoerg llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 3547*7330f729Sjoerg if (Init) { 3548*7330f729Sjoerg auto *InitType = Init->getType(); 3549*7330f729Sjoerg if (GV->getType()->getElementType() != InitType) { 3550*7330f729Sjoerg // The type of the initializer does not match the definition. 3551*7330f729Sjoerg // This happens when an initializer has a different type from 3552*7330f729Sjoerg // the type of the global (because of padding at the end of a 3553*7330f729Sjoerg // structure for instance). 3554*7330f729Sjoerg GV->setName(StringRef()); 3555*7330f729Sjoerg // Make a new global with the correct type, this is now guaranteed 3556*7330f729Sjoerg // to work. 3557*7330f729Sjoerg auto *NewGV = cast<llvm::GlobalVariable>( 3558*7330f729Sjoerg GetAddrOfGlobalVar(D, InitType, IsForDefinition) 3559*7330f729Sjoerg ->stripPointerCasts()); 3560*7330f729Sjoerg 3561*7330f729Sjoerg // Erase the old global, since it is no longer used. 3562*7330f729Sjoerg GV->eraseFromParent(); 3563*7330f729Sjoerg GV = NewGV; 3564*7330f729Sjoerg } else { 3565*7330f729Sjoerg GV->setInitializer(Init); 3566*7330f729Sjoerg GV->setConstant(true); 3567*7330f729Sjoerg GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 3568*7330f729Sjoerg } 3569*7330f729Sjoerg emitter.finalize(GV); 3570*7330f729Sjoerg } 3571*7330f729Sjoerg } 3572*7330f729Sjoerg } 3573*7330f729Sjoerg } 3574*7330f729Sjoerg } 3575*7330f729Sjoerg 3576*7330f729Sjoerg LangAS ExpectedAS = 3577*7330f729Sjoerg D ? D->getType().getAddressSpace() 3578*7330f729Sjoerg : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 3579*7330f729Sjoerg assert(getContext().getTargetAddressSpace(ExpectedAS) == 3580*7330f729Sjoerg Ty->getPointerAddressSpace()); 3581*7330f729Sjoerg if (AddrSpace != ExpectedAS) 3582*7330f729Sjoerg return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace, 3583*7330f729Sjoerg ExpectedAS, Ty); 3584*7330f729Sjoerg 3585*7330f729Sjoerg if (GV->isDeclaration()) 3586*7330f729Sjoerg getTargetCodeGenInfo().setTargetAttributes(D, GV, *this); 3587*7330f729Sjoerg 3588*7330f729Sjoerg return GV; 3589*7330f729Sjoerg } 3590*7330f729Sjoerg 3591*7330f729Sjoerg llvm::Constant * 3592*7330f729Sjoerg CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, 3593*7330f729Sjoerg ForDefinition_t IsForDefinition) { 3594*7330f729Sjoerg const Decl *D = GD.getDecl(); 3595*7330f729Sjoerg if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 3596*7330f729Sjoerg return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, 3597*7330f729Sjoerg /*DontDefer=*/false, IsForDefinition); 3598*7330f729Sjoerg else if (isa<CXXMethodDecl>(D)) { 3599*7330f729Sjoerg auto FInfo = &getTypes().arrangeCXXMethodDeclaration( 3600*7330f729Sjoerg cast<CXXMethodDecl>(D)); 3601*7330f729Sjoerg auto Ty = getTypes().GetFunctionType(*FInfo); 3602*7330f729Sjoerg return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 3603*7330f729Sjoerg IsForDefinition); 3604*7330f729Sjoerg } else if (isa<FunctionDecl>(D)) { 3605*7330f729Sjoerg const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3606*7330f729Sjoerg llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 3607*7330f729Sjoerg return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 3608*7330f729Sjoerg IsForDefinition); 3609*7330f729Sjoerg } else 3610*7330f729Sjoerg return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, 3611*7330f729Sjoerg IsForDefinition); 3612*7330f729Sjoerg } 3613*7330f729Sjoerg 3614*7330f729Sjoerg llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( 3615*7330f729Sjoerg StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, 3616*7330f729Sjoerg unsigned Alignment) { 3617*7330f729Sjoerg llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 3618*7330f729Sjoerg llvm::GlobalVariable *OldGV = nullptr; 3619*7330f729Sjoerg 3620*7330f729Sjoerg if (GV) { 3621*7330f729Sjoerg // Check if the variable has the right type. 3622*7330f729Sjoerg if (GV->getType()->getElementType() == Ty) 3623*7330f729Sjoerg return GV; 3624*7330f729Sjoerg 3625*7330f729Sjoerg // Because C++ name mangling, the only way we can end up with an already 3626*7330f729Sjoerg // existing global with the same name is if it has been declared extern "C". 3627*7330f729Sjoerg assert(GV->isDeclaration() && "Declaration has wrong type!"); 3628*7330f729Sjoerg OldGV = GV; 3629*7330f729Sjoerg } 3630*7330f729Sjoerg 3631*7330f729Sjoerg // Create a new variable. 3632*7330f729Sjoerg GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 3633*7330f729Sjoerg Linkage, nullptr, Name); 3634*7330f729Sjoerg 3635*7330f729Sjoerg if (OldGV) { 3636*7330f729Sjoerg // Replace occurrences of the old variable if needed. 3637*7330f729Sjoerg GV->takeName(OldGV); 3638*7330f729Sjoerg 3639*7330f729Sjoerg if (!OldGV->use_empty()) { 3640*7330f729Sjoerg llvm::Constant *NewPtrForOldDecl = 3641*7330f729Sjoerg llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 3642*7330f729Sjoerg OldGV->replaceAllUsesWith(NewPtrForOldDecl); 3643*7330f729Sjoerg } 3644*7330f729Sjoerg 3645*7330f729Sjoerg OldGV->eraseFromParent(); 3646*7330f729Sjoerg } 3647*7330f729Sjoerg 3648*7330f729Sjoerg if (supportsCOMDAT() && GV->isWeakForLinker() && 3649*7330f729Sjoerg !GV->hasAvailableExternallyLinkage()) 3650*7330f729Sjoerg GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3651*7330f729Sjoerg 3652*7330f729Sjoerg GV->setAlignment(llvm::MaybeAlign(Alignment)); 3653*7330f729Sjoerg 3654*7330f729Sjoerg return GV; 3655*7330f729Sjoerg } 3656*7330f729Sjoerg 3657*7330f729Sjoerg /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 3658*7330f729Sjoerg /// given global variable. If Ty is non-null and if the global doesn't exist, 3659*7330f729Sjoerg /// then it will be created with the specified type instead of whatever the 3660*7330f729Sjoerg /// normal requested type would be. If IsForDefinition is true, it is guaranteed 3661*7330f729Sjoerg /// that an actual global with type Ty will be returned, not conversion of a 3662*7330f729Sjoerg /// variable with the same mangled name but some other type. 3663*7330f729Sjoerg llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 3664*7330f729Sjoerg llvm::Type *Ty, 3665*7330f729Sjoerg ForDefinition_t IsForDefinition) { 3666*7330f729Sjoerg assert(D->hasGlobalStorage() && "Not a global variable"); 3667*7330f729Sjoerg QualType ASTTy = D->getType(); 3668*7330f729Sjoerg if (!Ty) 3669*7330f729Sjoerg Ty = getTypes().ConvertTypeForMem(ASTTy); 3670*7330f729Sjoerg 3671*7330f729Sjoerg llvm::PointerType *PTy = 3672*7330f729Sjoerg llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 3673*7330f729Sjoerg 3674*7330f729Sjoerg StringRef MangledName = getMangledName(D); 3675*7330f729Sjoerg return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition); 3676*7330f729Sjoerg } 3677*7330f729Sjoerg 3678*7330f729Sjoerg /// CreateRuntimeVariable - Create a new runtime global variable with the 3679*7330f729Sjoerg /// specified type and name. 3680*7330f729Sjoerg llvm::Constant * 3681*7330f729Sjoerg CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 3682*7330f729Sjoerg StringRef Name) { 3683*7330f729Sjoerg auto PtrTy = 3684*7330f729Sjoerg getContext().getLangOpts().OpenCL 3685*7330f729Sjoerg ? llvm::PointerType::get( 3686*7330f729Sjoerg Ty, getContext().getTargetAddressSpace(LangAS::opencl_global)) 3687*7330f729Sjoerg : llvm::PointerType::getUnqual(Ty); 3688*7330f729Sjoerg auto *Ret = GetOrCreateLLVMGlobal(Name, PtrTy, nullptr); 3689*7330f729Sjoerg setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); 3690*7330f729Sjoerg return Ret; 3691*7330f729Sjoerg } 3692*7330f729Sjoerg 3693*7330f729Sjoerg void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 3694*7330f729Sjoerg assert(!D->getInit() && "Cannot emit definite definitions here!"); 3695*7330f729Sjoerg 3696*7330f729Sjoerg StringRef MangledName = getMangledName(D); 3697*7330f729Sjoerg llvm::GlobalValue *GV = GetGlobalValue(MangledName); 3698*7330f729Sjoerg 3699*7330f729Sjoerg // We already have a definition, not declaration, with the same mangled name. 3700*7330f729Sjoerg // Emitting of declaration is not required (and actually overwrites emitted 3701*7330f729Sjoerg // definition). 3702*7330f729Sjoerg if (GV && !GV->isDeclaration()) 3703*7330f729Sjoerg return; 3704*7330f729Sjoerg 3705*7330f729Sjoerg // If we have not seen a reference to this variable yet, place it into the 3706*7330f729Sjoerg // deferred declarations table to be emitted if needed later. 3707*7330f729Sjoerg if (!MustBeEmitted(D) && !GV) { 3708*7330f729Sjoerg DeferredDecls[MangledName] = D; 3709*7330f729Sjoerg return; 3710*7330f729Sjoerg } 3711*7330f729Sjoerg 3712*7330f729Sjoerg // The tentative definition is the only definition. 3713*7330f729Sjoerg EmitGlobalVarDefinition(D); 3714*7330f729Sjoerg } 3715*7330f729Sjoerg 3716*7330f729Sjoerg CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 3717*7330f729Sjoerg return Context.toCharUnitsFromBits( 3718*7330f729Sjoerg getDataLayout().getTypeStoreSizeInBits(Ty)); 3719*7330f729Sjoerg } 3720*7330f729Sjoerg 3721*7330f729Sjoerg LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 3722*7330f729Sjoerg LangAS AddrSpace = LangAS::Default; 3723*7330f729Sjoerg if (LangOpts.OpenCL) { 3724*7330f729Sjoerg AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global; 3725*7330f729Sjoerg assert(AddrSpace == LangAS::opencl_global || 3726*7330f729Sjoerg AddrSpace == LangAS::opencl_constant || 3727*7330f729Sjoerg AddrSpace == LangAS::opencl_local || 3728*7330f729Sjoerg AddrSpace >= LangAS::FirstTargetAddressSpace); 3729*7330f729Sjoerg return AddrSpace; 3730*7330f729Sjoerg } 3731*7330f729Sjoerg 3732*7330f729Sjoerg if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 3733*7330f729Sjoerg if (D && D->hasAttr<CUDAConstantAttr>()) 3734*7330f729Sjoerg return LangAS::cuda_constant; 3735*7330f729Sjoerg else if (D && D->hasAttr<CUDASharedAttr>()) 3736*7330f729Sjoerg return LangAS::cuda_shared; 3737*7330f729Sjoerg else if (D && D->hasAttr<CUDADeviceAttr>()) 3738*7330f729Sjoerg return LangAS::cuda_device; 3739*7330f729Sjoerg else if (D && D->getType().isConstQualified()) 3740*7330f729Sjoerg return LangAS::cuda_constant; 3741*7330f729Sjoerg else 3742*7330f729Sjoerg return LangAS::cuda_device; 3743*7330f729Sjoerg } 3744*7330f729Sjoerg 3745*7330f729Sjoerg if (LangOpts.OpenMP) { 3746*7330f729Sjoerg LangAS AS; 3747*7330f729Sjoerg if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS)) 3748*7330f729Sjoerg return AS; 3749*7330f729Sjoerg } 3750*7330f729Sjoerg return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 3751*7330f729Sjoerg } 3752*7330f729Sjoerg 3753*7330f729Sjoerg LangAS CodeGenModule::getStringLiteralAddressSpace() const { 3754*7330f729Sjoerg // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 3755*7330f729Sjoerg if (LangOpts.OpenCL) 3756*7330f729Sjoerg return LangAS::opencl_constant; 3757*7330f729Sjoerg if (auto AS = getTarget().getConstantAddressSpace()) 3758*7330f729Sjoerg return AS.getValue(); 3759*7330f729Sjoerg return LangAS::Default; 3760*7330f729Sjoerg } 3761*7330f729Sjoerg 3762*7330f729Sjoerg // In address space agnostic languages, string literals are in default address 3763*7330f729Sjoerg // space in AST. However, certain targets (e.g. amdgcn) request them to be 3764*7330f729Sjoerg // emitted in constant address space in LLVM IR. To be consistent with other 3765*7330f729Sjoerg // parts of AST, string literal global variables in constant address space 3766*7330f729Sjoerg // need to be casted to default address space before being put into address 3767*7330f729Sjoerg // map and referenced by other part of CodeGen. 3768*7330f729Sjoerg // In OpenCL, string literals are in constant address space in AST, therefore 3769*7330f729Sjoerg // they should not be casted to default address space. 3770*7330f729Sjoerg static llvm::Constant * 3771*7330f729Sjoerg castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, 3772*7330f729Sjoerg llvm::GlobalVariable *GV) { 3773*7330f729Sjoerg llvm::Constant *Cast = GV; 3774*7330f729Sjoerg if (!CGM.getLangOpts().OpenCL) { 3775*7330f729Sjoerg if (auto AS = CGM.getTarget().getConstantAddressSpace()) { 3776*7330f729Sjoerg if (AS != LangAS::Default) 3777*7330f729Sjoerg Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( 3778*7330f729Sjoerg CGM, GV, AS.getValue(), LangAS::Default, 3779*7330f729Sjoerg GV->getValueType()->getPointerTo( 3780*7330f729Sjoerg CGM.getContext().getTargetAddressSpace(LangAS::Default))); 3781*7330f729Sjoerg } 3782*7330f729Sjoerg } 3783*7330f729Sjoerg return Cast; 3784*7330f729Sjoerg } 3785*7330f729Sjoerg 3786*7330f729Sjoerg template<typename SomeDecl> 3787*7330f729Sjoerg void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 3788*7330f729Sjoerg llvm::GlobalValue *GV) { 3789*7330f729Sjoerg if (!getLangOpts().CPlusPlus) 3790*7330f729Sjoerg return; 3791*7330f729Sjoerg 3792*7330f729Sjoerg // Must have 'used' attribute, or else inline assembly can't rely on 3793*7330f729Sjoerg // the name existing. 3794*7330f729Sjoerg if (!D->template hasAttr<UsedAttr>()) 3795*7330f729Sjoerg return; 3796*7330f729Sjoerg 3797*7330f729Sjoerg // Must have internal linkage and an ordinary name. 3798*7330f729Sjoerg if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 3799*7330f729Sjoerg return; 3800*7330f729Sjoerg 3801*7330f729Sjoerg // Must be in an extern "C" context. Entities declared directly within 3802*7330f729Sjoerg // a record are not extern "C" even if the record is in such a context. 3803*7330f729Sjoerg const SomeDecl *First = D->getFirstDecl(); 3804*7330f729Sjoerg if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 3805*7330f729Sjoerg return; 3806*7330f729Sjoerg 3807*7330f729Sjoerg // OK, this is an internal linkage entity inside an extern "C" linkage 3808*7330f729Sjoerg // specification. Make a note of that so we can give it the "expected" 3809*7330f729Sjoerg // mangled name if nothing else is using that name. 3810*7330f729Sjoerg std::pair<StaticExternCMap::iterator, bool> R = 3811*7330f729Sjoerg StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 3812*7330f729Sjoerg 3813*7330f729Sjoerg // If we have multiple internal linkage entities with the same name 3814*7330f729Sjoerg // in extern "C" regions, none of them gets that name. 3815*7330f729Sjoerg if (!R.second) 3816*7330f729Sjoerg R.first->second = nullptr; 3817*7330f729Sjoerg } 3818*7330f729Sjoerg 3819*7330f729Sjoerg static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 3820*7330f729Sjoerg if (!CGM.supportsCOMDAT()) 3821*7330f729Sjoerg return false; 3822*7330f729Sjoerg 3823*7330f729Sjoerg // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent 3824*7330f729Sjoerg // them being "merged" by the COMDAT Folding linker optimization. 3825*7330f729Sjoerg if (D.hasAttr<CUDAGlobalAttr>()) 3826*7330f729Sjoerg return false; 3827*7330f729Sjoerg 3828*7330f729Sjoerg if (D.hasAttr<SelectAnyAttr>()) 3829*7330f729Sjoerg return true; 3830*7330f729Sjoerg 3831*7330f729Sjoerg GVALinkage Linkage; 3832*7330f729Sjoerg if (auto *VD = dyn_cast<VarDecl>(&D)) 3833*7330f729Sjoerg Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 3834*7330f729Sjoerg else 3835*7330f729Sjoerg Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 3836*7330f729Sjoerg 3837*7330f729Sjoerg switch (Linkage) { 3838*7330f729Sjoerg case GVA_Internal: 3839*7330f729Sjoerg case GVA_AvailableExternally: 3840*7330f729Sjoerg case GVA_StrongExternal: 3841*7330f729Sjoerg return false; 3842*7330f729Sjoerg case GVA_DiscardableODR: 3843*7330f729Sjoerg case GVA_StrongODR: 3844*7330f729Sjoerg return true; 3845*7330f729Sjoerg } 3846*7330f729Sjoerg llvm_unreachable("No such linkage"); 3847*7330f729Sjoerg } 3848*7330f729Sjoerg 3849*7330f729Sjoerg void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 3850*7330f729Sjoerg llvm::GlobalObject &GO) { 3851*7330f729Sjoerg if (!shouldBeInCOMDAT(*this, D)) 3852*7330f729Sjoerg return; 3853*7330f729Sjoerg GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 3854*7330f729Sjoerg } 3855*7330f729Sjoerg 3856*7330f729Sjoerg /// Pass IsTentative as true if you want to create a tentative definition. 3857*7330f729Sjoerg void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 3858*7330f729Sjoerg bool IsTentative) { 3859*7330f729Sjoerg // OpenCL global variables of sampler type are translated to function calls, 3860*7330f729Sjoerg // therefore no need to be translated. 3861*7330f729Sjoerg QualType ASTTy = D->getType(); 3862*7330f729Sjoerg if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 3863*7330f729Sjoerg return; 3864*7330f729Sjoerg 3865*7330f729Sjoerg // If this is OpenMP device, check if it is legal to emit this global 3866*7330f729Sjoerg // normally. 3867*7330f729Sjoerg if (LangOpts.OpenMPIsDevice && OpenMPRuntime && 3868*7330f729Sjoerg OpenMPRuntime->emitTargetGlobalVariable(D)) 3869*7330f729Sjoerg return; 3870*7330f729Sjoerg 3871*7330f729Sjoerg llvm::Constant *Init = nullptr; 3872*7330f729Sjoerg bool NeedsGlobalCtor = false; 3873*7330f729Sjoerg bool NeedsGlobalDtor = 3874*7330f729Sjoerg D->needsDestruction(getContext()) == QualType::DK_cxx_destructor; 3875*7330f729Sjoerg 3876*7330f729Sjoerg const VarDecl *InitDecl; 3877*7330f729Sjoerg const Expr *InitExpr = D->getAnyInitializer(InitDecl); 3878*7330f729Sjoerg 3879*7330f729Sjoerg Optional<ConstantEmitter> emitter; 3880*7330f729Sjoerg 3881*7330f729Sjoerg // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 3882*7330f729Sjoerg // as part of their declaration." Sema has already checked for 3883*7330f729Sjoerg // error cases, so we just need to set Init to UndefValue. 3884*7330f729Sjoerg bool IsCUDASharedVar = 3885*7330f729Sjoerg getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); 3886*7330f729Sjoerg // Shadows of initialized device-side global variables are also left 3887*7330f729Sjoerg // undefined. 3888*7330f729Sjoerg bool IsCUDAShadowVar = 3889*7330f729Sjoerg !getLangOpts().CUDAIsDevice && 3890*7330f729Sjoerg (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || 3891*7330f729Sjoerg D->hasAttr<CUDASharedAttr>()); 3892*7330f729Sjoerg // HIP pinned shadow of initialized host-side global variables are also 3893*7330f729Sjoerg // left undefined. 3894*7330f729Sjoerg bool IsHIPPinnedShadowVar = 3895*7330f729Sjoerg getLangOpts().CUDAIsDevice && D->hasAttr<HIPPinnedShadowAttr>(); 3896*7330f729Sjoerg if (getLangOpts().CUDA && 3897*7330f729Sjoerg (IsCUDASharedVar || IsCUDAShadowVar || IsHIPPinnedShadowVar)) 3898*7330f729Sjoerg Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 3899*7330f729Sjoerg else if (!InitExpr) { 3900*7330f729Sjoerg // This is a tentative definition; tentative definitions are 3901*7330f729Sjoerg // implicitly initialized with { 0 }. 3902*7330f729Sjoerg // 3903*7330f729Sjoerg // Note that tentative definitions are only emitted at the end of 3904*7330f729Sjoerg // a translation unit, so they should never have incomplete 3905*7330f729Sjoerg // type. In addition, EmitTentativeDefinition makes sure that we 3906*7330f729Sjoerg // never attempt to emit a tentative definition if a real one 3907*7330f729Sjoerg // exists. A use may still exists, however, so we still may need 3908*7330f729Sjoerg // to do a RAUW. 3909*7330f729Sjoerg assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 3910*7330f729Sjoerg Init = EmitNullConstant(D->getType()); 3911*7330f729Sjoerg } else { 3912*7330f729Sjoerg initializedGlobalDecl = GlobalDecl(D); 3913*7330f729Sjoerg emitter.emplace(*this); 3914*7330f729Sjoerg Init = emitter->tryEmitForInitializer(*InitDecl); 3915*7330f729Sjoerg 3916*7330f729Sjoerg if (!Init) { 3917*7330f729Sjoerg QualType T = InitExpr->getType(); 3918*7330f729Sjoerg if (D->getType()->isReferenceType()) 3919*7330f729Sjoerg T = D->getType(); 3920*7330f729Sjoerg 3921*7330f729Sjoerg if (getLangOpts().CPlusPlus) { 3922*7330f729Sjoerg Init = EmitNullConstant(T); 3923*7330f729Sjoerg NeedsGlobalCtor = true; 3924*7330f729Sjoerg } else { 3925*7330f729Sjoerg ErrorUnsupported(D, "static initializer"); 3926*7330f729Sjoerg Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 3927*7330f729Sjoerg } 3928*7330f729Sjoerg } else { 3929*7330f729Sjoerg // We don't need an initializer, so remove the entry for the delayed 3930*7330f729Sjoerg // initializer position (just in case this entry was delayed) if we 3931*7330f729Sjoerg // also don't need to register a destructor. 3932*7330f729Sjoerg if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 3933*7330f729Sjoerg DelayedCXXInitPosition.erase(D); 3934*7330f729Sjoerg } 3935*7330f729Sjoerg } 3936*7330f729Sjoerg 3937*7330f729Sjoerg llvm::Type* InitType = Init->getType(); 3938*7330f729Sjoerg llvm::Constant *Entry = 3939*7330f729Sjoerg GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 3940*7330f729Sjoerg 3941*7330f729Sjoerg // Strip off pointer casts if we got them. 3942*7330f729Sjoerg Entry = Entry->stripPointerCasts(); 3943*7330f729Sjoerg 3944*7330f729Sjoerg // Entry is now either a Function or GlobalVariable. 3945*7330f729Sjoerg auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 3946*7330f729Sjoerg 3947*7330f729Sjoerg // We have a definition after a declaration with the wrong type. 3948*7330f729Sjoerg // We must make a new GlobalVariable* and update everything that used OldGV 3949*7330f729Sjoerg // (a declaration or tentative definition) with the new GlobalVariable* 3950*7330f729Sjoerg // (which will be a definition). 3951*7330f729Sjoerg // 3952*7330f729Sjoerg // This happens if there is a prototype for a global (e.g. 3953*7330f729Sjoerg // "extern int x[];") and then a definition of a different type (e.g. 3954*7330f729Sjoerg // "int x[10];"). This also happens when an initializer has a different type 3955*7330f729Sjoerg // from the type of the global (this happens with unions). 3956*7330f729Sjoerg if (!GV || GV->getType()->getElementType() != InitType || 3957*7330f729Sjoerg GV->getType()->getAddressSpace() != 3958*7330f729Sjoerg getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 3959*7330f729Sjoerg 3960*7330f729Sjoerg // Move the old entry aside so that we'll create a new one. 3961*7330f729Sjoerg Entry->setName(StringRef()); 3962*7330f729Sjoerg 3963*7330f729Sjoerg // Make a new global with the correct type, this is now guaranteed to work. 3964*7330f729Sjoerg GV = cast<llvm::GlobalVariable>( 3965*7330f729Sjoerg GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)) 3966*7330f729Sjoerg ->stripPointerCasts()); 3967*7330f729Sjoerg 3968*7330f729Sjoerg // Replace all uses of the old global with the new global 3969*7330f729Sjoerg llvm::Constant *NewPtrForOldDecl = 3970*7330f729Sjoerg llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 3971*7330f729Sjoerg Entry->replaceAllUsesWith(NewPtrForOldDecl); 3972*7330f729Sjoerg 3973*7330f729Sjoerg // Erase the old global, since it is no longer used. 3974*7330f729Sjoerg cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 3975*7330f729Sjoerg } 3976*7330f729Sjoerg 3977*7330f729Sjoerg MaybeHandleStaticInExternC(D, GV); 3978*7330f729Sjoerg 3979*7330f729Sjoerg if (D->hasAttr<AnnotateAttr>()) 3980*7330f729Sjoerg AddGlobalAnnotations(D, GV); 3981*7330f729Sjoerg 3982*7330f729Sjoerg // Set the llvm linkage type as appropriate. 3983*7330f729Sjoerg llvm::GlobalValue::LinkageTypes Linkage = 3984*7330f729Sjoerg getLLVMLinkageVarDefinition(D, GV->isConstant()); 3985*7330f729Sjoerg 3986*7330f729Sjoerg // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 3987*7330f729Sjoerg // the device. [...]" 3988*7330f729Sjoerg // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 3989*7330f729Sjoerg // __device__, declares a variable that: [...] 3990*7330f729Sjoerg // Is accessible from all the threads within the grid and from the host 3991*7330f729Sjoerg // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 3992*7330f729Sjoerg // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 3993*7330f729Sjoerg if (GV && LangOpts.CUDA) { 3994*7330f729Sjoerg if (LangOpts.CUDAIsDevice) { 3995*7330f729Sjoerg if (Linkage != llvm::GlobalValue::InternalLinkage && 3996*7330f729Sjoerg (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())) 3997*7330f729Sjoerg GV->setExternallyInitialized(true); 3998*7330f729Sjoerg } else { 3999*7330f729Sjoerg // Host-side shadows of external declarations of device-side 4000*7330f729Sjoerg // global variables become internal definitions. These have to 4001*7330f729Sjoerg // be internal in order to prevent name conflicts with global 4002*7330f729Sjoerg // host variables with the same name in a different TUs. 4003*7330f729Sjoerg if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 4004*7330f729Sjoerg D->hasAttr<HIPPinnedShadowAttr>()) { 4005*7330f729Sjoerg Linkage = llvm::GlobalValue::InternalLinkage; 4006*7330f729Sjoerg 4007*7330f729Sjoerg // Shadow variables and their properties must be registered 4008*7330f729Sjoerg // with CUDA runtime. 4009*7330f729Sjoerg unsigned Flags = 0; 4010*7330f729Sjoerg if (!D->hasDefinition()) 4011*7330f729Sjoerg Flags |= CGCUDARuntime::ExternDeviceVar; 4012*7330f729Sjoerg if (D->hasAttr<CUDAConstantAttr>()) 4013*7330f729Sjoerg Flags |= CGCUDARuntime::ConstantDeviceVar; 4014*7330f729Sjoerg // Extern global variables will be registered in the TU where they are 4015*7330f729Sjoerg // defined. 4016*7330f729Sjoerg if (!D->hasExternalStorage()) 4017*7330f729Sjoerg getCUDARuntime().registerDeviceVar(D, *GV, Flags); 4018*7330f729Sjoerg } else if (D->hasAttr<CUDASharedAttr>()) 4019*7330f729Sjoerg // __shared__ variables are odd. Shadows do get created, but 4020*7330f729Sjoerg // they are not registered with the CUDA runtime, so they 4021*7330f729Sjoerg // can't really be used to access their device-side 4022*7330f729Sjoerg // counterparts. It's not clear yet whether it's nvcc's bug or 4023*7330f729Sjoerg // a feature, but we've got to do the same for compatibility. 4024*7330f729Sjoerg Linkage = llvm::GlobalValue::InternalLinkage; 4025*7330f729Sjoerg } 4026*7330f729Sjoerg } 4027*7330f729Sjoerg 4028*7330f729Sjoerg if (!IsHIPPinnedShadowVar) 4029*7330f729Sjoerg GV->setInitializer(Init); 4030*7330f729Sjoerg if (emitter) emitter->finalize(GV); 4031*7330f729Sjoerg 4032*7330f729Sjoerg // If it is safe to mark the global 'constant', do so now. 4033*7330f729Sjoerg GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 4034*7330f729Sjoerg isTypeConstant(D->getType(), true)); 4035*7330f729Sjoerg 4036*7330f729Sjoerg // If it is in a read-only section, mark it 'constant'. 4037*7330f729Sjoerg if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 4038*7330f729Sjoerg const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 4039*7330f729Sjoerg if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 4040*7330f729Sjoerg GV->setConstant(true); 4041*7330f729Sjoerg } 4042*7330f729Sjoerg 4043*7330f729Sjoerg GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 4044*7330f729Sjoerg 4045*7330f729Sjoerg // On Darwin, if the normal linkage of a C++ thread_local variable is 4046*7330f729Sjoerg // LinkOnce or Weak, we keep the normal linkage to prevent multiple 4047*7330f729Sjoerg // copies within a linkage unit; otherwise, the backing variable has 4048*7330f729Sjoerg // internal linkage and all accesses should just be calls to the 4049*7330f729Sjoerg // Itanium-specified entry point, which has the normal linkage of the 4050*7330f729Sjoerg // variable. This is to preserve the ability to change the implementation 4051*7330f729Sjoerg // behind the scenes. 4052*7330f729Sjoerg if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic && 4053*7330f729Sjoerg Context.getTargetInfo().getTriple().isOSDarwin() && 4054*7330f729Sjoerg !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) && 4055*7330f729Sjoerg !llvm::GlobalVariable::isWeakLinkage(Linkage)) 4056*7330f729Sjoerg Linkage = llvm::GlobalValue::InternalLinkage; 4057*7330f729Sjoerg 4058*7330f729Sjoerg GV->setLinkage(Linkage); 4059*7330f729Sjoerg if (D->hasAttr<DLLImportAttr>()) 4060*7330f729Sjoerg GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 4061*7330f729Sjoerg else if (D->hasAttr<DLLExportAttr>()) 4062*7330f729Sjoerg GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 4063*7330f729Sjoerg else 4064*7330f729Sjoerg GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 4065*7330f729Sjoerg 4066*7330f729Sjoerg if (Linkage == llvm::GlobalVariable::CommonLinkage) { 4067*7330f729Sjoerg // common vars aren't constant even if declared const. 4068*7330f729Sjoerg GV->setConstant(false); 4069*7330f729Sjoerg // Tentative definition of global variables may be initialized with 4070*7330f729Sjoerg // non-zero null pointers. In this case they should have weak linkage 4071*7330f729Sjoerg // since common linkage must have zero initializer and must not have 4072*7330f729Sjoerg // explicit section therefore cannot have non-zero initial value. 4073*7330f729Sjoerg if (!GV->getInitializer()->isNullValue()) 4074*7330f729Sjoerg GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 4075*7330f729Sjoerg } 4076*7330f729Sjoerg 4077*7330f729Sjoerg setNonAliasAttributes(D, GV); 4078*7330f729Sjoerg 4079*7330f729Sjoerg if (D->getTLSKind() && !GV->isThreadLocal()) { 4080*7330f729Sjoerg if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4081*7330f729Sjoerg CXXThreadLocals.push_back(D); 4082*7330f729Sjoerg setTLSMode(GV, *D); 4083*7330f729Sjoerg } 4084*7330f729Sjoerg 4085*7330f729Sjoerg maybeSetTrivialComdat(*D, *GV); 4086*7330f729Sjoerg 4087*7330f729Sjoerg // Emit the initializer function if necessary. 4088*7330f729Sjoerg if (NeedsGlobalCtor || NeedsGlobalDtor) 4089*7330f729Sjoerg EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 4090*7330f729Sjoerg 4091*7330f729Sjoerg SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 4092*7330f729Sjoerg 4093*7330f729Sjoerg // Emit global variable debug information. 4094*7330f729Sjoerg if (CGDebugInfo *DI = getModuleDebugInfo()) 4095*7330f729Sjoerg if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 4096*7330f729Sjoerg DI->EmitGlobalVariable(GV, D); 4097*7330f729Sjoerg } 4098*7330f729Sjoerg 4099*7330f729Sjoerg static bool isVarDeclStrongDefinition(const ASTContext &Context, 4100*7330f729Sjoerg CodeGenModule &CGM, const VarDecl *D, 4101*7330f729Sjoerg bool NoCommon) { 4102*7330f729Sjoerg // Don't give variables common linkage if -fno-common was specified unless it 4103*7330f729Sjoerg // was overridden by a NoCommon attribute. 4104*7330f729Sjoerg if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 4105*7330f729Sjoerg return true; 4106*7330f729Sjoerg 4107*7330f729Sjoerg // C11 6.9.2/2: 4108*7330f729Sjoerg // A declaration of an identifier for an object that has file scope without 4109*7330f729Sjoerg // an initializer, and without a storage-class specifier or with the 4110*7330f729Sjoerg // storage-class specifier static, constitutes a tentative definition. 4111*7330f729Sjoerg if (D->getInit() || D->hasExternalStorage()) 4112*7330f729Sjoerg return true; 4113*7330f729Sjoerg 4114*7330f729Sjoerg // A variable cannot be both common and exist in a section. 4115*7330f729Sjoerg if (D->hasAttr<SectionAttr>()) 4116*7330f729Sjoerg return true; 4117*7330f729Sjoerg 4118*7330f729Sjoerg // A variable cannot be both common and exist in a section. 4119*7330f729Sjoerg // We don't try to determine which is the right section in the front-end. 4120*7330f729Sjoerg // If no specialized section name is applicable, it will resort to default. 4121*7330f729Sjoerg if (D->hasAttr<PragmaClangBSSSectionAttr>() || 4122*7330f729Sjoerg D->hasAttr<PragmaClangDataSectionAttr>() || 4123*7330f729Sjoerg D->hasAttr<PragmaClangRelroSectionAttr>() || 4124*7330f729Sjoerg D->hasAttr<PragmaClangRodataSectionAttr>()) 4125*7330f729Sjoerg return true; 4126*7330f729Sjoerg 4127*7330f729Sjoerg // Thread local vars aren't considered common linkage. 4128*7330f729Sjoerg if (D->getTLSKind()) 4129*7330f729Sjoerg return true; 4130*7330f729Sjoerg 4131*7330f729Sjoerg // Tentative definitions marked with WeakImportAttr are true definitions. 4132*7330f729Sjoerg if (D->hasAttr<WeakImportAttr>()) 4133*7330f729Sjoerg return true; 4134*7330f729Sjoerg 4135*7330f729Sjoerg // A variable cannot be both common and exist in a comdat. 4136*7330f729Sjoerg if (shouldBeInCOMDAT(CGM, *D)) 4137*7330f729Sjoerg return true; 4138*7330f729Sjoerg 4139*7330f729Sjoerg // Declarations with a required alignment do not have common linkage in MSVC 4140*7330f729Sjoerg // mode. 4141*7330f729Sjoerg if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4142*7330f729Sjoerg if (D->hasAttr<AlignedAttr>()) 4143*7330f729Sjoerg return true; 4144*7330f729Sjoerg QualType VarType = D->getType(); 4145*7330f729Sjoerg if (Context.isAlignmentRequired(VarType)) 4146*7330f729Sjoerg return true; 4147*7330f729Sjoerg 4148*7330f729Sjoerg if (const auto *RT = VarType->getAs<RecordType>()) { 4149*7330f729Sjoerg const RecordDecl *RD = RT->getDecl(); 4150*7330f729Sjoerg for (const FieldDecl *FD : RD->fields()) { 4151*7330f729Sjoerg if (FD->isBitField()) 4152*7330f729Sjoerg continue; 4153*7330f729Sjoerg if (FD->hasAttr<AlignedAttr>()) 4154*7330f729Sjoerg return true; 4155*7330f729Sjoerg if (Context.isAlignmentRequired(FD->getType())) 4156*7330f729Sjoerg return true; 4157*7330f729Sjoerg } 4158*7330f729Sjoerg } 4159*7330f729Sjoerg } 4160*7330f729Sjoerg 4161*7330f729Sjoerg // Microsoft's link.exe doesn't support alignments greater than 32 bytes for 4162*7330f729Sjoerg // common symbols, so symbols with greater alignment requirements cannot be 4163*7330f729Sjoerg // common. 4164*7330f729Sjoerg // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two 4165*7330f729Sjoerg // alignments for common symbols via the aligncomm directive, so this 4166*7330f729Sjoerg // restriction only applies to MSVC environments. 4167*7330f729Sjoerg if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && 4168*7330f729Sjoerg Context.getTypeAlignIfKnown(D->getType()) > 4169*7330f729Sjoerg Context.toBits(CharUnits::fromQuantity(32))) 4170*7330f729Sjoerg return true; 4171*7330f729Sjoerg 4172*7330f729Sjoerg return false; 4173*7330f729Sjoerg } 4174*7330f729Sjoerg 4175*7330f729Sjoerg llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 4176*7330f729Sjoerg const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 4177*7330f729Sjoerg if (Linkage == GVA_Internal) 4178*7330f729Sjoerg return llvm::Function::InternalLinkage; 4179*7330f729Sjoerg 4180*7330f729Sjoerg if (D->hasAttr<WeakAttr>()) { 4181*7330f729Sjoerg if (IsConstantVariable) 4182*7330f729Sjoerg return llvm::GlobalVariable::WeakODRLinkage; 4183*7330f729Sjoerg else 4184*7330f729Sjoerg return llvm::GlobalVariable::WeakAnyLinkage; 4185*7330f729Sjoerg } 4186*7330f729Sjoerg 4187*7330f729Sjoerg if (const auto *FD = D->getAsFunction()) 4188*7330f729Sjoerg if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) 4189*7330f729Sjoerg return llvm::GlobalVariable::LinkOnceAnyLinkage; 4190*7330f729Sjoerg 4191*7330f729Sjoerg // We are guaranteed to have a strong definition somewhere else, 4192*7330f729Sjoerg // so we can use available_externally linkage. 4193*7330f729Sjoerg if (Linkage == GVA_AvailableExternally) 4194*7330f729Sjoerg return llvm::GlobalValue::AvailableExternallyLinkage; 4195*7330f729Sjoerg 4196*7330f729Sjoerg // Note that Apple's kernel linker doesn't support symbol 4197*7330f729Sjoerg // coalescing, so we need to avoid linkonce and weak linkages there. 4198*7330f729Sjoerg // Normally, this means we just map to internal, but for explicit 4199*7330f729Sjoerg // instantiations we'll map to external. 4200*7330f729Sjoerg 4201*7330f729Sjoerg // In C++, the compiler has to emit a definition in every translation unit 4202*7330f729Sjoerg // that references the function. We should use linkonce_odr because 4203*7330f729Sjoerg // a) if all references in this translation unit are optimized away, we 4204*7330f729Sjoerg // don't need to codegen it. b) if the function persists, it needs to be 4205*7330f729Sjoerg // merged with other definitions. c) C++ has the ODR, so we know the 4206*7330f729Sjoerg // definition is dependable. 4207*7330f729Sjoerg if (Linkage == GVA_DiscardableODR) 4208*7330f729Sjoerg return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 4209*7330f729Sjoerg : llvm::Function::InternalLinkage; 4210*7330f729Sjoerg 4211*7330f729Sjoerg // An explicit instantiation of a template has weak linkage, since 4212*7330f729Sjoerg // explicit instantiations can occur in multiple translation units 4213*7330f729Sjoerg // and must all be equivalent. However, we are not allowed to 4214*7330f729Sjoerg // throw away these explicit instantiations. 4215*7330f729Sjoerg // 4216*7330f729Sjoerg // We don't currently support CUDA device code spread out across multiple TUs, 4217*7330f729Sjoerg // so say that CUDA templates are either external (for kernels) or internal. 4218*7330f729Sjoerg // This lets llvm perform aggressive inter-procedural optimizations. 4219*7330f729Sjoerg if (Linkage == GVA_StrongODR) { 4220*7330f729Sjoerg if (Context.getLangOpts().AppleKext) 4221*7330f729Sjoerg return llvm::Function::ExternalLinkage; 4222*7330f729Sjoerg if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) 4223*7330f729Sjoerg return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 4224*7330f729Sjoerg : llvm::Function::InternalLinkage; 4225*7330f729Sjoerg return llvm::Function::WeakODRLinkage; 4226*7330f729Sjoerg } 4227*7330f729Sjoerg 4228*7330f729Sjoerg // C++ doesn't have tentative definitions and thus cannot have common 4229*7330f729Sjoerg // linkage. 4230*7330f729Sjoerg if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 4231*7330f729Sjoerg !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 4232*7330f729Sjoerg CodeGenOpts.NoCommon)) 4233*7330f729Sjoerg return llvm::GlobalVariable::CommonLinkage; 4234*7330f729Sjoerg 4235*7330f729Sjoerg // selectany symbols are externally visible, so use weak instead of 4236*7330f729Sjoerg // linkonce. MSVC optimizes away references to const selectany globals, so 4237*7330f729Sjoerg // all definitions should be the same and ODR linkage should be used. 4238*7330f729Sjoerg // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 4239*7330f729Sjoerg if (D->hasAttr<SelectAnyAttr>()) 4240*7330f729Sjoerg return llvm::GlobalVariable::WeakODRLinkage; 4241*7330f729Sjoerg 4242*7330f729Sjoerg // Otherwise, we have strong external linkage. 4243*7330f729Sjoerg assert(Linkage == GVA_StrongExternal); 4244*7330f729Sjoerg return llvm::GlobalVariable::ExternalLinkage; 4245*7330f729Sjoerg } 4246*7330f729Sjoerg 4247*7330f729Sjoerg llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 4248*7330f729Sjoerg const VarDecl *VD, bool IsConstant) { 4249*7330f729Sjoerg GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 4250*7330f729Sjoerg return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 4251*7330f729Sjoerg } 4252*7330f729Sjoerg 4253*7330f729Sjoerg /// Replace the uses of a function that was declared with a non-proto type. 4254*7330f729Sjoerg /// We want to silently drop extra arguments from call sites 4255*7330f729Sjoerg static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 4256*7330f729Sjoerg llvm::Function *newFn) { 4257*7330f729Sjoerg // Fast path. 4258*7330f729Sjoerg if (old->use_empty()) return; 4259*7330f729Sjoerg 4260*7330f729Sjoerg llvm::Type *newRetTy = newFn->getReturnType(); 4261*7330f729Sjoerg SmallVector<llvm::Value*, 4> newArgs; 4262*7330f729Sjoerg SmallVector<llvm::OperandBundleDef, 1> newBundles; 4263*7330f729Sjoerg 4264*7330f729Sjoerg for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 4265*7330f729Sjoerg ui != ue; ) { 4266*7330f729Sjoerg llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 4267*7330f729Sjoerg llvm::User *user = use->getUser(); 4268*7330f729Sjoerg 4269*7330f729Sjoerg // Recognize and replace uses of bitcasts. Most calls to 4270*7330f729Sjoerg // unprototyped functions will use bitcasts. 4271*7330f729Sjoerg if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 4272*7330f729Sjoerg if (bitcast->getOpcode() == llvm::Instruction::BitCast) 4273*7330f729Sjoerg replaceUsesOfNonProtoConstant(bitcast, newFn); 4274*7330f729Sjoerg continue; 4275*7330f729Sjoerg } 4276*7330f729Sjoerg 4277*7330f729Sjoerg // Recognize calls to the function. 4278*7330f729Sjoerg llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user); 4279*7330f729Sjoerg if (!callSite) continue; 4280*7330f729Sjoerg if (!callSite->isCallee(&*use)) 4281*7330f729Sjoerg continue; 4282*7330f729Sjoerg 4283*7330f729Sjoerg // If the return types don't match exactly, then we can't 4284*7330f729Sjoerg // transform this call unless it's dead. 4285*7330f729Sjoerg if (callSite->getType() != newRetTy && !callSite->use_empty()) 4286*7330f729Sjoerg continue; 4287*7330f729Sjoerg 4288*7330f729Sjoerg // Get the call site's attribute list. 4289*7330f729Sjoerg SmallVector<llvm::AttributeSet, 8> newArgAttrs; 4290*7330f729Sjoerg llvm::AttributeList oldAttrs = callSite->getAttributes(); 4291*7330f729Sjoerg 4292*7330f729Sjoerg // If the function was passed too few arguments, don't transform. 4293*7330f729Sjoerg unsigned newNumArgs = newFn->arg_size(); 4294*7330f729Sjoerg if (callSite->arg_size() < newNumArgs) 4295*7330f729Sjoerg continue; 4296*7330f729Sjoerg 4297*7330f729Sjoerg // If extra arguments were passed, we silently drop them. 4298*7330f729Sjoerg // If any of the types mismatch, we don't transform. 4299*7330f729Sjoerg unsigned argNo = 0; 4300*7330f729Sjoerg bool dontTransform = false; 4301*7330f729Sjoerg for (llvm::Argument &A : newFn->args()) { 4302*7330f729Sjoerg if (callSite->getArgOperand(argNo)->getType() != A.getType()) { 4303*7330f729Sjoerg dontTransform = true; 4304*7330f729Sjoerg break; 4305*7330f729Sjoerg } 4306*7330f729Sjoerg 4307*7330f729Sjoerg // Add any parameter attributes. 4308*7330f729Sjoerg newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo)); 4309*7330f729Sjoerg argNo++; 4310*7330f729Sjoerg } 4311*7330f729Sjoerg if (dontTransform) 4312*7330f729Sjoerg continue; 4313*7330f729Sjoerg 4314*7330f729Sjoerg // Okay, we can transform this. Create the new call instruction and copy 4315*7330f729Sjoerg // over the required information. 4316*7330f729Sjoerg newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo); 4317*7330f729Sjoerg 4318*7330f729Sjoerg // Copy over any operand bundles. 4319*7330f729Sjoerg callSite->getOperandBundlesAsDefs(newBundles); 4320*7330f729Sjoerg 4321*7330f729Sjoerg llvm::CallBase *newCall; 4322*7330f729Sjoerg if (dyn_cast<llvm::CallInst>(callSite)) { 4323*7330f729Sjoerg newCall = 4324*7330f729Sjoerg llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite); 4325*7330f729Sjoerg } else { 4326*7330f729Sjoerg auto *oldInvoke = cast<llvm::InvokeInst>(callSite); 4327*7330f729Sjoerg newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(), 4328*7330f729Sjoerg oldInvoke->getUnwindDest(), newArgs, 4329*7330f729Sjoerg newBundles, "", callSite); 4330*7330f729Sjoerg } 4331*7330f729Sjoerg newArgs.clear(); // for the next iteration 4332*7330f729Sjoerg 4333*7330f729Sjoerg if (!newCall->getType()->isVoidTy()) 4334*7330f729Sjoerg newCall->takeName(callSite); 4335*7330f729Sjoerg newCall->setAttributes(llvm::AttributeList::get( 4336*7330f729Sjoerg newFn->getContext(), oldAttrs.getFnAttributes(), 4337*7330f729Sjoerg oldAttrs.getRetAttributes(), newArgAttrs)); 4338*7330f729Sjoerg newCall->setCallingConv(callSite->getCallingConv()); 4339*7330f729Sjoerg 4340*7330f729Sjoerg // Finally, remove the old call, replacing any uses with the new one. 4341*7330f729Sjoerg if (!callSite->use_empty()) 4342*7330f729Sjoerg callSite->replaceAllUsesWith(newCall); 4343*7330f729Sjoerg 4344*7330f729Sjoerg // Copy debug location attached to CI. 4345*7330f729Sjoerg if (callSite->getDebugLoc()) 4346*7330f729Sjoerg newCall->setDebugLoc(callSite->getDebugLoc()); 4347*7330f729Sjoerg 4348*7330f729Sjoerg callSite->eraseFromParent(); 4349*7330f729Sjoerg } 4350*7330f729Sjoerg } 4351*7330f729Sjoerg 4352*7330f729Sjoerg /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 4353*7330f729Sjoerg /// implement a function with no prototype, e.g. "int foo() {}". If there are 4354*7330f729Sjoerg /// existing call uses of the old function in the module, this adjusts them to 4355*7330f729Sjoerg /// call the new function directly. 4356*7330f729Sjoerg /// 4357*7330f729Sjoerg /// This is not just a cleanup: the always_inline pass requires direct calls to 4358*7330f729Sjoerg /// functions to be able to inline them. If there is a bitcast in the way, it 4359*7330f729Sjoerg /// won't inline them. Instcombine normally deletes these calls, but it isn't 4360*7330f729Sjoerg /// run at -O0. 4361*7330f729Sjoerg static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 4362*7330f729Sjoerg llvm::Function *NewFn) { 4363*7330f729Sjoerg // If we're redefining a global as a function, don't transform it. 4364*7330f729Sjoerg if (!isa<llvm::Function>(Old)) return; 4365*7330f729Sjoerg 4366*7330f729Sjoerg replaceUsesOfNonProtoConstant(Old, NewFn); 4367*7330f729Sjoerg } 4368*7330f729Sjoerg 4369*7330f729Sjoerg void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 4370*7330f729Sjoerg auto DK = VD->isThisDeclarationADefinition(); 4371*7330f729Sjoerg if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 4372*7330f729Sjoerg return; 4373*7330f729Sjoerg 4374*7330f729Sjoerg TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 4375*7330f729Sjoerg // If we have a definition, this might be a deferred decl. If the 4376*7330f729Sjoerg // instantiation is explicit, make sure we emit it at the end. 4377*7330f729Sjoerg if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 4378*7330f729Sjoerg GetAddrOfGlobalVar(VD); 4379*7330f729Sjoerg 4380*7330f729Sjoerg EmitTopLevelDecl(VD); 4381*7330f729Sjoerg } 4382*7330f729Sjoerg 4383*7330f729Sjoerg void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 4384*7330f729Sjoerg llvm::GlobalValue *GV) { 4385*7330f729Sjoerg // Check if this must be emitted as declare variant. 4386*7330f729Sjoerg if (LangOpts.OpenMP && OpenMPRuntime && 4387*7330f729Sjoerg OpenMPRuntime->emitDeclareVariant(GD, /*IsForDefinition=*/true)) 4388*7330f729Sjoerg return; 4389*7330f729Sjoerg 4390*7330f729Sjoerg const auto *D = cast<FunctionDecl>(GD.getDecl()); 4391*7330f729Sjoerg 4392*7330f729Sjoerg // Compute the function info and LLVM type. 4393*7330f729Sjoerg const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4394*7330f729Sjoerg llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 4395*7330f729Sjoerg 4396*7330f729Sjoerg // Get or create the prototype for the function. 4397*7330f729Sjoerg if (!GV || (GV->getType()->getElementType() != Ty)) 4398*7330f729Sjoerg GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 4399*7330f729Sjoerg /*DontDefer=*/true, 4400*7330f729Sjoerg ForDefinition)); 4401*7330f729Sjoerg 4402*7330f729Sjoerg // Already emitted. 4403*7330f729Sjoerg if (!GV->isDeclaration()) 4404*7330f729Sjoerg return; 4405*7330f729Sjoerg 4406*7330f729Sjoerg // We need to set linkage and visibility on the function before 4407*7330f729Sjoerg // generating code for it because various parts of IR generation 4408*7330f729Sjoerg // want to propagate this information down (e.g. to local static 4409*7330f729Sjoerg // declarations). 4410*7330f729Sjoerg auto *Fn = cast<llvm::Function>(GV); 4411*7330f729Sjoerg setFunctionLinkage(GD, Fn); 4412*7330f729Sjoerg 4413*7330f729Sjoerg // FIXME: this is redundant with part of setFunctionDefinitionAttributes 4414*7330f729Sjoerg setGVProperties(Fn, GD); 4415*7330f729Sjoerg 4416*7330f729Sjoerg MaybeHandleStaticInExternC(D, Fn); 4417*7330f729Sjoerg 4418*7330f729Sjoerg 4419*7330f729Sjoerg maybeSetTrivialComdat(*D, *Fn); 4420*7330f729Sjoerg 4421*7330f729Sjoerg CodeGenFunction(*this).GenerateCode(D, Fn, FI); 4422*7330f729Sjoerg 4423*7330f729Sjoerg setNonAliasAttributes(GD, Fn); 4424*7330f729Sjoerg SetLLVMFunctionAttributesForDefinition(D, Fn); 4425*7330f729Sjoerg 4426*7330f729Sjoerg if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 4427*7330f729Sjoerg AddGlobalCtor(Fn, CA->getPriority()); 4428*7330f729Sjoerg if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 4429*7330f729Sjoerg AddGlobalDtor(Fn, DA->getPriority()); 4430*7330f729Sjoerg if (D->hasAttr<AnnotateAttr>()) 4431*7330f729Sjoerg AddGlobalAnnotations(D, Fn); 4432*7330f729Sjoerg } 4433*7330f729Sjoerg 4434*7330f729Sjoerg void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 4435*7330f729Sjoerg const auto *D = cast<ValueDecl>(GD.getDecl()); 4436*7330f729Sjoerg const AliasAttr *AA = D->getAttr<AliasAttr>(); 4437*7330f729Sjoerg assert(AA && "Not an alias?"); 4438*7330f729Sjoerg 4439*7330f729Sjoerg StringRef MangledName = getMangledName(GD); 4440*7330f729Sjoerg 4441*7330f729Sjoerg if (AA->getAliasee() == MangledName) { 4442*7330f729Sjoerg Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 4443*7330f729Sjoerg return; 4444*7330f729Sjoerg } 4445*7330f729Sjoerg 4446*7330f729Sjoerg // If there is a definition in the module, then it wins over the alias. 4447*7330f729Sjoerg // This is dubious, but allow it to be safe. Just ignore the alias. 4448*7330f729Sjoerg llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4449*7330f729Sjoerg if (Entry && !Entry->isDeclaration()) 4450*7330f729Sjoerg return; 4451*7330f729Sjoerg 4452*7330f729Sjoerg Aliases.push_back(GD); 4453*7330f729Sjoerg 4454*7330f729Sjoerg llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 4455*7330f729Sjoerg 4456*7330f729Sjoerg // Create a reference to the named value. This ensures that it is emitted 4457*7330f729Sjoerg // if a deferred decl. 4458*7330f729Sjoerg llvm::Constant *Aliasee; 4459*7330f729Sjoerg llvm::GlobalValue::LinkageTypes LT; 4460*7330f729Sjoerg if (isa<llvm::FunctionType>(DeclTy)) { 4461*7330f729Sjoerg Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 4462*7330f729Sjoerg /*ForVTable=*/false); 4463*7330f729Sjoerg LT = getFunctionLinkage(GD); 4464*7330f729Sjoerg } else { 4465*7330f729Sjoerg Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 4466*7330f729Sjoerg llvm::PointerType::getUnqual(DeclTy), 4467*7330f729Sjoerg /*D=*/nullptr); 4468*7330f729Sjoerg LT = getLLVMLinkageVarDefinition(cast<VarDecl>(GD.getDecl()), 4469*7330f729Sjoerg D->getType().isConstQualified()); 4470*7330f729Sjoerg } 4471*7330f729Sjoerg 4472*7330f729Sjoerg // Create the new alias itself, but don't set a name yet. 4473*7330f729Sjoerg auto *GA = 4474*7330f729Sjoerg llvm::GlobalAlias::create(DeclTy, 0, LT, "", Aliasee, &getModule()); 4475*7330f729Sjoerg 4476*7330f729Sjoerg if (Entry) { 4477*7330f729Sjoerg if (GA->getAliasee() == Entry) { 4478*7330f729Sjoerg Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 4479*7330f729Sjoerg return; 4480*7330f729Sjoerg } 4481*7330f729Sjoerg 4482*7330f729Sjoerg assert(Entry->isDeclaration()); 4483*7330f729Sjoerg 4484*7330f729Sjoerg // If there is a declaration in the module, then we had an extern followed 4485*7330f729Sjoerg // by the alias, as in: 4486*7330f729Sjoerg // extern int test6(); 4487*7330f729Sjoerg // ... 4488*7330f729Sjoerg // int test6() __attribute__((alias("test7"))); 4489*7330f729Sjoerg // 4490*7330f729Sjoerg // Remove it and replace uses of it with the alias. 4491*7330f729Sjoerg GA->takeName(Entry); 4492*7330f729Sjoerg 4493*7330f729Sjoerg Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 4494*7330f729Sjoerg Entry->getType())); 4495*7330f729Sjoerg Entry->eraseFromParent(); 4496*7330f729Sjoerg } else { 4497*7330f729Sjoerg GA->setName(MangledName); 4498*7330f729Sjoerg } 4499*7330f729Sjoerg 4500*7330f729Sjoerg // Set attributes which are particular to an alias; this is a 4501*7330f729Sjoerg // specialization of the attributes which may be set on a global 4502*7330f729Sjoerg // variable/function. 4503*7330f729Sjoerg if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 4504*7330f729Sjoerg D->isWeakImported()) { 4505*7330f729Sjoerg GA->setLinkage(llvm::Function::WeakAnyLinkage); 4506*7330f729Sjoerg } 4507*7330f729Sjoerg 4508*7330f729Sjoerg if (const auto *VD = dyn_cast<VarDecl>(D)) 4509*7330f729Sjoerg if (VD->getTLSKind()) 4510*7330f729Sjoerg setTLSMode(GA, *VD); 4511*7330f729Sjoerg 4512*7330f729Sjoerg SetCommonAttributes(GD, GA); 4513*7330f729Sjoerg } 4514*7330f729Sjoerg 4515*7330f729Sjoerg void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 4516*7330f729Sjoerg const auto *D = cast<ValueDecl>(GD.getDecl()); 4517*7330f729Sjoerg const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 4518*7330f729Sjoerg assert(IFA && "Not an ifunc?"); 4519*7330f729Sjoerg 4520*7330f729Sjoerg StringRef MangledName = getMangledName(GD); 4521*7330f729Sjoerg 4522*7330f729Sjoerg if (IFA->getResolver() == MangledName) { 4523*7330f729Sjoerg Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 4524*7330f729Sjoerg return; 4525*7330f729Sjoerg } 4526*7330f729Sjoerg 4527*7330f729Sjoerg // Report an error if some definition overrides ifunc. 4528*7330f729Sjoerg llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4529*7330f729Sjoerg if (Entry && !Entry->isDeclaration()) { 4530*7330f729Sjoerg GlobalDecl OtherGD; 4531*7330f729Sjoerg if (lookupRepresentativeDecl(MangledName, OtherGD) && 4532*7330f729Sjoerg DiagnosedConflictingDefinitions.insert(GD).second) { 4533*7330f729Sjoerg Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) 4534*7330f729Sjoerg << MangledName; 4535*7330f729Sjoerg Diags.Report(OtherGD.getDecl()->getLocation(), 4536*7330f729Sjoerg diag::note_previous_definition); 4537*7330f729Sjoerg } 4538*7330f729Sjoerg return; 4539*7330f729Sjoerg } 4540*7330f729Sjoerg 4541*7330f729Sjoerg Aliases.push_back(GD); 4542*7330f729Sjoerg 4543*7330f729Sjoerg llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 4544*7330f729Sjoerg llvm::Constant *Resolver = 4545*7330f729Sjoerg GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD, 4546*7330f729Sjoerg /*ForVTable=*/false); 4547*7330f729Sjoerg llvm::GlobalIFunc *GIF = 4548*7330f729Sjoerg llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 4549*7330f729Sjoerg "", Resolver, &getModule()); 4550*7330f729Sjoerg if (Entry) { 4551*7330f729Sjoerg if (GIF->getResolver() == Entry) { 4552*7330f729Sjoerg Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 4553*7330f729Sjoerg return; 4554*7330f729Sjoerg } 4555*7330f729Sjoerg assert(Entry->isDeclaration()); 4556*7330f729Sjoerg 4557*7330f729Sjoerg // If there is a declaration in the module, then we had an extern followed 4558*7330f729Sjoerg // by the ifunc, as in: 4559*7330f729Sjoerg // extern int test(); 4560*7330f729Sjoerg // ... 4561*7330f729Sjoerg // int test() __attribute__((ifunc("resolver"))); 4562*7330f729Sjoerg // 4563*7330f729Sjoerg // Remove it and replace uses of it with the ifunc. 4564*7330f729Sjoerg GIF->takeName(Entry); 4565*7330f729Sjoerg 4566*7330f729Sjoerg Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 4567*7330f729Sjoerg Entry->getType())); 4568*7330f729Sjoerg Entry->eraseFromParent(); 4569*7330f729Sjoerg } else 4570*7330f729Sjoerg GIF->setName(MangledName); 4571*7330f729Sjoerg 4572*7330f729Sjoerg SetCommonAttributes(GD, GIF); 4573*7330f729Sjoerg } 4574*7330f729Sjoerg 4575*7330f729Sjoerg llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 4576*7330f729Sjoerg ArrayRef<llvm::Type*> Tys) { 4577*7330f729Sjoerg return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 4578*7330f729Sjoerg Tys); 4579*7330f729Sjoerg } 4580*7330f729Sjoerg 4581*7330f729Sjoerg static llvm::StringMapEntry<llvm::GlobalVariable *> & 4582*7330f729Sjoerg GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 4583*7330f729Sjoerg const StringLiteral *Literal, bool TargetIsLSB, 4584*7330f729Sjoerg bool &IsUTF16, unsigned &StringLength) { 4585*7330f729Sjoerg StringRef String = Literal->getString(); 4586*7330f729Sjoerg unsigned NumBytes = String.size(); 4587*7330f729Sjoerg 4588*7330f729Sjoerg // Check for simple case. 4589*7330f729Sjoerg if (!Literal->containsNonAsciiOrNull()) { 4590*7330f729Sjoerg StringLength = NumBytes; 4591*7330f729Sjoerg return *Map.insert(std::make_pair(String, nullptr)).first; 4592*7330f729Sjoerg } 4593*7330f729Sjoerg 4594*7330f729Sjoerg // Otherwise, convert the UTF8 literals into a string of shorts. 4595*7330f729Sjoerg IsUTF16 = true; 4596*7330f729Sjoerg 4597*7330f729Sjoerg SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 4598*7330f729Sjoerg const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 4599*7330f729Sjoerg llvm::UTF16 *ToPtr = &ToBuf[0]; 4600*7330f729Sjoerg 4601*7330f729Sjoerg (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 4602*7330f729Sjoerg ToPtr + NumBytes, llvm::strictConversion); 4603*7330f729Sjoerg 4604*7330f729Sjoerg // ConvertUTF8toUTF16 returns the length in ToPtr. 4605*7330f729Sjoerg StringLength = ToPtr - &ToBuf[0]; 4606*7330f729Sjoerg 4607*7330f729Sjoerg // Add an explicit null. 4608*7330f729Sjoerg *ToPtr = 0; 4609*7330f729Sjoerg return *Map.insert(std::make_pair( 4610*7330f729Sjoerg StringRef(reinterpret_cast<const char *>(ToBuf.data()), 4611*7330f729Sjoerg (StringLength + 1) * 2), 4612*7330f729Sjoerg nullptr)).first; 4613*7330f729Sjoerg } 4614*7330f729Sjoerg 4615*7330f729Sjoerg ConstantAddress 4616*7330f729Sjoerg CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 4617*7330f729Sjoerg unsigned StringLength = 0; 4618*7330f729Sjoerg bool isUTF16 = false; 4619*7330f729Sjoerg llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 4620*7330f729Sjoerg GetConstantCFStringEntry(CFConstantStringMap, Literal, 4621*7330f729Sjoerg getDataLayout().isLittleEndian(), isUTF16, 4622*7330f729Sjoerg StringLength); 4623*7330f729Sjoerg 4624*7330f729Sjoerg if (auto *C = Entry.second) 4625*7330f729Sjoerg return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 4626*7330f729Sjoerg 4627*7330f729Sjoerg llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 4628*7330f729Sjoerg llvm::Constant *Zeros[] = { Zero, Zero }; 4629*7330f729Sjoerg 4630*7330f729Sjoerg const ASTContext &Context = getContext(); 4631*7330f729Sjoerg const llvm::Triple &Triple = getTriple(); 4632*7330f729Sjoerg 4633*7330f729Sjoerg const auto CFRuntime = getLangOpts().CFRuntime; 4634*7330f729Sjoerg const bool IsSwiftABI = 4635*7330f729Sjoerg static_cast<unsigned>(CFRuntime) >= 4636*7330f729Sjoerg static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); 4637*7330f729Sjoerg const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; 4638*7330f729Sjoerg 4639*7330f729Sjoerg // If we don't already have it, get __CFConstantStringClassReference. 4640*7330f729Sjoerg if (!CFConstantStringClassRef) { 4641*7330f729Sjoerg const char *CFConstantStringClassName = "__CFConstantStringClassReference"; 4642*7330f729Sjoerg llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 4643*7330f729Sjoerg Ty = llvm::ArrayType::get(Ty, 0); 4644*7330f729Sjoerg 4645*7330f729Sjoerg switch (CFRuntime) { 4646*7330f729Sjoerg default: break; 4647*7330f729Sjoerg case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH; 4648*7330f729Sjoerg case LangOptions::CoreFoundationABI::Swift5_0: 4649*7330f729Sjoerg CFConstantStringClassName = 4650*7330f729Sjoerg Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" 4651*7330f729Sjoerg : "$s10Foundation19_NSCFConstantStringCN"; 4652*7330f729Sjoerg Ty = IntPtrTy; 4653*7330f729Sjoerg break; 4654*7330f729Sjoerg case LangOptions::CoreFoundationABI::Swift4_2: 4655*7330f729Sjoerg CFConstantStringClassName = 4656*7330f729Sjoerg Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" 4657*7330f729Sjoerg : "$S10Foundation19_NSCFConstantStringCN"; 4658*7330f729Sjoerg Ty = IntPtrTy; 4659*7330f729Sjoerg break; 4660*7330f729Sjoerg case LangOptions::CoreFoundationABI::Swift4_1: 4661*7330f729Sjoerg CFConstantStringClassName = 4662*7330f729Sjoerg Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" 4663*7330f729Sjoerg : "__T010Foundation19_NSCFConstantStringCN"; 4664*7330f729Sjoerg Ty = IntPtrTy; 4665*7330f729Sjoerg break; 4666*7330f729Sjoerg } 4667*7330f729Sjoerg 4668*7330f729Sjoerg llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); 4669*7330f729Sjoerg 4670*7330f729Sjoerg if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { 4671*7330f729Sjoerg llvm::GlobalValue *GV = nullptr; 4672*7330f729Sjoerg 4673*7330f729Sjoerg if ((GV = dyn_cast<llvm::GlobalValue>(C))) { 4674*7330f729Sjoerg IdentifierInfo &II = Context.Idents.get(GV->getName()); 4675*7330f729Sjoerg TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); 4676*7330f729Sjoerg DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 4677*7330f729Sjoerg 4678*7330f729Sjoerg const VarDecl *VD = nullptr; 4679*7330f729Sjoerg for (const auto &Result : DC->lookup(&II)) 4680*7330f729Sjoerg if ((VD = dyn_cast<VarDecl>(Result))) 4681*7330f729Sjoerg break; 4682*7330f729Sjoerg 4683*7330f729Sjoerg if (Triple.isOSBinFormatELF()) { 4684*7330f729Sjoerg if (!VD) 4685*7330f729Sjoerg GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 4686*7330f729Sjoerg } else { 4687*7330f729Sjoerg GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 4688*7330f729Sjoerg if (!VD || !VD->hasAttr<DLLExportAttr>()) 4689*7330f729Sjoerg GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 4690*7330f729Sjoerg else 4691*7330f729Sjoerg GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 4692*7330f729Sjoerg } 4693*7330f729Sjoerg 4694*7330f729Sjoerg setDSOLocal(GV); 4695*7330f729Sjoerg } 4696*7330f729Sjoerg } 4697*7330f729Sjoerg 4698*7330f729Sjoerg // Decay array -> ptr 4699*7330f729Sjoerg CFConstantStringClassRef = 4700*7330f729Sjoerg IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) 4701*7330f729Sjoerg : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); 4702*7330f729Sjoerg } 4703*7330f729Sjoerg 4704*7330f729Sjoerg QualType CFTy = Context.getCFConstantStringType(); 4705*7330f729Sjoerg 4706*7330f729Sjoerg auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 4707*7330f729Sjoerg 4708*7330f729Sjoerg ConstantInitBuilder Builder(*this); 4709*7330f729Sjoerg auto Fields = Builder.beginStruct(STy); 4710*7330f729Sjoerg 4711*7330f729Sjoerg // Class pointer. 4712*7330f729Sjoerg Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef)); 4713*7330f729Sjoerg 4714*7330f729Sjoerg // Flags. 4715*7330f729Sjoerg if (IsSwiftABI) { 4716*7330f729Sjoerg Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); 4717*7330f729Sjoerg Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); 4718*7330f729Sjoerg } else { 4719*7330f729Sjoerg Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 4720*7330f729Sjoerg } 4721*7330f729Sjoerg 4722*7330f729Sjoerg // String pointer. 4723*7330f729Sjoerg llvm::Constant *C = nullptr; 4724*7330f729Sjoerg if (isUTF16) { 4725*7330f729Sjoerg auto Arr = llvm::makeArrayRef( 4726*7330f729Sjoerg reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 4727*7330f729Sjoerg Entry.first().size() / 2); 4728*7330f729Sjoerg C = llvm::ConstantDataArray::get(VMContext, Arr); 4729*7330f729Sjoerg } else { 4730*7330f729Sjoerg C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 4731*7330f729Sjoerg } 4732*7330f729Sjoerg 4733*7330f729Sjoerg // Note: -fwritable-strings doesn't make the backing store strings of 4734*7330f729Sjoerg // CFStrings writable. (See <rdar://problem/10657500>) 4735*7330f729Sjoerg auto *GV = 4736*7330f729Sjoerg new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 4737*7330f729Sjoerg llvm::GlobalValue::PrivateLinkage, C, ".str"); 4738*7330f729Sjoerg GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 4739*7330f729Sjoerg // Don't enforce the target's minimum global alignment, since the only use 4740*7330f729Sjoerg // of the string is via this class initializer. 4741*7330f729Sjoerg CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) 4742*7330f729Sjoerg : Context.getTypeAlignInChars(Context.CharTy); 4743*7330f729Sjoerg GV->setAlignment(Align.getAsAlign()); 4744*7330f729Sjoerg 4745*7330f729Sjoerg // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 4746*7330f729Sjoerg // Without it LLVM can merge the string with a non unnamed_addr one during 4747*7330f729Sjoerg // LTO. Doing that changes the section it ends in, which surprises ld64. 4748*7330f729Sjoerg if (Triple.isOSBinFormatMachO()) 4749*7330f729Sjoerg GV->setSection(isUTF16 ? "__TEXT,__ustring" 4750*7330f729Sjoerg : "__TEXT,__cstring,cstring_literals"); 4751*7330f729Sjoerg // Make sure the literal ends up in .rodata to allow for safe ICF and for 4752*7330f729Sjoerg // the static linker to adjust permissions to read-only later on. 4753*7330f729Sjoerg else if (Triple.isOSBinFormatELF()) 4754*7330f729Sjoerg GV->setSection(".rodata"); 4755*7330f729Sjoerg 4756*7330f729Sjoerg // String. 4757*7330f729Sjoerg llvm::Constant *Str = 4758*7330f729Sjoerg llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 4759*7330f729Sjoerg 4760*7330f729Sjoerg if (isUTF16) 4761*7330f729Sjoerg // Cast the UTF16 string to the correct type. 4762*7330f729Sjoerg Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 4763*7330f729Sjoerg Fields.add(Str); 4764*7330f729Sjoerg 4765*7330f729Sjoerg // String length. 4766*7330f729Sjoerg llvm::IntegerType *LengthTy = 4767*7330f729Sjoerg llvm::IntegerType::get(getModule().getContext(), 4768*7330f729Sjoerg Context.getTargetInfo().getLongWidth()); 4769*7330f729Sjoerg if (IsSwiftABI) { 4770*7330f729Sjoerg if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 4771*7330f729Sjoerg CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 4772*7330f729Sjoerg LengthTy = Int32Ty; 4773*7330f729Sjoerg else 4774*7330f729Sjoerg LengthTy = IntPtrTy; 4775*7330f729Sjoerg } 4776*7330f729Sjoerg Fields.addInt(LengthTy, StringLength); 4777*7330f729Sjoerg 4778*7330f729Sjoerg // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is 4779*7330f729Sjoerg // properly aligned on 32-bit platforms. 4780*7330f729Sjoerg CharUnits Alignment = 4781*7330f729Sjoerg IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign(); 4782*7330f729Sjoerg 4783*7330f729Sjoerg // The struct. 4784*7330f729Sjoerg GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 4785*7330f729Sjoerg /*isConstant=*/false, 4786*7330f729Sjoerg llvm::GlobalVariable::PrivateLinkage); 4787*7330f729Sjoerg GV->addAttribute("objc_arc_inert"); 4788*7330f729Sjoerg switch (Triple.getObjectFormat()) { 4789*7330f729Sjoerg case llvm::Triple::UnknownObjectFormat: 4790*7330f729Sjoerg llvm_unreachable("unknown file format"); 4791*7330f729Sjoerg case llvm::Triple::XCOFF: 4792*7330f729Sjoerg llvm_unreachable("XCOFF is not yet implemented"); 4793*7330f729Sjoerg case llvm::Triple::COFF: 4794*7330f729Sjoerg case llvm::Triple::ELF: 4795*7330f729Sjoerg case llvm::Triple::Wasm: 4796*7330f729Sjoerg GV->setSection("cfstring"); 4797*7330f729Sjoerg break; 4798*7330f729Sjoerg case llvm::Triple::MachO: 4799*7330f729Sjoerg GV->setSection("__DATA,__cfstring"); 4800*7330f729Sjoerg break; 4801*7330f729Sjoerg } 4802*7330f729Sjoerg Entry.second = GV; 4803*7330f729Sjoerg 4804*7330f729Sjoerg return ConstantAddress(GV, Alignment); 4805*7330f729Sjoerg } 4806*7330f729Sjoerg 4807*7330f729Sjoerg bool CodeGenModule::getExpressionLocationsEnabled() const { 4808*7330f729Sjoerg return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 4809*7330f729Sjoerg } 4810*7330f729Sjoerg 4811*7330f729Sjoerg QualType CodeGenModule::getObjCFastEnumerationStateType() { 4812*7330f729Sjoerg if (ObjCFastEnumerationStateType.isNull()) { 4813*7330f729Sjoerg RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 4814*7330f729Sjoerg D->startDefinition(); 4815*7330f729Sjoerg 4816*7330f729Sjoerg QualType FieldTypes[] = { 4817*7330f729Sjoerg Context.UnsignedLongTy, 4818*7330f729Sjoerg Context.getPointerType(Context.getObjCIdType()), 4819*7330f729Sjoerg Context.getPointerType(Context.UnsignedLongTy), 4820*7330f729Sjoerg Context.getConstantArrayType(Context.UnsignedLongTy, 4821*7330f729Sjoerg llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0) 4822*7330f729Sjoerg }; 4823*7330f729Sjoerg 4824*7330f729Sjoerg for (size_t i = 0; i < 4; ++i) { 4825*7330f729Sjoerg FieldDecl *Field = FieldDecl::Create(Context, 4826*7330f729Sjoerg D, 4827*7330f729Sjoerg SourceLocation(), 4828*7330f729Sjoerg SourceLocation(), nullptr, 4829*7330f729Sjoerg FieldTypes[i], /*TInfo=*/nullptr, 4830*7330f729Sjoerg /*BitWidth=*/nullptr, 4831*7330f729Sjoerg /*Mutable=*/false, 4832*7330f729Sjoerg ICIS_NoInit); 4833*7330f729Sjoerg Field->setAccess(AS_public); 4834*7330f729Sjoerg D->addDecl(Field); 4835*7330f729Sjoerg } 4836*7330f729Sjoerg 4837*7330f729Sjoerg D->completeDefinition(); 4838*7330f729Sjoerg ObjCFastEnumerationStateType = Context.getTagDeclType(D); 4839*7330f729Sjoerg } 4840*7330f729Sjoerg 4841*7330f729Sjoerg return ObjCFastEnumerationStateType; 4842*7330f729Sjoerg } 4843*7330f729Sjoerg 4844*7330f729Sjoerg llvm::Constant * 4845*7330f729Sjoerg CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 4846*7330f729Sjoerg assert(!E->getType()->isPointerType() && "Strings are always arrays"); 4847*7330f729Sjoerg 4848*7330f729Sjoerg // Don't emit it as the address of the string, emit the string data itself 4849*7330f729Sjoerg // as an inline array. 4850*7330f729Sjoerg if (E->getCharByteWidth() == 1) { 4851*7330f729Sjoerg SmallString<64> Str(E->getString()); 4852*7330f729Sjoerg 4853*7330f729Sjoerg // Resize the string to the right size, which is indicated by its type. 4854*7330f729Sjoerg const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 4855*7330f729Sjoerg Str.resize(CAT->getSize().getZExtValue()); 4856*7330f729Sjoerg return llvm::ConstantDataArray::getString(VMContext, Str, false); 4857*7330f729Sjoerg } 4858*7330f729Sjoerg 4859*7330f729Sjoerg auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 4860*7330f729Sjoerg llvm::Type *ElemTy = AType->getElementType(); 4861*7330f729Sjoerg unsigned NumElements = AType->getNumElements(); 4862*7330f729Sjoerg 4863*7330f729Sjoerg // Wide strings have either 2-byte or 4-byte elements. 4864*7330f729Sjoerg if (ElemTy->getPrimitiveSizeInBits() == 16) { 4865*7330f729Sjoerg SmallVector<uint16_t, 32> Elements; 4866*7330f729Sjoerg Elements.reserve(NumElements); 4867*7330f729Sjoerg 4868*7330f729Sjoerg for(unsigned i = 0, e = E->getLength(); i != e; ++i) 4869*7330f729Sjoerg Elements.push_back(E->getCodeUnit(i)); 4870*7330f729Sjoerg Elements.resize(NumElements); 4871*7330f729Sjoerg return llvm::ConstantDataArray::get(VMContext, Elements); 4872*7330f729Sjoerg } 4873*7330f729Sjoerg 4874*7330f729Sjoerg assert(ElemTy->getPrimitiveSizeInBits() == 32); 4875*7330f729Sjoerg SmallVector<uint32_t, 32> Elements; 4876*7330f729Sjoerg Elements.reserve(NumElements); 4877*7330f729Sjoerg 4878*7330f729Sjoerg for(unsigned i = 0, e = E->getLength(); i != e; ++i) 4879*7330f729Sjoerg Elements.push_back(E->getCodeUnit(i)); 4880*7330f729Sjoerg Elements.resize(NumElements); 4881*7330f729Sjoerg return llvm::ConstantDataArray::get(VMContext, Elements); 4882*7330f729Sjoerg } 4883*7330f729Sjoerg 4884*7330f729Sjoerg static llvm::GlobalVariable * 4885*7330f729Sjoerg GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 4886*7330f729Sjoerg CodeGenModule &CGM, StringRef GlobalName, 4887*7330f729Sjoerg CharUnits Alignment) { 4888*7330f729Sjoerg unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( 4889*7330f729Sjoerg CGM.getStringLiteralAddressSpace()); 4890*7330f729Sjoerg 4891*7330f729Sjoerg llvm::Module &M = CGM.getModule(); 4892*7330f729Sjoerg // Create a global variable for this string 4893*7330f729Sjoerg auto *GV = new llvm::GlobalVariable( 4894*7330f729Sjoerg M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 4895*7330f729Sjoerg nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 4896*7330f729Sjoerg GV->setAlignment(Alignment.getAsAlign()); 4897*7330f729Sjoerg GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 4898*7330f729Sjoerg if (GV->isWeakForLinker()) { 4899*7330f729Sjoerg assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 4900*7330f729Sjoerg GV->setComdat(M.getOrInsertComdat(GV->getName())); 4901*7330f729Sjoerg } 4902*7330f729Sjoerg CGM.setDSOLocal(GV); 4903*7330f729Sjoerg 4904*7330f729Sjoerg return GV; 4905*7330f729Sjoerg } 4906*7330f729Sjoerg 4907*7330f729Sjoerg /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 4908*7330f729Sjoerg /// constant array for the given string literal. 4909*7330f729Sjoerg ConstantAddress 4910*7330f729Sjoerg CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 4911*7330f729Sjoerg StringRef Name) { 4912*7330f729Sjoerg CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 4913*7330f729Sjoerg 4914*7330f729Sjoerg llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 4915*7330f729Sjoerg llvm::GlobalVariable **Entry = nullptr; 4916*7330f729Sjoerg if (!LangOpts.WritableStrings) { 4917*7330f729Sjoerg Entry = &ConstantStringMap[C]; 4918*7330f729Sjoerg if (auto GV = *Entry) { 4919*7330f729Sjoerg if (Alignment.getQuantity() > GV->getAlignment()) 4920*7330f729Sjoerg GV->setAlignment(Alignment.getAsAlign()); 4921*7330f729Sjoerg return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 4922*7330f729Sjoerg Alignment); 4923*7330f729Sjoerg } 4924*7330f729Sjoerg } 4925*7330f729Sjoerg 4926*7330f729Sjoerg SmallString<256> MangledNameBuffer; 4927*7330f729Sjoerg StringRef GlobalVariableName; 4928*7330f729Sjoerg llvm::GlobalValue::LinkageTypes LT; 4929*7330f729Sjoerg 4930*7330f729Sjoerg // Mangle the string literal if that's how the ABI merges duplicate strings. 4931*7330f729Sjoerg // Don't do it if they are writable, since we don't want writes in one TU to 4932*7330f729Sjoerg // affect strings in another. 4933*7330f729Sjoerg if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && 4934*7330f729Sjoerg !LangOpts.WritableStrings) { 4935*7330f729Sjoerg llvm::raw_svector_ostream Out(MangledNameBuffer); 4936*7330f729Sjoerg getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 4937*7330f729Sjoerg LT = llvm::GlobalValue::LinkOnceODRLinkage; 4938*7330f729Sjoerg GlobalVariableName = MangledNameBuffer; 4939*7330f729Sjoerg } else { 4940*7330f729Sjoerg LT = llvm::GlobalValue::PrivateLinkage; 4941*7330f729Sjoerg GlobalVariableName = Name; 4942*7330f729Sjoerg } 4943*7330f729Sjoerg 4944*7330f729Sjoerg auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 4945*7330f729Sjoerg if (Entry) 4946*7330f729Sjoerg *Entry = GV; 4947*7330f729Sjoerg 4948*7330f729Sjoerg SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 4949*7330f729Sjoerg QualType()); 4950*7330f729Sjoerg 4951*7330f729Sjoerg return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 4952*7330f729Sjoerg Alignment); 4953*7330f729Sjoerg } 4954*7330f729Sjoerg 4955*7330f729Sjoerg /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 4956*7330f729Sjoerg /// array for the given ObjCEncodeExpr node. 4957*7330f729Sjoerg ConstantAddress 4958*7330f729Sjoerg CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 4959*7330f729Sjoerg std::string Str; 4960*7330f729Sjoerg getContext().getObjCEncodingForType(E->getEncodedType(), Str); 4961*7330f729Sjoerg 4962*7330f729Sjoerg return GetAddrOfConstantCString(Str); 4963*7330f729Sjoerg } 4964*7330f729Sjoerg 4965*7330f729Sjoerg /// GetAddrOfConstantCString - Returns a pointer to a character array containing 4966*7330f729Sjoerg /// the literal and a terminating '\0' character. 4967*7330f729Sjoerg /// The result has pointer to array type. 4968*7330f729Sjoerg ConstantAddress CodeGenModule::GetAddrOfConstantCString( 4969*7330f729Sjoerg const std::string &Str, const char *GlobalName) { 4970*7330f729Sjoerg StringRef StrWithNull(Str.c_str(), Str.size() + 1); 4971*7330f729Sjoerg CharUnits Alignment = 4972*7330f729Sjoerg getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 4973*7330f729Sjoerg 4974*7330f729Sjoerg llvm::Constant *C = 4975*7330f729Sjoerg llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 4976*7330f729Sjoerg 4977*7330f729Sjoerg // Don't share any string literals if strings aren't constant. 4978*7330f729Sjoerg llvm::GlobalVariable **Entry = nullptr; 4979*7330f729Sjoerg if (!LangOpts.WritableStrings) { 4980*7330f729Sjoerg Entry = &ConstantStringMap[C]; 4981*7330f729Sjoerg if (auto GV = *Entry) { 4982*7330f729Sjoerg if (Alignment.getQuantity() > GV->getAlignment()) 4983*7330f729Sjoerg GV->setAlignment(Alignment.getAsAlign()); 4984*7330f729Sjoerg return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 4985*7330f729Sjoerg Alignment); 4986*7330f729Sjoerg } 4987*7330f729Sjoerg } 4988*7330f729Sjoerg 4989*7330f729Sjoerg // Get the default prefix if a name wasn't specified. 4990*7330f729Sjoerg if (!GlobalName) 4991*7330f729Sjoerg GlobalName = ".str"; 4992*7330f729Sjoerg // Create a global variable for this. 4993*7330f729Sjoerg auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 4994*7330f729Sjoerg GlobalName, Alignment); 4995*7330f729Sjoerg if (Entry) 4996*7330f729Sjoerg *Entry = GV; 4997*7330f729Sjoerg 4998*7330f729Sjoerg return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 4999*7330f729Sjoerg Alignment); 5000*7330f729Sjoerg } 5001*7330f729Sjoerg 5002*7330f729Sjoerg ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 5003*7330f729Sjoerg const MaterializeTemporaryExpr *E, const Expr *Init) { 5004*7330f729Sjoerg assert((E->getStorageDuration() == SD_Static || 5005*7330f729Sjoerg E->getStorageDuration() == SD_Thread) && "not a global temporary"); 5006*7330f729Sjoerg const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 5007*7330f729Sjoerg 5008*7330f729Sjoerg // If we're not materializing a subobject of the temporary, keep the 5009*7330f729Sjoerg // cv-qualifiers from the type of the MaterializeTemporaryExpr. 5010*7330f729Sjoerg QualType MaterializedType = Init->getType(); 5011*7330f729Sjoerg if (Init == E->GetTemporaryExpr()) 5012*7330f729Sjoerg MaterializedType = E->getType(); 5013*7330f729Sjoerg 5014*7330f729Sjoerg CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 5015*7330f729Sjoerg 5016*7330f729Sjoerg if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E]) 5017*7330f729Sjoerg return ConstantAddress(Slot, Align); 5018*7330f729Sjoerg 5019*7330f729Sjoerg // FIXME: If an externally-visible declaration extends multiple temporaries, 5020*7330f729Sjoerg // we need to give each temporary the same name in every translation unit (and 5021*7330f729Sjoerg // we also need to make the temporaries externally-visible). 5022*7330f729Sjoerg SmallString<256> Name; 5023*7330f729Sjoerg llvm::raw_svector_ostream Out(Name); 5024*7330f729Sjoerg getCXXABI().getMangleContext().mangleReferenceTemporary( 5025*7330f729Sjoerg VD, E->getManglingNumber(), Out); 5026*7330f729Sjoerg 5027*7330f729Sjoerg APValue *Value = nullptr; 5028*7330f729Sjoerg if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) { 5029*7330f729Sjoerg // If the initializer of the extending declaration is a constant 5030*7330f729Sjoerg // initializer, we should have a cached constant initializer for this 5031*7330f729Sjoerg // temporary. Note that this might have a different value from the value 5032*7330f729Sjoerg // computed by evaluating the initializer if the surrounding constant 5033*7330f729Sjoerg // expression modifies the temporary. 5034*7330f729Sjoerg Value = getContext().getMaterializedTemporaryValue(E, false); 5035*7330f729Sjoerg } 5036*7330f729Sjoerg 5037*7330f729Sjoerg // Try evaluating it now, it might have a constant initializer. 5038*7330f729Sjoerg Expr::EvalResult EvalResult; 5039*7330f729Sjoerg if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 5040*7330f729Sjoerg !EvalResult.hasSideEffects()) 5041*7330f729Sjoerg Value = &EvalResult.Val; 5042*7330f729Sjoerg 5043*7330f729Sjoerg LangAS AddrSpace = 5044*7330f729Sjoerg VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace(); 5045*7330f729Sjoerg 5046*7330f729Sjoerg Optional<ConstantEmitter> emitter; 5047*7330f729Sjoerg llvm::Constant *InitialValue = nullptr; 5048*7330f729Sjoerg bool Constant = false; 5049*7330f729Sjoerg llvm::Type *Type; 5050*7330f729Sjoerg if (Value) { 5051*7330f729Sjoerg // The temporary has a constant initializer, use it. 5052*7330f729Sjoerg emitter.emplace(*this); 5053*7330f729Sjoerg InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 5054*7330f729Sjoerg MaterializedType); 5055*7330f729Sjoerg Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 5056*7330f729Sjoerg Type = InitialValue->getType(); 5057*7330f729Sjoerg } else { 5058*7330f729Sjoerg // No initializer, the initialization will be provided when we 5059*7330f729Sjoerg // initialize the declaration which performed lifetime extension. 5060*7330f729Sjoerg Type = getTypes().ConvertTypeForMem(MaterializedType); 5061*7330f729Sjoerg } 5062*7330f729Sjoerg 5063*7330f729Sjoerg // Create a global variable for this lifetime-extended temporary. 5064*7330f729Sjoerg llvm::GlobalValue::LinkageTypes Linkage = 5065*7330f729Sjoerg getLLVMLinkageVarDefinition(VD, Constant); 5066*7330f729Sjoerg if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 5067*7330f729Sjoerg const VarDecl *InitVD; 5068*7330f729Sjoerg if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 5069*7330f729Sjoerg isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 5070*7330f729Sjoerg // Temporaries defined inside a class get linkonce_odr linkage because the 5071*7330f729Sjoerg // class can be defined in multiple translation units. 5072*7330f729Sjoerg Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 5073*7330f729Sjoerg } else { 5074*7330f729Sjoerg // There is no need for this temporary to have external linkage if the 5075*7330f729Sjoerg // VarDecl has external linkage. 5076*7330f729Sjoerg Linkage = llvm::GlobalVariable::InternalLinkage; 5077*7330f729Sjoerg } 5078*7330f729Sjoerg } 5079*7330f729Sjoerg auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 5080*7330f729Sjoerg auto *GV = new llvm::GlobalVariable( 5081*7330f729Sjoerg getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 5082*7330f729Sjoerg /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 5083*7330f729Sjoerg if (emitter) emitter->finalize(GV); 5084*7330f729Sjoerg setGVProperties(GV, VD); 5085*7330f729Sjoerg GV->setAlignment(Align.getAsAlign()); 5086*7330f729Sjoerg if (supportsCOMDAT() && GV->isWeakForLinker()) 5087*7330f729Sjoerg GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 5088*7330f729Sjoerg if (VD->getTLSKind()) 5089*7330f729Sjoerg setTLSMode(GV, *VD); 5090*7330f729Sjoerg llvm::Constant *CV = GV; 5091*7330f729Sjoerg if (AddrSpace != LangAS::Default) 5092*7330f729Sjoerg CV = getTargetCodeGenInfo().performAddrSpaceCast( 5093*7330f729Sjoerg *this, GV, AddrSpace, LangAS::Default, 5094*7330f729Sjoerg Type->getPointerTo( 5095*7330f729Sjoerg getContext().getTargetAddressSpace(LangAS::Default))); 5096*7330f729Sjoerg MaterializedGlobalTemporaryMap[E] = CV; 5097*7330f729Sjoerg return ConstantAddress(CV, Align); 5098*7330f729Sjoerg } 5099*7330f729Sjoerg 5100*7330f729Sjoerg /// EmitObjCPropertyImplementations - Emit information for synthesized 5101*7330f729Sjoerg /// properties for an implementation. 5102*7330f729Sjoerg void CodeGenModule::EmitObjCPropertyImplementations(const 5103*7330f729Sjoerg ObjCImplementationDecl *D) { 5104*7330f729Sjoerg for (const auto *PID : D->property_impls()) { 5105*7330f729Sjoerg // Dynamic is just for type-checking. 5106*7330f729Sjoerg if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 5107*7330f729Sjoerg ObjCPropertyDecl *PD = PID->getPropertyDecl(); 5108*7330f729Sjoerg 5109*7330f729Sjoerg // Determine which methods need to be implemented, some may have 5110*7330f729Sjoerg // been overridden. Note that ::isPropertyAccessor is not the method 5111*7330f729Sjoerg // we want, that just indicates if the decl came from a 5112*7330f729Sjoerg // property. What we want to know is if the method is defined in 5113*7330f729Sjoerg // this implementation. 5114*7330f729Sjoerg if (!D->getInstanceMethod(PD->getGetterName())) 5115*7330f729Sjoerg CodeGenFunction(*this).GenerateObjCGetter( 5116*7330f729Sjoerg const_cast<ObjCImplementationDecl *>(D), PID); 5117*7330f729Sjoerg if (!PD->isReadOnly() && 5118*7330f729Sjoerg !D->getInstanceMethod(PD->getSetterName())) 5119*7330f729Sjoerg CodeGenFunction(*this).GenerateObjCSetter( 5120*7330f729Sjoerg const_cast<ObjCImplementationDecl *>(D), PID); 5121*7330f729Sjoerg } 5122*7330f729Sjoerg } 5123*7330f729Sjoerg } 5124*7330f729Sjoerg 5125*7330f729Sjoerg static bool needsDestructMethod(ObjCImplementationDecl *impl) { 5126*7330f729Sjoerg const ObjCInterfaceDecl *iface = impl->getClassInterface(); 5127*7330f729Sjoerg for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 5128*7330f729Sjoerg ivar; ivar = ivar->getNextIvar()) 5129*7330f729Sjoerg if (ivar->getType().isDestructedType()) 5130*7330f729Sjoerg return true; 5131*7330f729Sjoerg 5132*7330f729Sjoerg return false; 5133*7330f729Sjoerg } 5134*7330f729Sjoerg 5135*7330f729Sjoerg static bool AllTrivialInitializers(CodeGenModule &CGM, 5136*7330f729Sjoerg ObjCImplementationDecl *D) { 5137*7330f729Sjoerg CodeGenFunction CGF(CGM); 5138*7330f729Sjoerg for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 5139*7330f729Sjoerg E = D->init_end(); B != E; ++B) { 5140*7330f729Sjoerg CXXCtorInitializer *CtorInitExp = *B; 5141*7330f729Sjoerg Expr *Init = CtorInitExp->getInit(); 5142*7330f729Sjoerg if (!CGF.isTrivialInitializer(Init)) 5143*7330f729Sjoerg return false; 5144*7330f729Sjoerg } 5145*7330f729Sjoerg return true; 5146*7330f729Sjoerg } 5147*7330f729Sjoerg 5148*7330f729Sjoerg /// EmitObjCIvarInitializations - Emit information for ivar initialization 5149*7330f729Sjoerg /// for an implementation. 5150*7330f729Sjoerg void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 5151*7330f729Sjoerg // We might need a .cxx_destruct even if we don't have any ivar initializers. 5152*7330f729Sjoerg if (needsDestructMethod(D)) { 5153*7330f729Sjoerg IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 5154*7330f729Sjoerg Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 5155*7330f729Sjoerg ObjCMethodDecl *DTORMethod = 5156*7330f729Sjoerg ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 5157*7330f729Sjoerg cxxSelector, getContext().VoidTy, nullptr, D, 5158*7330f729Sjoerg /*isInstance=*/true, /*isVariadic=*/false, 5159*7330f729Sjoerg /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 5160*7330f729Sjoerg /*isDefined=*/false, ObjCMethodDecl::Required); 5161*7330f729Sjoerg D->addInstanceMethod(DTORMethod); 5162*7330f729Sjoerg CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 5163*7330f729Sjoerg D->setHasDestructors(true); 5164*7330f729Sjoerg } 5165*7330f729Sjoerg 5166*7330f729Sjoerg // If the implementation doesn't have any ivar initializers, we don't need 5167*7330f729Sjoerg // a .cxx_construct. 5168*7330f729Sjoerg if (D->getNumIvarInitializers() == 0 || 5169*7330f729Sjoerg AllTrivialInitializers(*this, D)) 5170*7330f729Sjoerg return; 5171*7330f729Sjoerg 5172*7330f729Sjoerg IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 5173*7330f729Sjoerg Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 5174*7330f729Sjoerg // The constructor returns 'self'. 5175*7330f729Sjoerg ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 5176*7330f729Sjoerg D->getLocation(), 5177*7330f729Sjoerg D->getLocation(), 5178*7330f729Sjoerg cxxSelector, 5179*7330f729Sjoerg getContext().getObjCIdType(), 5180*7330f729Sjoerg nullptr, D, /*isInstance=*/true, 5181*7330f729Sjoerg /*isVariadic=*/false, 5182*7330f729Sjoerg /*isPropertyAccessor=*/true, 5183*7330f729Sjoerg /*isImplicitlyDeclared=*/true, 5184*7330f729Sjoerg /*isDefined=*/false, 5185*7330f729Sjoerg ObjCMethodDecl::Required); 5186*7330f729Sjoerg D->addInstanceMethod(CTORMethod); 5187*7330f729Sjoerg CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 5188*7330f729Sjoerg D->setHasNonZeroConstructors(true); 5189*7330f729Sjoerg } 5190*7330f729Sjoerg 5191*7330f729Sjoerg // EmitLinkageSpec - Emit all declarations in a linkage spec. 5192*7330f729Sjoerg void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 5193*7330f729Sjoerg if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 5194*7330f729Sjoerg LSD->getLanguage() != LinkageSpecDecl::lang_cxx && 5195*7330f729Sjoerg LSD->getLanguage() != LinkageSpecDecl::lang_cxx_11 && 5196*7330f729Sjoerg LSD->getLanguage() != LinkageSpecDecl::lang_cxx_14) { 5197*7330f729Sjoerg ErrorUnsupported(LSD, "linkage spec"); 5198*7330f729Sjoerg return; 5199*7330f729Sjoerg } 5200*7330f729Sjoerg 5201*7330f729Sjoerg EmitDeclContext(LSD); 5202*7330f729Sjoerg } 5203*7330f729Sjoerg 5204*7330f729Sjoerg void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 5205*7330f729Sjoerg for (auto *I : DC->decls()) { 5206*7330f729Sjoerg // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 5207*7330f729Sjoerg // are themselves considered "top-level", so EmitTopLevelDecl on an 5208*7330f729Sjoerg // ObjCImplDecl does not recursively visit them. We need to do that in 5209*7330f729Sjoerg // case they're nested inside another construct (LinkageSpecDecl / 5210*7330f729Sjoerg // ExportDecl) that does stop them from being considered "top-level". 5211*7330f729Sjoerg if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 5212*7330f729Sjoerg for (auto *M : OID->methods()) 5213*7330f729Sjoerg EmitTopLevelDecl(M); 5214*7330f729Sjoerg } 5215*7330f729Sjoerg 5216*7330f729Sjoerg EmitTopLevelDecl(I); 5217*7330f729Sjoerg } 5218*7330f729Sjoerg } 5219*7330f729Sjoerg 5220*7330f729Sjoerg /// EmitTopLevelDecl - Emit code for a single top level declaration. 5221*7330f729Sjoerg void CodeGenModule::EmitTopLevelDecl(Decl *D) { 5222*7330f729Sjoerg // Ignore dependent declarations. 5223*7330f729Sjoerg if (D->isTemplated()) 5224*7330f729Sjoerg return; 5225*7330f729Sjoerg 5226*7330f729Sjoerg switch (D->getKind()) { 5227*7330f729Sjoerg case Decl::CXXConversion: 5228*7330f729Sjoerg case Decl::CXXMethod: 5229*7330f729Sjoerg case Decl::Function: 5230*7330f729Sjoerg EmitGlobal(cast<FunctionDecl>(D)); 5231*7330f729Sjoerg // Always provide some coverage mapping 5232*7330f729Sjoerg // even for the functions that aren't emitted. 5233*7330f729Sjoerg AddDeferredUnusedCoverageMapping(D); 5234*7330f729Sjoerg break; 5235*7330f729Sjoerg 5236*7330f729Sjoerg case Decl::CXXDeductionGuide: 5237*7330f729Sjoerg // Function-like, but does not result in code emission. 5238*7330f729Sjoerg break; 5239*7330f729Sjoerg 5240*7330f729Sjoerg case Decl::Var: 5241*7330f729Sjoerg case Decl::Decomposition: 5242*7330f729Sjoerg case Decl::VarTemplateSpecialization: 5243*7330f729Sjoerg EmitGlobal(cast<VarDecl>(D)); 5244*7330f729Sjoerg if (auto *DD = dyn_cast<DecompositionDecl>(D)) 5245*7330f729Sjoerg for (auto *B : DD->bindings()) 5246*7330f729Sjoerg if (auto *HD = B->getHoldingVar()) 5247*7330f729Sjoerg EmitGlobal(HD); 5248*7330f729Sjoerg break; 5249*7330f729Sjoerg 5250*7330f729Sjoerg // Indirect fields from global anonymous structs and unions can be 5251*7330f729Sjoerg // ignored; only the actual variable requires IR gen support. 5252*7330f729Sjoerg case Decl::IndirectField: 5253*7330f729Sjoerg break; 5254*7330f729Sjoerg 5255*7330f729Sjoerg // C++ Decls 5256*7330f729Sjoerg case Decl::Namespace: 5257*7330f729Sjoerg EmitDeclContext(cast<NamespaceDecl>(D)); 5258*7330f729Sjoerg break; 5259*7330f729Sjoerg case Decl::ClassTemplateSpecialization: { 5260*7330f729Sjoerg const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 5261*7330f729Sjoerg if (DebugInfo && 5262*7330f729Sjoerg Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition && 5263*7330f729Sjoerg Spec->hasDefinition()) 5264*7330f729Sjoerg DebugInfo->completeTemplateDefinition(*Spec); 5265*7330f729Sjoerg } LLVM_FALLTHROUGH; 5266*7330f729Sjoerg case Decl::CXXRecord: 5267*7330f729Sjoerg if (DebugInfo) { 5268*7330f729Sjoerg if (auto *ES = D->getASTContext().getExternalSource()) 5269*7330f729Sjoerg if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 5270*7330f729Sjoerg DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D)); 5271*7330f729Sjoerg } 5272*7330f729Sjoerg // Emit any static data members, they may be definitions. 5273*7330f729Sjoerg for (auto *I : cast<CXXRecordDecl>(D)->decls()) 5274*7330f729Sjoerg if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 5275*7330f729Sjoerg EmitTopLevelDecl(I); 5276*7330f729Sjoerg break; 5277*7330f729Sjoerg // No code generation needed. 5278*7330f729Sjoerg case Decl::UsingShadow: 5279*7330f729Sjoerg case Decl::ClassTemplate: 5280*7330f729Sjoerg case Decl::VarTemplate: 5281*7330f729Sjoerg case Decl::Concept: 5282*7330f729Sjoerg case Decl::VarTemplatePartialSpecialization: 5283*7330f729Sjoerg case Decl::FunctionTemplate: 5284*7330f729Sjoerg case Decl::TypeAliasTemplate: 5285*7330f729Sjoerg case Decl::Block: 5286*7330f729Sjoerg case Decl::Empty: 5287*7330f729Sjoerg case Decl::Binding: 5288*7330f729Sjoerg break; 5289*7330f729Sjoerg case Decl::Using: // using X; [C++] 5290*7330f729Sjoerg if (CGDebugInfo *DI = getModuleDebugInfo()) 5291*7330f729Sjoerg DI->EmitUsingDecl(cast<UsingDecl>(*D)); 5292*7330f729Sjoerg return; 5293*7330f729Sjoerg case Decl::NamespaceAlias: 5294*7330f729Sjoerg if (CGDebugInfo *DI = getModuleDebugInfo()) 5295*7330f729Sjoerg DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 5296*7330f729Sjoerg return; 5297*7330f729Sjoerg case Decl::UsingDirective: // using namespace X; [C++] 5298*7330f729Sjoerg if (CGDebugInfo *DI = getModuleDebugInfo()) 5299*7330f729Sjoerg DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 5300*7330f729Sjoerg return; 5301*7330f729Sjoerg case Decl::CXXConstructor: 5302*7330f729Sjoerg getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 5303*7330f729Sjoerg break; 5304*7330f729Sjoerg case Decl::CXXDestructor: 5305*7330f729Sjoerg getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 5306*7330f729Sjoerg break; 5307*7330f729Sjoerg 5308*7330f729Sjoerg case Decl::StaticAssert: 5309*7330f729Sjoerg // Nothing to do. 5310*7330f729Sjoerg break; 5311*7330f729Sjoerg 5312*7330f729Sjoerg // Objective-C Decls 5313*7330f729Sjoerg 5314*7330f729Sjoerg // Forward declarations, no (immediate) code generation. 5315*7330f729Sjoerg case Decl::ObjCInterface: 5316*7330f729Sjoerg case Decl::ObjCCategory: 5317*7330f729Sjoerg break; 5318*7330f729Sjoerg 5319*7330f729Sjoerg case Decl::ObjCProtocol: { 5320*7330f729Sjoerg auto *Proto = cast<ObjCProtocolDecl>(D); 5321*7330f729Sjoerg if (Proto->isThisDeclarationADefinition()) 5322*7330f729Sjoerg ObjCRuntime->GenerateProtocol(Proto); 5323*7330f729Sjoerg break; 5324*7330f729Sjoerg } 5325*7330f729Sjoerg 5326*7330f729Sjoerg case Decl::ObjCCategoryImpl: 5327*7330f729Sjoerg // Categories have properties but don't support synthesize so we 5328*7330f729Sjoerg // can ignore them here. 5329*7330f729Sjoerg ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 5330*7330f729Sjoerg break; 5331*7330f729Sjoerg 5332*7330f729Sjoerg case Decl::ObjCImplementation: { 5333*7330f729Sjoerg auto *OMD = cast<ObjCImplementationDecl>(D); 5334*7330f729Sjoerg EmitObjCPropertyImplementations(OMD); 5335*7330f729Sjoerg EmitObjCIvarInitializations(OMD); 5336*7330f729Sjoerg ObjCRuntime->GenerateClass(OMD); 5337*7330f729Sjoerg // Emit global variable debug information. 5338*7330f729Sjoerg if (CGDebugInfo *DI = getModuleDebugInfo()) 5339*7330f729Sjoerg if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 5340*7330f729Sjoerg DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 5341*7330f729Sjoerg OMD->getClassInterface()), OMD->getLocation()); 5342*7330f729Sjoerg break; 5343*7330f729Sjoerg } 5344*7330f729Sjoerg case Decl::ObjCMethod: { 5345*7330f729Sjoerg auto *OMD = cast<ObjCMethodDecl>(D); 5346*7330f729Sjoerg // If this is not a prototype, emit the body. 5347*7330f729Sjoerg if (OMD->getBody()) 5348*7330f729Sjoerg CodeGenFunction(*this).GenerateObjCMethod(OMD); 5349*7330f729Sjoerg break; 5350*7330f729Sjoerg } 5351*7330f729Sjoerg case Decl::ObjCCompatibleAlias: 5352*7330f729Sjoerg ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 5353*7330f729Sjoerg break; 5354*7330f729Sjoerg 5355*7330f729Sjoerg case Decl::PragmaComment: { 5356*7330f729Sjoerg const auto *PCD = cast<PragmaCommentDecl>(D); 5357*7330f729Sjoerg switch (PCD->getCommentKind()) { 5358*7330f729Sjoerg case PCK_Unknown: 5359*7330f729Sjoerg llvm_unreachable("unexpected pragma comment kind"); 5360*7330f729Sjoerg case PCK_Linker: 5361*7330f729Sjoerg AppendLinkerOptions(PCD->getArg()); 5362*7330f729Sjoerg break; 5363*7330f729Sjoerg case PCK_Lib: 5364*7330f729Sjoerg AddDependentLib(PCD->getArg()); 5365*7330f729Sjoerg break; 5366*7330f729Sjoerg case PCK_Compiler: 5367*7330f729Sjoerg case PCK_ExeStr: 5368*7330f729Sjoerg case PCK_User: 5369*7330f729Sjoerg break; // We ignore all of these. 5370*7330f729Sjoerg } 5371*7330f729Sjoerg break; 5372*7330f729Sjoerg } 5373*7330f729Sjoerg 5374*7330f729Sjoerg case Decl::PragmaDetectMismatch: { 5375*7330f729Sjoerg const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 5376*7330f729Sjoerg AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 5377*7330f729Sjoerg break; 5378*7330f729Sjoerg } 5379*7330f729Sjoerg 5380*7330f729Sjoerg case Decl::LinkageSpec: 5381*7330f729Sjoerg EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 5382*7330f729Sjoerg break; 5383*7330f729Sjoerg 5384*7330f729Sjoerg case Decl::FileScopeAsm: { 5385*7330f729Sjoerg // File-scope asm is ignored during device-side CUDA compilation. 5386*7330f729Sjoerg if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 5387*7330f729Sjoerg break; 5388*7330f729Sjoerg // File-scope asm is ignored during device-side OpenMP compilation. 5389*7330f729Sjoerg if (LangOpts.OpenMPIsDevice) 5390*7330f729Sjoerg break; 5391*7330f729Sjoerg auto *AD = cast<FileScopeAsmDecl>(D); 5392*7330f729Sjoerg getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 5393*7330f729Sjoerg break; 5394*7330f729Sjoerg } 5395*7330f729Sjoerg 5396*7330f729Sjoerg case Decl::Import: { 5397*7330f729Sjoerg auto *Import = cast<ImportDecl>(D); 5398*7330f729Sjoerg 5399*7330f729Sjoerg // If we've already imported this module, we're done. 5400*7330f729Sjoerg if (!ImportedModules.insert(Import->getImportedModule())) 5401*7330f729Sjoerg break; 5402*7330f729Sjoerg 5403*7330f729Sjoerg // Emit debug information for direct imports. 5404*7330f729Sjoerg if (!Import->getImportedOwningModule()) { 5405*7330f729Sjoerg if (CGDebugInfo *DI = getModuleDebugInfo()) 5406*7330f729Sjoerg DI->EmitImportDecl(*Import); 5407*7330f729Sjoerg } 5408*7330f729Sjoerg 5409*7330f729Sjoerg // Find all of the submodules and emit the module initializers. 5410*7330f729Sjoerg llvm::SmallPtrSet<clang::Module *, 16> Visited; 5411*7330f729Sjoerg SmallVector<clang::Module *, 16> Stack; 5412*7330f729Sjoerg Visited.insert(Import->getImportedModule()); 5413*7330f729Sjoerg Stack.push_back(Import->getImportedModule()); 5414*7330f729Sjoerg 5415*7330f729Sjoerg while (!Stack.empty()) { 5416*7330f729Sjoerg clang::Module *Mod = Stack.pop_back_val(); 5417*7330f729Sjoerg if (!EmittedModuleInitializers.insert(Mod).second) 5418*7330f729Sjoerg continue; 5419*7330f729Sjoerg 5420*7330f729Sjoerg for (auto *D : Context.getModuleInitializers(Mod)) 5421*7330f729Sjoerg EmitTopLevelDecl(D); 5422*7330f729Sjoerg 5423*7330f729Sjoerg // Visit the submodules of this module. 5424*7330f729Sjoerg for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 5425*7330f729Sjoerg SubEnd = Mod->submodule_end(); 5426*7330f729Sjoerg Sub != SubEnd; ++Sub) { 5427*7330f729Sjoerg // Skip explicit children; they need to be explicitly imported to emit 5428*7330f729Sjoerg // the initializers. 5429*7330f729Sjoerg if ((*Sub)->IsExplicit) 5430*7330f729Sjoerg continue; 5431*7330f729Sjoerg 5432*7330f729Sjoerg if (Visited.insert(*Sub).second) 5433*7330f729Sjoerg Stack.push_back(*Sub); 5434*7330f729Sjoerg } 5435*7330f729Sjoerg } 5436*7330f729Sjoerg break; 5437*7330f729Sjoerg } 5438*7330f729Sjoerg 5439*7330f729Sjoerg case Decl::Export: 5440*7330f729Sjoerg EmitDeclContext(cast<ExportDecl>(D)); 5441*7330f729Sjoerg break; 5442*7330f729Sjoerg 5443*7330f729Sjoerg case Decl::OMPThreadPrivate: 5444*7330f729Sjoerg EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 5445*7330f729Sjoerg break; 5446*7330f729Sjoerg 5447*7330f729Sjoerg case Decl::OMPAllocate: 5448*7330f729Sjoerg break; 5449*7330f729Sjoerg 5450*7330f729Sjoerg case Decl::OMPDeclareReduction: 5451*7330f729Sjoerg EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 5452*7330f729Sjoerg break; 5453*7330f729Sjoerg 5454*7330f729Sjoerg case Decl::OMPDeclareMapper: 5455*7330f729Sjoerg EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D)); 5456*7330f729Sjoerg break; 5457*7330f729Sjoerg 5458*7330f729Sjoerg case Decl::OMPRequires: 5459*7330f729Sjoerg EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); 5460*7330f729Sjoerg break; 5461*7330f729Sjoerg 5462*7330f729Sjoerg default: 5463*7330f729Sjoerg // Make sure we handled everything we should, every other kind is a 5464*7330f729Sjoerg // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 5465*7330f729Sjoerg // function. Need to recode Decl::Kind to do that easily. 5466*7330f729Sjoerg assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 5467*7330f729Sjoerg break; 5468*7330f729Sjoerg } 5469*7330f729Sjoerg } 5470*7330f729Sjoerg 5471*7330f729Sjoerg void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 5472*7330f729Sjoerg // Do we need to generate coverage mapping? 5473*7330f729Sjoerg if (!CodeGenOpts.CoverageMapping) 5474*7330f729Sjoerg return; 5475*7330f729Sjoerg switch (D->getKind()) { 5476*7330f729Sjoerg case Decl::CXXConversion: 5477*7330f729Sjoerg case Decl::CXXMethod: 5478*7330f729Sjoerg case Decl::Function: 5479*7330f729Sjoerg case Decl::ObjCMethod: 5480*7330f729Sjoerg case Decl::CXXConstructor: 5481*7330f729Sjoerg case Decl::CXXDestructor: { 5482*7330f729Sjoerg if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 5483*7330f729Sjoerg return; 5484*7330f729Sjoerg SourceManager &SM = getContext().getSourceManager(); 5485*7330f729Sjoerg if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) 5486*7330f729Sjoerg return; 5487*7330f729Sjoerg auto I = DeferredEmptyCoverageMappingDecls.find(D); 5488*7330f729Sjoerg if (I == DeferredEmptyCoverageMappingDecls.end()) 5489*7330f729Sjoerg DeferredEmptyCoverageMappingDecls[D] = true; 5490*7330f729Sjoerg break; 5491*7330f729Sjoerg } 5492*7330f729Sjoerg default: 5493*7330f729Sjoerg break; 5494*7330f729Sjoerg }; 5495*7330f729Sjoerg } 5496*7330f729Sjoerg 5497*7330f729Sjoerg void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 5498*7330f729Sjoerg // Do we need to generate coverage mapping? 5499*7330f729Sjoerg if (!CodeGenOpts.CoverageMapping) 5500*7330f729Sjoerg return; 5501*7330f729Sjoerg if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 5502*7330f729Sjoerg if (Fn->isTemplateInstantiation()) 5503*7330f729Sjoerg ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 5504*7330f729Sjoerg } 5505*7330f729Sjoerg auto I = DeferredEmptyCoverageMappingDecls.find(D); 5506*7330f729Sjoerg if (I == DeferredEmptyCoverageMappingDecls.end()) 5507*7330f729Sjoerg DeferredEmptyCoverageMappingDecls[D] = false; 5508*7330f729Sjoerg else 5509*7330f729Sjoerg I->second = false; 5510*7330f729Sjoerg } 5511*7330f729Sjoerg 5512*7330f729Sjoerg void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 5513*7330f729Sjoerg // We call takeVector() here to avoid use-after-free. 5514*7330f729Sjoerg // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 5515*7330f729Sjoerg // we deserialize function bodies to emit coverage info for them, and that 5516*7330f729Sjoerg // deserializes more declarations. How should we handle that case? 5517*7330f729Sjoerg for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 5518*7330f729Sjoerg if (!Entry.second) 5519*7330f729Sjoerg continue; 5520*7330f729Sjoerg const Decl *D = Entry.first; 5521*7330f729Sjoerg switch (D->getKind()) { 5522*7330f729Sjoerg case Decl::CXXConversion: 5523*7330f729Sjoerg case Decl::CXXMethod: 5524*7330f729Sjoerg case Decl::Function: 5525*7330f729Sjoerg case Decl::ObjCMethod: { 5526*7330f729Sjoerg CodeGenPGO PGO(*this); 5527*7330f729Sjoerg GlobalDecl GD(cast<FunctionDecl>(D)); 5528*7330f729Sjoerg PGO.emitEmptyCounterMapping(D, getMangledName(GD), 5529*7330f729Sjoerg getFunctionLinkage(GD)); 5530*7330f729Sjoerg break; 5531*7330f729Sjoerg } 5532*7330f729Sjoerg case Decl::CXXConstructor: { 5533*7330f729Sjoerg CodeGenPGO PGO(*this); 5534*7330f729Sjoerg GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 5535*7330f729Sjoerg PGO.emitEmptyCounterMapping(D, getMangledName(GD), 5536*7330f729Sjoerg getFunctionLinkage(GD)); 5537*7330f729Sjoerg break; 5538*7330f729Sjoerg } 5539*7330f729Sjoerg case Decl::CXXDestructor: { 5540*7330f729Sjoerg CodeGenPGO PGO(*this); 5541*7330f729Sjoerg GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 5542*7330f729Sjoerg PGO.emitEmptyCounterMapping(D, getMangledName(GD), 5543*7330f729Sjoerg getFunctionLinkage(GD)); 5544*7330f729Sjoerg break; 5545*7330f729Sjoerg } 5546*7330f729Sjoerg default: 5547*7330f729Sjoerg break; 5548*7330f729Sjoerg }; 5549*7330f729Sjoerg } 5550*7330f729Sjoerg } 5551*7330f729Sjoerg 5552*7330f729Sjoerg /// Turns the given pointer into a constant. 5553*7330f729Sjoerg static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 5554*7330f729Sjoerg const void *Ptr) { 5555*7330f729Sjoerg uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 5556*7330f729Sjoerg llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 5557*7330f729Sjoerg return llvm::ConstantInt::get(i64, PtrInt); 5558*7330f729Sjoerg } 5559*7330f729Sjoerg 5560*7330f729Sjoerg static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 5561*7330f729Sjoerg llvm::NamedMDNode *&GlobalMetadata, 5562*7330f729Sjoerg GlobalDecl D, 5563*7330f729Sjoerg llvm::GlobalValue *Addr) { 5564*7330f729Sjoerg if (!GlobalMetadata) 5565*7330f729Sjoerg GlobalMetadata = 5566*7330f729Sjoerg CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 5567*7330f729Sjoerg 5568*7330f729Sjoerg // TODO: should we report variant information for ctors/dtors? 5569*7330f729Sjoerg llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 5570*7330f729Sjoerg llvm::ConstantAsMetadata::get(GetPointerConstant( 5571*7330f729Sjoerg CGM.getLLVMContext(), D.getDecl()))}; 5572*7330f729Sjoerg GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 5573*7330f729Sjoerg } 5574*7330f729Sjoerg 5575*7330f729Sjoerg /// For each function which is declared within an extern "C" region and marked 5576*7330f729Sjoerg /// as 'used', but has internal linkage, create an alias from the unmangled 5577*7330f729Sjoerg /// name to the mangled name if possible. People expect to be able to refer 5578*7330f729Sjoerg /// to such functions with an unmangled name from inline assembly within the 5579*7330f729Sjoerg /// same translation unit. 5580*7330f729Sjoerg void CodeGenModule::EmitStaticExternCAliases() { 5581*7330f729Sjoerg if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) 5582*7330f729Sjoerg return; 5583*7330f729Sjoerg for (auto &I : StaticExternCValues) { 5584*7330f729Sjoerg IdentifierInfo *Name = I.first; 5585*7330f729Sjoerg llvm::GlobalValue *Val = I.second; 5586*7330f729Sjoerg if (Val && !getModule().getNamedValue(Name->getName())) 5587*7330f729Sjoerg addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 5588*7330f729Sjoerg } 5589*7330f729Sjoerg } 5590*7330f729Sjoerg 5591*7330f729Sjoerg bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 5592*7330f729Sjoerg GlobalDecl &Result) const { 5593*7330f729Sjoerg auto Res = Manglings.find(MangledName); 5594*7330f729Sjoerg if (Res == Manglings.end()) 5595*7330f729Sjoerg return false; 5596*7330f729Sjoerg Result = Res->getValue(); 5597*7330f729Sjoerg return true; 5598*7330f729Sjoerg } 5599*7330f729Sjoerg 5600*7330f729Sjoerg /// Emits metadata nodes associating all the global values in the 5601*7330f729Sjoerg /// current module with the Decls they came from. This is useful for 5602*7330f729Sjoerg /// projects using IR gen as a subroutine. 5603*7330f729Sjoerg /// 5604*7330f729Sjoerg /// Since there's currently no way to associate an MDNode directly 5605*7330f729Sjoerg /// with an llvm::GlobalValue, we create a global named metadata 5606*7330f729Sjoerg /// with the name 'clang.global.decl.ptrs'. 5607*7330f729Sjoerg void CodeGenModule::EmitDeclMetadata() { 5608*7330f729Sjoerg llvm::NamedMDNode *GlobalMetadata = nullptr; 5609*7330f729Sjoerg 5610*7330f729Sjoerg for (auto &I : MangledDeclNames) { 5611*7330f729Sjoerg llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 5612*7330f729Sjoerg // Some mangled names don't necessarily have an associated GlobalValue 5613*7330f729Sjoerg // in this module, e.g. if we mangled it for DebugInfo. 5614*7330f729Sjoerg if (Addr) 5615*7330f729Sjoerg EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 5616*7330f729Sjoerg } 5617*7330f729Sjoerg } 5618*7330f729Sjoerg 5619*7330f729Sjoerg /// Emits metadata nodes for all the local variables in the current 5620*7330f729Sjoerg /// function. 5621*7330f729Sjoerg void CodeGenFunction::EmitDeclMetadata() { 5622*7330f729Sjoerg if (LocalDeclMap.empty()) return; 5623*7330f729Sjoerg 5624*7330f729Sjoerg llvm::LLVMContext &Context = getLLVMContext(); 5625*7330f729Sjoerg 5626*7330f729Sjoerg // Find the unique metadata ID for this name. 5627*7330f729Sjoerg unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 5628*7330f729Sjoerg 5629*7330f729Sjoerg llvm::NamedMDNode *GlobalMetadata = nullptr; 5630*7330f729Sjoerg 5631*7330f729Sjoerg for (auto &I : LocalDeclMap) { 5632*7330f729Sjoerg const Decl *D = I.first; 5633*7330f729Sjoerg llvm::Value *Addr = I.second.getPointer(); 5634*7330f729Sjoerg if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 5635*7330f729Sjoerg llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 5636*7330f729Sjoerg Alloca->setMetadata( 5637*7330f729Sjoerg DeclPtrKind, llvm::MDNode::get( 5638*7330f729Sjoerg Context, llvm::ValueAsMetadata::getConstant(DAddr))); 5639*7330f729Sjoerg } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 5640*7330f729Sjoerg GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 5641*7330f729Sjoerg EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 5642*7330f729Sjoerg } 5643*7330f729Sjoerg } 5644*7330f729Sjoerg } 5645*7330f729Sjoerg 5646*7330f729Sjoerg void CodeGenModule::EmitVersionIdentMetadata() { 5647*7330f729Sjoerg llvm::NamedMDNode *IdentMetadata = 5648*7330f729Sjoerg TheModule.getOrInsertNamedMetadata("llvm.ident"); 5649*7330f729Sjoerg std::string Version = getClangFullVersion(); 5650*7330f729Sjoerg llvm::LLVMContext &Ctx = TheModule.getContext(); 5651*7330f729Sjoerg 5652*7330f729Sjoerg llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 5653*7330f729Sjoerg IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 5654*7330f729Sjoerg } 5655*7330f729Sjoerg 5656*7330f729Sjoerg void CodeGenModule::EmitCommandLineMetadata() { 5657*7330f729Sjoerg llvm::NamedMDNode *CommandLineMetadata = 5658*7330f729Sjoerg TheModule.getOrInsertNamedMetadata("llvm.commandline"); 5659*7330f729Sjoerg std::string CommandLine = getCodeGenOpts().RecordCommandLine; 5660*7330f729Sjoerg llvm::LLVMContext &Ctx = TheModule.getContext(); 5661*7330f729Sjoerg 5662*7330f729Sjoerg llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; 5663*7330f729Sjoerg CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); 5664*7330f729Sjoerg } 5665*7330f729Sjoerg 5666*7330f729Sjoerg void CodeGenModule::EmitTargetMetadata() { 5667*7330f729Sjoerg // Warning, new MangledDeclNames may be appended within this loop. 5668*7330f729Sjoerg // We rely on MapVector insertions adding new elements to the end 5669*7330f729Sjoerg // of the container. 5670*7330f729Sjoerg // FIXME: Move this loop into the one target that needs it, and only 5671*7330f729Sjoerg // loop over those declarations for which we couldn't emit the target 5672*7330f729Sjoerg // metadata when we emitted the declaration. 5673*7330f729Sjoerg for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 5674*7330f729Sjoerg auto Val = *(MangledDeclNames.begin() + I); 5675*7330f729Sjoerg const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 5676*7330f729Sjoerg llvm::GlobalValue *GV = GetGlobalValue(Val.second); 5677*7330f729Sjoerg getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 5678*7330f729Sjoerg } 5679*7330f729Sjoerg } 5680*7330f729Sjoerg 5681*7330f729Sjoerg void CodeGenModule::EmitCoverageFile() { 5682*7330f729Sjoerg if (getCodeGenOpts().CoverageDataFile.empty() && 5683*7330f729Sjoerg getCodeGenOpts().CoverageNotesFile.empty()) 5684*7330f729Sjoerg return; 5685*7330f729Sjoerg 5686*7330f729Sjoerg llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 5687*7330f729Sjoerg if (!CUNode) 5688*7330f729Sjoerg return; 5689*7330f729Sjoerg 5690*7330f729Sjoerg llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 5691*7330f729Sjoerg llvm::LLVMContext &Ctx = TheModule.getContext(); 5692*7330f729Sjoerg auto *CoverageDataFile = 5693*7330f729Sjoerg llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 5694*7330f729Sjoerg auto *CoverageNotesFile = 5695*7330f729Sjoerg llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 5696*7330f729Sjoerg for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 5697*7330f729Sjoerg llvm::MDNode *CU = CUNode->getOperand(i); 5698*7330f729Sjoerg llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 5699*7330f729Sjoerg GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 5700*7330f729Sjoerg } 5701*7330f729Sjoerg } 5702*7330f729Sjoerg 5703*7330f729Sjoerg llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { 5704*7330f729Sjoerg // Sema has checked that all uuid strings are of the form 5705*7330f729Sjoerg // "12345678-1234-1234-1234-1234567890ab". 5706*7330f729Sjoerg assert(Uuid.size() == 36); 5707*7330f729Sjoerg for (unsigned i = 0; i < 36; ++i) { 5708*7330f729Sjoerg if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 5709*7330f729Sjoerg else assert(isHexDigit(Uuid[i])); 5710*7330f729Sjoerg } 5711*7330f729Sjoerg 5712*7330f729Sjoerg // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". 5713*7330f729Sjoerg const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 5714*7330f729Sjoerg 5715*7330f729Sjoerg llvm::Constant *Field3[8]; 5716*7330f729Sjoerg for (unsigned Idx = 0; Idx < 8; ++Idx) 5717*7330f729Sjoerg Field3[Idx] = llvm::ConstantInt::get( 5718*7330f729Sjoerg Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 5719*7330f729Sjoerg 5720*7330f729Sjoerg llvm::Constant *Fields[4] = { 5721*7330f729Sjoerg llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 5722*7330f729Sjoerg llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 5723*7330f729Sjoerg llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 5724*7330f729Sjoerg llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 5725*7330f729Sjoerg }; 5726*7330f729Sjoerg 5727*7330f729Sjoerg return llvm::ConstantStruct::getAnon(Fields); 5728*7330f729Sjoerg } 5729*7330f729Sjoerg 5730*7330f729Sjoerg llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 5731*7330f729Sjoerg bool ForEH) { 5732*7330f729Sjoerg // Return a bogus pointer if RTTI is disabled, unless it's for EH. 5733*7330f729Sjoerg // FIXME: should we even be calling this method if RTTI is disabled 5734*7330f729Sjoerg // and it's not for EH? 5735*7330f729Sjoerg if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice) 5736*7330f729Sjoerg return llvm::Constant::getNullValue(Int8PtrTy); 5737*7330f729Sjoerg 5738*7330f729Sjoerg if (ForEH && Ty->isObjCObjectPointerType() && 5739*7330f729Sjoerg LangOpts.ObjCRuntime.isGNUFamily()) 5740*7330f729Sjoerg return ObjCRuntime->GetEHType(Ty); 5741*7330f729Sjoerg 5742*7330f729Sjoerg return getCXXABI().getAddrOfRTTIDescriptor(Ty); 5743*7330f729Sjoerg } 5744*7330f729Sjoerg 5745*7330f729Sjoerg void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 5746*7330f729Sjoerg // Do not emit threadprivates in simd-only mode. 5747*7330f729Sjoerg if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 5748*7330f729Sjoerg return; 5749*7330f729Sjoerg for (auto RefExpr : D->varlists()) { 5750*7330f729Sjoerg auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 5751*7330f729Sjoerg bool PerformInit = 5752*7330f729Sjoerg VD->getAnyInitializer() && 5753*7330f729Sjoerg !VD->getAnyInitializer()->isConstantInitializer(getContext(), 5754*7330f729Sjoerg /*ForRef=*/false); 5755*7330f729Sjoerg 5756*7330f729Sjoerg Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 5757*7330f729Sjoerg if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 5758*7330f729Sjoerg VD, Addr, RefExpr->getBeginLoc(), PerformInit)) 5759*7330f729Sjoerg CXXGlobalInits.push_back(InitFunction); 5760*7330f729Sjoerg } 5761*7330f729Sjoerg } 5762*7330f729Sjoerg 5763*7330f729Sjoerg llvm::Metadata * 5764*7330f729Sjoerg CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 5765*7330f729Sjoerg StringRef Suffix) { 5766*7330f729Sjoerg llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; 5767*7330f729Sjoerg if (InternalId) 5768*7330f729Sjoerg return InternalId; 5769*7330f729Sjoerg 5770*7330f729Sjoerg if (isExternallyVisible(T->getLinkage())) { 5771*7330f729Sjoerg std::string OutName; 5772*7330f729Sjoerg llvm::raw_string_ostream Out(OutName); 5773*7330f729Sjoerg getCXXABI().getMangleContext().mangleTypeName(T, Out); 5774*7330f729Sjoerg Out << Suffix; 5775*7330f729Sjoerg 5776*7330f729Sjoerg InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 5777*7330f729Sjoerg } else { 5778*7330f729Sjoerg InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 5779*7330f729Sjoerg llvm::ArrayRef<llvm::Metadata *>()); 5780*7330f729Sjoerg } 5781*7330f729Sjoerg 5782*7330f729Sjoerg return InternalId; 5783*7330f729Sjoerg } 5784*7330f729Sjoerg 5785*7330f729Sjoerg llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 5786*7330f729Sjoerg return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); 5787*7330f729Sjoerg } 5788*7330f729Sjoerg 5789*7330f729Sjoerg llvm::Metadata * 5790*7330f729Sjoerg CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { 5791*7330f729Sjoerg return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); 5792*7330f729Sjoerg } 5793*7330f729Sjoerg 5794*7330f729Sjoerg // Generalize pointer types to a void pointer with the qualifiers of the 5795*7330f729Sjoerg // originally pointed-to type, e.g. 'const char *' and 'char * const *' 5796*7330f729Sjoerg // generalize to 'const void *' while 'char *' and 'const char **' generalize to 5797*7330f729Sjoerg // 'void *'. 5798*7330f729Sjoerg static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 5799*7330f729Sjoerg if (!Ty->isPointerType()) 5800*7330f729Sjoerg return Ty; 5801*7330f729Sjoerg 5802*7330f729Sjoerg return Ctx.getPointerType( 5803*7330f729Sjoerg QualType(Ctx.VoidTy).withCVRQualifiers( 5804*7330f729Sjoerg Ty->getPointeeType().getCVRQualifiers())); 5805*7330f729Sjoerg } 5806*7330f729Sjoerg 5807*7330f729Sjoerg // Apply type generalization to a FunctionType's return and argument types 5808*7330f729Sjoerg static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 5809*7330f729Sjoerg if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 5810*7330f729Sjoerg SmallVector<QualType, 8> GeneralizedParams; 5811*7330f729Sjoerg for (auto &Param : FnType->param_types()) 5812*7330f729Sjoerg GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 5813*7330f729Sjoerg 5814*7330f729Sjoerg return Ctx.getFunctionType( 5815*7330f729Sjoerg GeneralizeType(Ctx, FnType->getReturnType()), 5816*7330f729Sjoerg GeneralizedParams, FnType->getExtProtoInfo()); 5817*7330f729Sjoerg } 5818*7330f729Sjoerg 5819*7330f729Sjoerg if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 5820*7330f729Sjoerg return Ctx.getFunctionNoProtoType( 5821*7330f729Sjoerg GeneralizeType(Ctx, FnType->getReturnType())); 5822*7330f729Sjoerg 5823*7330f729Sjoerg llvm_unreachable("Encountered unknown FunctionType"); 5824*7330f729Sjoerg } 5825*7330f729Sjoerg 5826*7330f729Sjoerg llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 5827*7330f729Sjoerg return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), 5828*7330f729Sjoerg GeneralizedMetadataIdMap, ".generalized"); 5829*7330f729Sjoerg } 5830*7330f729Sjoerg 5831*7330f729Sjoerg /// Returns whether this module needs the "all-vtables" type identifier. 5832*7330f729Sjoerg bool CodeGenModule::NeedAllVtablesTypeId() const { 5833*7330f729Sjoerg // Returns true if at least one of vtable-based CFI checkers is enabled and 5834*7330f729Sjoerg // is not in the trapping mode. 5835*7330f729Sjoerg return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 5836*7330f729Sjoerg !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 5837*7330f729Sjoerg (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 5838*7330f729Sjoerg !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 5839*7330f729Sjoerg (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 5840*7330f729Sjoerg !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 5841*7330f729Sjoerg (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 5842*7330f729Sjoerg !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 5843*7330f729Sjoerg } 5844*7330f729Sjoerg 5845*7330f729Sjoerg void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 5846*7330f729Sjoerg CharUnits Offset, 5847*7330f729Sjoerg const CXXRecordDecl *RD) { 5848*7330f729Sjoerg llvm::Metadata *MD = 5849*7330f729Sjoerg CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 5850*7330f729Sjoerg VTable->addTypeMetadata(Offset.getQuantity(), MD); 5851*7330f729Sjoerg 5852*7330f729Sjoerg if (CodeGenOpts.SanitizeCfiCrossDso) 5853*7330f729Sjoerg if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 5854*7330f729Sjoerg VTable->addTypeMetadata(Offset.getQuantity(), 5855*7330f729Sjoerg llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 5856*7330f729Sjoerg 5857*7330f729Sjoerg if (NeedAllVtablesTypeId()) { 5858*7330f729Sjoerg llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 5859*7330f729Sjoerg VTable->addTypeMetadata(Offset.getQuantity(), MD); 5860*7330f729Sjoerg } 5861*7330f729Sjoerg } 5862*7330f729Sjoerg 5863*7330f729Sjoerg TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) { 5864*7330f729Sjoerg assert(TD != nullptr); 5865*7330f729Sjoerg TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); 5866*7330f729Sjoerg 5867*7330f729Sjoerg ParsedAttr.Features.erase( 5868*7330f729Sjoerg llvm::remove_if(ParsedAttr.Features, 5869*7330f729Sjoerg [&](const std::string &Feat) { 5870*7330f729Sjoerg return !Target.isValidFeatureName( 5871*7330f729Sjoerg StringRef{Feat}.substr(1)); 5872*7330f729Sjoerg }), 5873*7330f729Sjoerg ParsedAttr.Features.end()); 5874*7330f729Sjoerg return ParsedAttr; 5875*7330f729Sjoerg } 5876*7330f729Sjoerg 5877*7330f729Sjoerg 5878*7330f729Sjoerg // Fills in the supplied string map with the set of target features for the 5879*7330f729Sjoerg // passed in function. 5880*7330f729Sjoerg void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 5881*7330f729Sjoerg GlobalDecl GD) { 5882*7330f729Sjoerg StringRef TargetCPU = Target.getTargetOpts().CPU; 5883*7330f729Sjoerg const FunctionDecl *FD = GD.getDecl()->getAsFunction(); 5884*7330f729Sjoerg if (const auto *TD = FD->getAttr<TargetAttr>()) { 5885*7330f729Sjoerg TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD); 5886*7330f729Sjoerg 5887*7330f729Sjoerg // Make a copy of the features as passed on the command line into the 5888*7330f729Sjoerg // beginning of the additional features from the function to override. 5889*7330f729Sjoerg ParsedAttr.Features.insert(ParsedAttr.Features.begin(), 5890*7330f729Sjoerg Target.getTargetOpts().FeaturesAsWritten.begin(), 5891*7330f729Sjoerg Target.getTargetOpts().FeaturesAsWritten.end()); 5892*7330f729Sjoerg 5893*7330f729Sjoerg if (ParsedAttr.Architecture != "" && 5894*7330f729Sjoerg Target.isValidCPUName(ParsedAttr.Architecture)) 5895*7330f729Sjoerg TargetCPU = ParsedAttr.Architecture; 5896*7330f729Sjoerg 5897*7330f729Sjoerg // Now populate the feature map, first with the TargetCPU which is either 5898*7330f729Sjoerg // the default or a new one from the target attribute string. Then we'll use 5899*7330f729Sjoerg // the passed in features (FeaturesAsWritten) along with the new ones from 5900*7330f729Sjoerg // the attribute. 5901*7330f729Sjoerg Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 5902*7330f729Sjoerg ParsedAttr.Features); 5903*7330f729Sjoerg } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) { 5904*7330f729Sjoerg llvm::SmallVector<StringRef, 32> FeaturesTmp; 5905*7330f729Sjoerg Target.getCPUSpecificCPUDispatchFeatures( 5906*7330f729Sjoerg SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp); 5907*7330f729Sjoerg std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end()); 5908*7330f729Sjoerg Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features); 5909*7330f729Sjoerg } else { 5910*7330f729Sjoerg Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 5911*7330f729Sjoerg Target.getTargetOpts().Features); 5912*7330f729Sjoerg } 5913*7330f729Sjoerg } 5914*7330f729Sjoerg 5915*7330f729Sjoerg llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 5916*7330f729Sjoerg if (!SanStats) 5917*7330f729Sjoerg SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule()); 5918*7330f729Sjoerg 5919*7330f729Sjoerg return *SanStats; 5920*7330f729Sjoerg } 5921*7330f729Sjoerg llvm::Value * 5922*7330f729Sjoerg CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 5923*7330f729Sjoerg CodeGenFunction &CGF) { 5924*7330f729Sjoerg llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 5925*7330f729Sjoerg auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 5926*7330f729Sjoerg auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 5927*7330f729Sjoerg return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy, 5928*7330f729Sjoerg "__translate_sampler_initializer"), 5929*7330f729Sjoerg {C}); 5930*7330f729Sjoerg } 5931