1f22ef01cSRoman Divacky //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 2f22ef01cSRoman Divacky // 3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure 4f22ef01cSRoman Divacky // 5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source 6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details. 7f22ef01cSRoman Divacky // 8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 9f22ef01cSRoman Divacky // 10f22ef01cSRoman Divacky // This coordinates the per-module state used while generating code. 11f22ef01cSRoman Divacky // 12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 13f22ef01cSRoman Divacky 14f22ef01cSRoman Divacky #include "CodeGenModule.h" 150623d748SDimitry Andric #include "CGBlocks.h" 166122f3e6SDimitry Andric #include "CGCUDARuntime.h" 17e580952dSDimitry Andric #include "CGCXXABI.h" 18139f7f9bSDimitry Andric #include "CGCall.h" 19139f7f9bSDimitry Andric #include "CGDebugInfo.h" 20f22ef01cSRoman Divacky #include "CGObjCRuntime.h" 216122f3e6SDimitry Andric #include "CGOpenCLRuntime.h" 2259d1ed5bSDimitry Andric #include "CGOpenMPRuntime.h" 23e7145dcbSDimitry Andric #include "CGOpenMPRuntimeNVPTX.h" 24139f7f9bSDimitry Andric #include "CodeGenFunction.h" 2559d1ed5bSDimitry Andric #include "CodeGenPGO.h" 269a199699SDimitry Andric #include "ConstantEmitter.h" 2739d628a0SDimitry Andric #include "CoverageMappingGen.h" 28f22ef01cSRoman Divacky #include "TargetInfo.h" 29f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h" 30f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h" 31f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h" 32139f7f9bSDimitry Andric #include "clang/AST/DeclObjC.h" 33ffd1746dSEd Schouten #include "clang/AST/DeclTemplate.h" 342754fe60SDimitry Andric #include "clang/AST/Mangle.h" 35f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h" 36f8254f43SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h" 37dff0c46cSDimitry Andric #include "clang/Basic/Builtins.h" 38139f7f9bSDimitry Andric #include "clang/Basic/CharInfo.h" 39f22ef01cSRoman Divacky #include "clang/Basic/Diagnostic.h" 40139f7f9bSDimitry Andric #include "clang/Basic/Module.h" 41f22ef01cSRoman Divacky #include "clang/Basic/SourceManager.h" 42f22ef01cSRoman Divacky #include "clang/Basic/TargetInfo.h" 43f785676fSDimitry Andric #include "clang/Basic/Version.h" 4420e90f04SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h" 45139f7f9bSDimitry Andric #include "clang/Frontend/CodeGenOptions.h" 46f785676fSDimitry Andric #include "clang/Sema/SemaDiagnostic.h" 47f22ef01cSRoman Divacky #include "llvm/ADT/Triple.h" 48d8866befSDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h" 4959d1ed5bSDimitry Andric #include "llvm/IR/CallSite.h" 50139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h" 51139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h" 52139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h" 53139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h" 54139f7f9bSDimitry Andric #include "llvm/IR/Module.h" 5559d1ed5bSDimitry Andric #include "llvm/ProfileData/InstrProfReader.h" 56139f7f9bSDimitry Andric #include "llvm/Support/ConvertUTF.h" 57f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h" 580623d748SDimitry Andric #include "llvm/Support/MD5.h" 59139f7f9bSDimitry Andric 60f22ef01cSRoman Divacky using namespace clang; 61f22ef01cSRoman Divacky using namespace CodeGen; 62f22ef01cSRoman Divacky 639a199699SDimitry Andric static llvm::cl::opt<bool> LimitedCoverage( 649a199699SDimitry Andric "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden, 659a199699SDimitry Andric llvm::cl::desc("Emit limited coverage mapping information (experimental)"), 669a199699SDimitry Andric llvm::cl::init(false)); 679a199699SDimitry Andric 686122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata"; 696122f3e6SDimitry Andric 7059d1ed5bSDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 71284c1978SDimitry Andric switch (CGM.getTarget().getCXXABI().getKind()) { 72139f7f9bSDimitry Andric case TargetCXXABI::GenericAArch64: 73139f7f9bSDimitry Andric case TargetCXXABI::GenericARM: 74139f7f9bSDimitry Andric case TargetCXXABI::iOS: 7559d1ed5bSDimitry Andric case TargetCXXABI::iOS64: 760623d748SDimitry Andric case TargetCXXABI::WatchOS: 77ef6fa9e2SDimitry Andric case TargetCXXABI::GenericMIPS: 78139f7f9bSDimitry Andric case TargetCXXABI::GenericItanium: 790623d748SDimitry Andric case TargetCXXABI::WebAssembly: 8059d1ed5bSDimitry Andric return CreateItaniumCXXABI(CGM); 81139f7f9bSDimitry Andric case TargetCXXABI::Microsoft: 8259d1ed5bSDimitry Andric return CreateMicrosoftCXXABI(CGM); 83e580952dSDimitry Andric } 84e580952dSDimitry Andric 85e580952dSDimitry Andric llvm_unreachable("invalid C++ ABI kind"); 86e580952dSDimitry Andric } 87e580952dSDimitry Andric 883dac3a9bSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO, 893dac3a9bSDimitry Andric const PreprocessorOptions &PPO, 903dac3a9bSDimitry Andric const CodeGenOptions &CGO, llvm::Module &M, 9139d628a0SDimitry Andric DiagnosticsEngine &diags, 9239d628a0SDimitry Andric CoverageSourceInfo *CoverageInfo) 933dac3a9bSDimitry Andric : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO), 943dac3a9bSDimitry Andric PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), 950623d748SDimitry Andric Target(C.getTargetInfo()), ABI(createCXXABI(*this)), 96e7145dcbSDimitry Andric VMContext(M.getContext()), Types(*this), VTables(*this), 97e7145dcbSDimitry Andric SanitizerMD(new SanitizerMetadata(*this)) { 98dff0c46cSDimitry Andric 99dff0c46cSDimitry Andric // Initialize the type cache. 100dff0c46cSDimitry Andric llvm::LLVMContext &LLVMContext = M.getContext(); 101dff0c46cSDimitry Andric VoidTy = llvm::Type::getVoidTy(LLVMContext); 102dff0c46cSDimitry Andric Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 103dff0c46cSDimitry Andric Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 104dff0c46cSDimitry Andric Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 105dff0c46cSDimitry Andric Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 10613ddaa84SDimitry Andric HalfTy = llvm::Type::getHalfTy(LLVMContext); 107dff0c46cSDimitry Andric FloatTy = llvm::Type::getFloatTy(LLVMContext); 108dff0c46cSDimitry Andric DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 109dff0c46cSDimitry Andric PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 110dff0c46cSDimitry Andric PointerAlignInBytes = 111dff0c46cSDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 11244290647SDimitry Andric SizeSizeInBytes = 11344290647SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); 1140623d748SDimitry Andric IntAlignInBytes = 1150623d748SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 116dff0c46cSDimitry Andric IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 11744290647SDimitry Andric IntPtrTy = llvm::IntegerType::get(LLVMContext, 11844290647SDimitry Andric C.getTargetInfo().getMaxPointerWidth()); 119dff0c46cSDimitry Andric Int8PtrTy = Int8Ty->getPointerTo(0); 120dff0c46cSDimitry Andric Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 1216bc11b14SDimitry Andric AllocaInt8PtrTy = Int8Ty->getPointerTo( 1226bc11b14SDimitry Andric M.getDataLayout().getAllocaAddrSpace()); 123d8866befSDimitry Andric ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); 124dff0c46cSDimitry Andric 125139f7f9bSDimitry Andric RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 12639d628a0SDimitry Andric BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC(); 127139f7f9bSDimitry Andric 128dff0c46cSDimitry Andric if (LangOpts.ObjC1) 1293b0f4066SDimitry Andric createObjCRuntime(); 130dff0c46cSDimitry Andric if (LangOpts.OpenCL) 1316122f3e6SDimitry Andric createOpenCLRuntime(); 13259d1ed5bSDimitry Andric if (LangOpts.OpenMP) 13359d1ed5bSDimitry Andric createOpenMPRuntime(); 134dff0c46cSDimitry Andric if (LangOpts.CUDA) 1356122f3e6SDimitry Andric createCUDARuntime(); 136f22ef01cSRoman Divacky 1377ae0e2c9SDimitry Andric // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 13839d628a0SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 1397ae0e2c9SDimitry Andric (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 1409a199699SDimitry Andric TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(), 141e7145dcbSDimitry Andric getCXXABI().getMangleContext())); 1422754fe60SDimitry Andric 1433b0f4066SDimitry Andric // If debug info or coverage generation is enabled, create the CGDebugInfo 1443b0f4066SDimitry Andric // object. 145e7145dcbSDimitry Andric if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo || 146e7145dcbSDimitry Andric CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) 147e7145dcbSDimitry Andric DebugInfo.reset(new CGDebugInfo(*this)); 1482754fe60SDimitry Andric 1492754fe60SDimitry Andric Block.GlobalUniqueCount = 0; 1502754fe60SDimitry Andric 1510623d748SDimitry Andric if (C.getLangOpts().ObjC1) 152e7145dcbSDimitry Andric ObjCData.reset(new ObjCEntrypoints()); 15359d1ed5bSDimitry Andric 154e7145dcbSDimitry Andric if (CodeGenOpts.hasProfileClangUse()) { 155e7145dcbSDimitry Andric auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 156e7145dcbSDimitry Andric CodeGenOpts.ProfileInstrumentUsePath); 157e7145dcbSDimitry Andric if (auto E = ReaderOrErr.takeError()) { 15859d1ed5bSDimitry Andric unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 1593dac3a9bSDimitry Andric "Could not read profile %0: %1"); 160e7145dcbSDimitry Andric llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { 161e7145dcbSDimitry Andric getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath 162e7145dcbSDimitry Andric << EI.message(); 163e7145dcbSDimitry Andric }); 16433956c43SDimitry Andric } else 16533956c43SDimitry Andric PGOReader = std::move(ReaderOrErr.get()); 16659d1ed5bSDimitry Andric } 16739d628a0SDimitry Andric 16839d628a0SDimitry Andric // If coverage mapping generation is enabled, create the 16939d628a0SDimitry Andric // CoverageMappingModuleGen object. 17039d628a0SDimitry Andric if (CodeGenOpts.CoverageMapping) 17139d628a0SDimitry Andric CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 172f22ef01cSRoman Divacky } 173f22ef01cSRoman Divacky 174e7145dcbSDimitry Andric CodeGenModule::~CodeGenModule() {} 175f22ef01cSRoman Divacky 176f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() { 1777ae0e2c9SDimitry Andric // This is just isGNUFamily(), but we want to force implementors of 1787ae0e2c9SDimitry Andric // new ABIs to decide how best to do this. 1797ae0e2c9SDimitry Andric switch (LangOpts.ObjCRuntime.getKind()) { 1807ae0e2c9SDimitry Andric case ObjCRuntime::GNUstep: 1817ae0e2c9SDimitry Andric case ObjCRuntime::GCC: 1827ae0e2c9SDimitry Andric case ObjCRuntime::ObjFW: 183e7145dcbSDimitry Andric ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 1847ae0e2c9SDimitry Andric return; 1857ae0e2c9SDimitry Andric 1867ae0e2c9SDimitry Andric case ObjCRuntime::FragileMacOSX: 1877ae0e2c9SDimitry Andric case ObjCRuntime::MacOSX: 1887ae0e2c9SDimitry Andric case ObjCRuntime::iOS: 1890623d748SDimitry Andric case ObjCRuntime::WatchOS: 190e7145dcbSDimitry Andric ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 1917ae0e2c9SDimitry Andric return; 1927ae0e2c9SDimitry Andric } 1937ae0e2c9SDimitry Andric llvm_unreachable("bad runtime kind"); 1946122f3e6SDimitry Andric } 1956122f3e6SDimitry Andric 1966122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() { 197e7145dcbSDimitry Andric OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 1986122f3e6SDimitry Andric } 1996122f3e6SDimitry Andric 20059d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() { 201e7145dcbSDimitry Andric // Select a specialized code generation class based on the target, if any. 202e7145dcbSDimitry Andric // If it does not exist use the default implementation. 20344290647SDimitry Andric switch (getTriple().getArch()) { 204e7145dcbSDimitry Andric case llvm::Triple::nvptx: 205e7145dcbSDimitry Andric case llvm::Triple::nvptx64: 206e7145dcbSDimitry Andric assert(getLangOpts().OpenMPIsDevice && 207e7145dcbSDimitry Andric "OpenMP NVPTX is only prepared to deal with device code."); 208e7145dcbSDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this)); 209e7145dcbSDimitry Andric break; 210e7145dcbSDimitry Andric default: 211e7145dcbSDimitry Andric OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 212e7145dcbSDimitry Andric break; 213e7145dcbSDimitry Andric } 21459d1ed5bSDimitry Andric } 21559d1ed5bSDimitry Andric 2166122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() { 217e7145dcbSDimitry Andric CUDARuntime.reset(CreateNVCUDARuntime(*this)); 218f22ef01cSRoman Divacky } 219f22ef01cSRoman Divacky 22039d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 22139d628a0SDimitry Andric Replacements[Name] = C; 22239d628a0SDimitry Andric } 22339d628a0SDimitry Andric 224f785676fSDimitry Andric void CodeGenModule::applyReplacements() { 2258f0fd8f6SDimitry Andric for (auto &I : Replacements) { 2268f0fd8f6SDimitry Andric StringRef MangledName = I.first(); 2278f0fd8f6SDimitry Andric llvm::Constant *Replacement = I.second; 228f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 229f785676fSDimitry Andric if (!Entry) 230f785676fSDimitry Andric continue; 23159d1ed5bSDimitry Andric auto *OldF = cast<llvm::Function>(Entry); 23259d1ed5bSDimitry Andric auto *NewF = dyn_cast<llvm::Function>(Replacement); 233f785676fSDimitry Andric if (!NewF) { 23459d1ed5bSDimitry Andric if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 23559d1ed5bSDimitry Andric NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 23659d1ed5bSDimitry Andric } else { 23759d1ed5bSDimitry Andric auto *CE = cast<llvm::ConstantExpr>(Replacement); 238f785676fSDimitry Andric assert(CE->getOpcode() == llvm::Instruction::BitCast || 239f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::GetElementPtr); 240f785676fSDimitry Andric NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 241f785676fSDimitry Andric } 24259d1ed5bSDimitry Andric } 243f785676fSDimitry Andric 244f785676fSDimitry Andric // Replace old with new, but keep the old order. 245f785676fSDimitry Andric OldF->replaceAllUsesWith(Replacement); 246f785676fSDimitry Andric if (NewF) { 247f785676fSDimitry Andric NewF->removeFromParent(); 2480623d748SDimitry Andric OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 2490623d748SDimitry Andric NewF); 250f785676fSDimitry Andric } 251f785676fSDimitry Andric OldF->eraseFromParent(); 252f785676fSDimitry Andric } 253f785676fSDimitry Andric } 254f785676fSDimitry Andric 2550623d748SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 2560623d748SDimitry Andric GlobalValReplacements.push_back(std::make_pair(GV, C)); 2570623d748SDimitry Andric } 2580623d748SDimitry Andric 2590623d748SDimitry Andric void CodeGenModule::applyGlobalValReplacements() { 2600623d748SDimitry Andric for (auto &I : GlobalValReplacements) { 2610623d748SDimitry Andric llvm::GlobalValue *GV = I.first; 2620623d748SDimitry Andric llvm::Constant *C = I.second; 2630623d748SDimitry Andric 2640623d748SDimitry Andric GV->replaceAllUsesWith(C); 2650623d748SDimitry Andric GV->eraseFromParent(); 2660623d748SDimitry Andric } 2670623d748SDimitry Andric } 2680623d748SDimitry Andric 26959d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a 27059d1ed5bSDimitry Andric // linear structure. 271e7145dcbSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal( 272e7145dcbSDimitry Andric const llvm::GlobalIndirectSymbol &GIS) { 273e7145dcbSDimitry Andric llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited; 274e7145dcbSDimitry Andric const llvm::Constant *C = &GIS; 27559d1ed5bSDimitry Andric for (;;) { 27659d1ed5bSDimitry Andric C = C->stripPointerCasts(); 27759d1ed5bSDimitry Andric if (auto *GO = dyn_cast<llvm::GlobalObject>(C)) 27859d1ed5bSDimitry Andric return GO; 27959d1ed5bSDimitry Andric // stripPointerCasts will not walk over weak aliases. 280e7145dcbSDimitry Andric auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C); 281e7145dcbSDimitry Andric if (!GIS2) 28259d1ed5bSDimitry Andric return nullptr; 283e7145dcbSDimitry Andric if (!Visited.insert(GIS2).second) 28459d1ed5bSDimitry Andric return nullptr; 285e7145dcbSDimitry Andric C = GIS2->getIndirectSymbol(); 28659d1ed5bSDimitry Andric } 28759d1ed5bSDimitry Andric } 28859d1ed5bSDimitry Andric 289f785676fSDimitry Andric void CodeGenModule::checkAliases() { 29059d1ed5bSDimitry Andric // Check if the constructed aliases are well formed. It is really unfortunate 29159d1ed5bSDimitry Andric // that we have to do this in CodeGen, but we only construct mangled names 29259d1ed5bSDimitry Andric // and aliases during codegen. 293f785676fSDimitry Andric bool Error = false; 29459d1ed5bSDimitry Andric DiagnosticsEngine &Diags = getDiags(); 2958f0fd8f6SDimitry Andric for (const GlobalDecl &GD : Aliases) { 29659d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 297e7145dcbSDimitry Andric SourceLocation Location; 298e7145dcbSDimitry Andric bool IsIFunc = D->hasAttr<IFuncAttr>(); 299e7145dcbSDimitry Andric if (const Attr *A = D->getDefiningAttr()) 300e7145dcbSDimitry Andric Location = A->getLocation(); 301e7145dcbSDimitry Andric else 302e7145dcbSDimitry Andric llvm_unreachable("Not an alias or ifunc?"); 303f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 304f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 305e7145dcbSDimitry Andric auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry); 30659d1ed5bSDimitry Andric const llvm::GlobalValue *GV = getAliasedGlobal(*Alias); 30759d1ed5bSDimitry Andric if (!GV) { 308f785676fSDimitry Andric Error = true; 309e7145dcbSDimitry Andric Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 31059d1ed5bSDimitry Andric } else if (GV->isDeclaration()) { 311f785676fSDimitry Andric Error = true; 312e7145dcbSDimitry Andric Diags.Report(Location, diag::err_alias_to_undefined) 313e7145dcbSDimitry Andric << IsIFunc << IsIFunc; 314e7145dcbSDimitry Andric } else if (IsIFunc) { 315e7145dcbSDimitry Andric // Check resolver function type. 316e7145dcbSDimitry Andric llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>( 317e7145dcbSDimitry Andric GV->getType()->getPointerElementType()); 318e7145dcbSDimitry Andric assert(FTy); 319e7145dcbSDimitry Andric if (!FTy->getReturnType()->isPointerTy()) 320e7145dcbSDimitry Andric Diags.Report(Location, diag::err_ifunc_resolver_return); 321e7145dcbSDimitry Andric if (FTy->getNumParams()) 322e7145dcbSDimitry Andric Diags.Report(Location, diag::err_ifunc_resolver_params); 32359d1ed5bSDimitry Andric } 32459d1ed5bSDimitry Andric 325e7145dcbSDimitry Andric llvm::Constant *Aliasee = Alias->getIndirectSymbol(); 32659d1ed5bSDimitry Andric llvm::GlobalValue *AliaseeGV; 32759d1ed5bSDimitry Andric if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 32859d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 32959d1ed5bSDimitry Andric else 33059d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 33159d1ed5bSDimitry Andric 33259d1ed5bSDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 33359d1ed5bSDimitry Andric StringRef AliasSection = SA->getName(); 33459d1ed5bSDimitry Andric if (AliasSection != AliaseeGV->getSection()) 33559d1ed5bSDimitry Andric Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 336e7145dcbSDimitry Andric << AliasSection << IsIFunc << IsIFunc; 33759d1ed5bSDimitry Andric } 33859d1ed5bSDimitry Andric 33959d1ed5bSDimitry Andric // We have to handle alias to weak aliases in here. LLVM itself disallows 34059d1ed5bSDimitry Andric // this since the object semantics would not match the IL one. For 34159d1ed5bSDimitry Andric // compatibility with gcc we implement it by just pointing the alias 34259d1ed5bSDimitry Andric // to its aliasee's aliasee. We also warn, since the user is probably 34359d1ed5bSDimitry Andric // expecting the link to be weak. 344e7145dcbSDimitry Andric if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) { 345e7145dcbSDimitry Andric if (GA->isInterposable()) { 346e7145dcbSDimitry Andric Diags.Report(Location, diag::warn_alias_to_weak_alias) 347e7145dcbSDimitry Andric << GV->getName() << GA->getName() << IsIFunc; 34859d1ed5bSDimitry Andric Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 349e7145dcbSDimitry Andric GA->getIndirectSymbol(), Alias->getType()); 350e7145dcbSDimitry Andric Alias->setIndirectSymbol(Aliasee); 35159d1ed5bSDimitry Andric } 352f785676fSDimitry Andric } 353f785676fSDimitry Andric } 354f785676fSDimitry Andric if (!Error) 355f785676fSDimitry Andric return; 356f785676fSDimitry Andric 3578f0fd8f6SDimitry Andric for (const GlobalDecl &GD : Aliases) { 358f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 359f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 360e7145dcbSDimitry Andric auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry); 361f785676fSDimitry Andric Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 362f785676fSDimitry Andric Alias->eraseFromParent(); 363f785676fSDimitry Andric } 364f785676fSDimitry Andric } 365f785676fSDimitry Andric 36659d1ed5bSDimitry Andric void CodeGenModule::clear() { 36759d1ed5bSDimitry Andric DeferredDeclsToEmit.clear(); 36833956c43SDimitry Andric if (OpenMPRuntime) 36933956c43SDimitry Andric OpenMPRuntime->clear(); 37059d1ed5bSDimitry Andric } 37159d1ed5bSDimitry Andric 37259d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 37359d1ed5bSDimitry Andric StringRef MainFile) { 37459d1ed5bSDimitry Andric if (!hasDiagnostics()) 37559d1ed5bSDimitry Andric return; 37659d1ed5bSDimitry Andric if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 37759d1ed5bSDimitry Andric if (MainFile.empty()) 37859d1ed5bSDimitry Andric MainFile = "<stdin>"; 37959d1ed5bSDimitry Andric Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 380f37b6182SDimitry Andric } else { 381f37b6182SDimitry Andric if (Mismatched > 0) 382f37b6182SDimitry Andric Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; 383f37b6182SDimitry Andric 384f37b6182SDimitry Andric if (Missing > 0) 385f37b6182SDimitry Andric Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; 386f37b6182SDimitry Andric } 38759d1ed5bSDimitry Andric } 38859d1ed5bSDimitry Andric 389f22ef01cSRoman Divacky void CodeGenModule::Release() { 390f22ef01cSRoman Divacky EmitDeferred(); 391f9448bf3SDimitry Andric EmitVTablesOpportunistically(); 3920623d748SDimitry Andric applyGlobalValReplacements(); 393f785676fSDimitry Andric applyReplacements(); 394f785676fSDimitry Andric checkAliases(); 395f22ef01cSRoman Divacky EmitCXXGlobalInitFunc(); 396f22ef01cSRoman Divacky EmitCXXGlobalDtorFunc(); 397284c1978SDimitry Andric EmitCXXThreadLocalInitFunc(); 3986122f3e6SDimitry Andric if (ObjCRuntime) 3996122f3e6SDimitry Andric if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 400f22ef01cSRoman Divacky AddGlobalCtor(ObjCInitFunction); 40133956c43SDimitry Andric if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice && 40233956c43SDimitry Andric CUDARuntime) { 40333956c43SDimitry Andric if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction()) 40433956c43SDimitry Andric AddGlobalCtor(CudaCtorFunction); 40533956c43SDimitry Andric if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction()) 40633956c43SDimitry Andric AddGlobalDtor(CudaDtorFunction); 40733956c43SDimitry Andric } 408ea942507SDimitry Andric if (OpenMPRuntime) 409ea942507SDimitry Andric if (llvm::Function *OpenMPRegistrationFunction = 410302affcbSDimitry Andric OpenMPRuntime->emitRegistrationFunction()) { 411302affcbSDimitry Andric auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ? 412302affcbSDimitry Andric OpenMPRegistrationFunction : nullptr; 413302affcbSDimitry Andric AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey); 414302affcbSDimitry Andric } 4150623d748SDimitry Andric if (PGOReader) { 416e7145dcbSDimitry Andric getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext)); 4170623d748SDimitry Andric if (PGOStats.hasDiagnostics()) 41859d1ed5bSDimitry Andric PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 4190623d748SDimitry Andric } 420f22ef01cSRoman Divacky EmitCtorList(GlobalCtors, "llvm.global_ctors"); 421f22ef01cSRoman Divacky EmitCtorList(GlobalDtors, "llvm.global_dtors"); 4226122f3e6SDimitry Andric EmitGlobalAnnotations(); 423284c1978SDimitry Andric EmitStaticExternCAliases(); 42439d628a0SDimitry Andric EmitDeferredUnusedCoverageMappings(); 42539d628a0SDimitry Andric if (CoverageMapping) 42639d628a0SDimitry Andric CoverageMapping->emit(); 42720e90f04SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 428e7145dcbSDimitry Andric CodeGenFunction(*this).EmitCfiCheckFail(); 42920e90f04SDimitry Andric CodeGenFunction(*this).EmitCfiCheckStub(); 43020e90f04SDimitry Andric } 43120e90f04SDimitry Andric emitAtAvailableLinkGuard(); 43259d1ed5bSDimitry Andric emitLLVMUsed(); 433e7145dcbSDimitry Andric if (SanStats) 434e7145dcbSDimitry Andric SanStats->finish(); 435ffd1746dSEd Schouten 436f785676fSDimitry Andric if (CodeGenOpts.Autolink && 437f785676fSDimitry Andric (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 438139f7f9bSDimitry Andric EmitModuleLinkOptions(); 439139f7f9bSDimitry Andric } 44020e90f04SDimitry Andric 44120e90f04SDimitry Andric // Record mregparm value now so it is visible through rest of codegen. 44220e90f04SDimitry Andric if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 44320e90f04SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", 44420e90f04SDimitry Andric CodeGenOpts.NumRegisterParameters); 44520e90f04SDimitry Andric 4460623d748SDimitry Andric if (CodeGenOpts.DwarfVersion) { 447f785676fSDimitry Andric // We actually want the latest version when there are conflicts. 448f785676fSDimitry Andric // We can change from Warning to Latest if such mode is supported. 449f785676fSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 450f785676fSDimitry Andric CodeGenOpts.DwarfVersion); 4510623d748SDimitry Andric } 4520623d748SDimitry Andric if (CodeGenOpts.EmitCodeView) { 4530623d748SDimitry Andric // Indicate that we want CodeView in the metadata. 4540623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 4550623d748SDimitry Andric } 4560623d748SDimitry Andric if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 4570623d748SDimitry Andric // We don't support LTO with 2 with different StrictVTablePointers 4580623d748SDimitry Andric // FIXME: we could support it by stripping all the information introduced 4590623d748SDimitry Andric // by StrictVTablePointers. 4600623d748SDimitry Andric 4610623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 4620623d748SDimitry Andric 4630623d748SDimitry Andric llvm::Metadata *Ops[2] = { 4640623d748SDimitry Andric llvm::MDString::get(VMContext, "StrictVTablePointers"), 4650623d748SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 4660623d748SDimitry Andric llvm::Type::getInt32Ty(VMContext), 1))}; 4670623d748SDimitry Andric 4680623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Require, 4690623d748SDimitry Andric "StrictVTablePointersRequirement", 4700623d748SDimitry Andric llvm::MDNode::get(VMContext, Ops)); 4710623d748SDimitry Andric } 472f785676fSDimitry Andric if (DebugInfo) 47359d1ed5bSDimitry Andric // We support a single version in the linked module. The LLVM 47459d1ed5bSDimitry Andric // parser will drop debug info with a different version number 47559d1ed5bSDimitry Andric // (and warn about it, too). 47659d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 477f785676fSDimitry Andric llvm::DEBUG_METADATA_VERSION); 478139f7f9bSDimitry Andric 47959d1ed5bSDimitry Andric // We need to record the widths of enums and wchar_t, so that we can generate 480d8866befSDimitry Andric // the correct build attributes in the ARM backend. wchar_size is also used by 481d8866befSDimitry Andric // TargetLibraryInfo. 4829a199699SDimitry Andric uint64_t WCharWidth = 4839a199699SDimitry Andric Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 484d8866befSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 485d8866befSDimitry Andric 48659d1ed5bSDimitry Andric llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 48759d1ed5bSDimitry Andric if ( Arch == llvm::Triple::arm 48859d1ed5bSDimitry Andric || Arch == llvm::Triple::armeb 48959d1ed5bSDimitry Andric || Arch == llvm::Triple::thumb 49059d1ed5bSDimitry Andric || Arch == llvm::Triple::thumbeb) { 49159d1ed5bSDimitry Andric // The minimum width of an enum in bytes 49259d1ed5bSDimitry Andric uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 49359d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 49459d1ed5bSDimitry Andric } 49559d1ed5bSDimitry Andric 4960623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 4970623d748SDimitry Andric // Indicate that we want cross-DSO control flow integrity checks. 4980623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 4990623d748SDimitry Andric } 5000623d748SDimitry Andric 50144290647SDimitry Andric if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { 502e7145dcbSDimitry Andric // Indicate whether __nvvm_reflect should be configured to flush denormal 503e7145dcbSDimitry Andric // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 504e7145dcbSDimitry Andric // property.) 505e7145dcbSDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 506e7145dcbSDimitry Andric LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0); 50739d628a0SDimitry Andric } 50839d628a0SDimitry Andric 509edd7eaddSDimitry Andric // Emit OpenCL specific module metadata: OpenCL/SPIR version. 510edd7eaddSDimitry Andric if (LangOpts.OpenCL) { 511edd7eaddSDimitry Andric EmitOpenCLMetadata(); 512edd7eaddSDimitry Andric // Emit SPIR version. 513edd7eaddSDimitry Andric if (getTriple().getArch() == llvm::Triple::spir || 514edd7eaddSDimitry Andric getTriple().getArch() == llvm::Triple::spir64) { 515edd7eaddSDimitry Andric // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the 516edd7eaddSDimitry Andric // opencl.spir.version named metadata. 517edd7eaddSDimitry Andric llvm::Metadata *SPIRVerElts[] = { 518edd7eaddSDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 519edd7eaddSDimitry Andric Int32Ty, LangOpts.OpenCLVersion / 100)), 520edd7eaddSDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 521edd7eaddSDimitry Andric Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))}; 522edd7eaddSDimitry Andric llvm::NamedMDNode *SPIRVerMD = 523edd7eaddSDimitry Andric TheModule.getOrInsertNamedMetadata("opencl.spir.version"); 524edd7eaddSDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 525edd7eaddSDimitry Andric SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts)); 526edd7eaddSDimitry Andric } 527edd7eaddSDimitry Andric } 528edd7eaddSDimitry Andric 529e7145dcbSDimitry Andric if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 530e7145dcbSDimitry Andric assert(PLevel < 3 && "Invalid PIC Level"); 531e7145dcbSDimitry Andric getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 532e7145dcbSDimitry Andric if (Context.getLangOpts().PIE) 533e7145dcbSDimitry Andric getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 53439d628a0SDimitry Andric } 53539d628a0SDimitry Andric 5362754fe60SDimitry Andric SimplifyPersonality(); 5372754fe60SDimitry Andric 538ffd1746dSEd Schouten if (getCodeGenOpts().EmitDeclMetadata) 539ffd1746dSEd Schouten EmitDeclMetadata(); 540bd5abe19SDimitry Andric 541bd5abe19SDimitry Andric if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 542bd5abe19SDimitry Andric EmitCoverageFile(); 5436122f3e6SDimitry Andric 5446122f3e6SDimitry Andric if (DebugInfo) 5456122f3e6SDimitry Andric DebugInfo->finalize(); 546f785676fSDimitry Andric 547f785676fSDimitry Andric EmitVersionIdentMetadata(); 54859d1ed5bSDimitry Andric 54959d1ed5bSDimitry Andric EmitTargetMetadata(); 550f22ef01cSRoman Divacky } 551f22ef01cSRoman Divacky 552edd7eaddSDimitry Andric void CodeGenModule::EmitOpenCLMetadata() { 553edd7eaddSDimitry Andric // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the 554edd7eaddSDimitry Andric // opencl.ocl.version named metadata node. 555edd7eaddSDimitry Andric llvm::Metadata *OCLVerElts[] = { 556edd7eaddSDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 557edd7eaddSDimitry Andric Int32Ty, LangOpts.OpenCLVersion / 100)), 558edd7eaddSDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 559edd7eaddSDimitry Andric Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))}; 560edd7eaddSDimitry Andric llvm::NamedMDNode *OCLVerMD = 561edd7eaddSDimitry Andric TheModule.getOrInsertNamedMetadata("opencl.ocl.version"); 562edd7eaddSDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 563edd7eaddSDimitry Andric OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts)); 564edd7eaddSDimitry Andric } 565edd7eaddSDimitry Andric 5663b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 5673b0f4066SDimitry Andric // Make sure that this type is translated. 5683b0f4066SDimitry Andric Types.UpdateCompletedType(TD); 5693b0f4066SDimitry Andric } 5703b0f4066SDimitry Andric 571e7145dcbSDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 572e7145dcbSDimitry Andric // Make sure that this type is translated. 573e7145dcbSDimitry Andric Types.RefreshTypeCacheForClass(RD); 574e7145dcbSDimitry Andric } 575e7145dcbSDimitry Andric 5769a199699SDimitry Andric llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) { 5772754fe60SDimitry Andric if (!TBAA) 57859d1ed5bSDimitry Andric return nullptr; 5799a199699SDimitry Andric return TBAA->getTypeInfo(QTy); 5802754fe60SDimitry Andric } 5812754fe60SDimitry Andric 5829a199699SDimitry Andric TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { 5839a199699SDimitry Andric // Pointee values may have incomplete types, but they shall never be 5849a199699SDimitry Andric // dereferenced. 5859a199699SDimitry Andric if (AccessType->isIncompleteType()) 5869a199699SDimitry Andric return TBAAAccessInfo::getIncompleteInfo(); 5879a199699SDimitry Andric 5889a199699SDimitry Andric uint64_t Size = Context.getTypeSizeInChars(AccessType).getQuantity(); 5899a199699SDimitry Andric return TBAAAccessInfo(getTBAATypeInfo(AccessType), Size); 5909a199699SDimitry Andric } 5919a199699SDimitry Andric 5929a199699SDimitry Andric TBAAAccessInfo 5939a199699SDimitry Andric CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) { 594dff0c46cSDimitry Andric if (!TBAA) 5959a199699SDimitry Andric return TBAAAccessInfo(); 5969a199699SDimitry Andric return TBAA->getVTablePtrAccessInfo(VTablePtrType); 597dff0c46cSDimitry Andric } 598dff0c46cSDimitry Andric 5993861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 6003861d79fSDimitry Andric if (!TBAA) 60159d1ed5bSDimitry Andric return nullptr; 6023861d79fSDimitry Andric return TBAA->getTBAAStructInfo(QTy); 6033861d79fSDimitry Andric } 6043861d79fSDimitry Andric 6059a199699SDimitry Andric llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { 606139f7f9bSDimitry Andric if (!TBAA) 60759d1ed5bSDimitry Andric return nullptr; 6089a199699SDimitry Andric return TBAA->getBaseTypeInfo(QTy); 609139f7f9bSDimitry Andric } 610139f7f9bSDimitry Andric 6119a199699SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { 6129a199699SDimitry Andric if (!TBAA) 6139a199699SDimitry Andric return nullptr; 6149a199699SDimitry Andric return TBAA->getAccessTagInfo(Info); 6159a199699SDimitry Andric } 6169a199699SDimitry Andric 6179a199699SDimitry Andric TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 6189a199699SDimitry Andric TBAAAccessInfo TargetInfo) { 6199a199699SDimitry Andric if (!TBAA) 6209a199699SDimitry Andric return TBAAAccessInfo(); 6219a199699SDimitry Andric return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo); 6229a199699SDimitry Andric } 6239a199699SDimitry Andric 6249a199699SDimitry Andric TBAAAccessInfo 6259a199699SDimitry Andric CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, 6269a199699SDimitry Andric TBAAAccessInfo InfoB) { 6279a199699SDimitry Andric if (!TBAA) 6289a199699SDimitry Andric return TBAAAccessInfo(); 6299a199699SDimitry Andric return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB); 6309a199699SDimitry Andric } 6319a199699SDimitry Andric 6320623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 6339a199699SDimitry Andric TBAAAccessInfo TBAAInfo) { 6349a199699SDimitry Andric if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo)) 6359a199699SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag); 6362754fe60SDimitry Andric } 6372754fe60SDimitry Andric 6380623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup( 6390623d748SDimitry Andric llvm::Instruction *I, const CXXRecordDecl *RD) { 64051690af2SDimitry Andric I->setMetadata(llvm::LLVMContext::MD_invariant_group, 64151690af2SDimitry Andric llvm::MDNode::get(getLLVMContext(), {})); 6420623d748SDimitry Andric } 6430623d748SDimitry Andric 64459d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) { 64559d1ed5bSDimitry Andric unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 64659d1ed5bSDimitry Andric getDiags().Report(Context.getFullLoc(loc), diagID) << message; 647f22ef01cSRoman Divacky } 648f22ef01cSRoman Divacky 649f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 650f22ef01cSRoman Divacky /// specified stmt yet. 651f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 6526122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 653f22ef01cSRoman Divacky "cannot compile this %0 yet"); 654f22ef01cSRoman Divacky std::string Msg = Type; 655f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 656f22ef01cSRoman Divacky << Msg << S->getSourceRange(); 657f22ef01cSRoman Divacky } 658f22ef01cSRoman Divacky 659f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 660f22ef01cSRoman Divacky /// specified decl yet. 661f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 6626122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 663f22ef01cSRoman Divacky "cannot compile this %0 yet"); 664f22ef01cSRoman Divacky std::string Msg = Type; 665f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 666f22ef01cSRoman Divacky } 667f22ef01cSRoman Divacky 66817a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 66917a519f9SDimitry Andric return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 67017a519f9SDimitry Andric } 67117a519f9SDimitry Andric 672f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 6739a199699SDimitry Andric const NamedDecl *D, 6749a199699SDimitry Andric ForDefinition_t IsForDefinition) const { 675f22ef01cSRoman Divacky // Internal definitions always have default visibility. 676f22ef01cSRoman Divacky if (GV->hasLocalLinkage()) { 677f22ef01cSRoman Divacky GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 678f22ef01cSRoman Divacky return; 679f22ef01cSRoman Divacky } 680f22ef01cSRoman Divacky 6812754fe60SDimitry Andric // Set visibility for definitions. 682139f7f9bSDimitry Andric LinkageInfo LV = D->getLinkageAndVisibility(); 6839a199699SDimitry Andric if (LV.isVisibilityExplicit() || 6849a199699SDimitry Andric (IsForDefinition && !GV->hasAvailableExternallyLinkage())) 685139f7f9bSDimitry Andric GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 686f22ef01cSRoman Divacky } 687f22ef01cSRoman Divacky 6887ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 6897ae0e2c9SDimitry Andric return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 6907ae0e2c9SDimitry Andric .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 6917ae0e2c9SDimitry Andric .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 6927ae0e2c9SDimitry Andric .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 6937ae0e2c9SDimitry Andric .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 6947ae0e2c9SDimitry Andric } 6957ae0e2c9SDimitry Andric 6967ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 6977ae0e2c9SDimitry Andric CodeGenOptions::TLSModel M) { 6987ae0e2c9SDimitry Andric switch (M) { 6997ae0e2c9SDimitry Andric case CodeGenOptions::GeneralDynamicTLSModel: 7007ae0e2c9SDimitry Andric return llvm::GlobalVariable::GeneralDynamicTLSModel; 7017ae0e2c9SDimitry Andric case CodeGenOptions::LocalDynamicTLSModel: 7027ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalDynamicTLSModel; 7037ae0e2c9SDimitry Andric case CodeGenOptions::InitialExecTLSModel: 7047ae0e2c9SDimitry Andric return llvm::GlobalVariable::InitialExecTLSModel; 7057ae0e2c9SDimitry Andric case CodeGenOptions::LocalExecTLSModel: 7067ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalExecTLSModel; 7077ae0e2c9SDimitry Andric } 7087ae0e2c9SDimitry Andric llvm_unreachable("Invalid TLS model!"); 7097ae0e2c9SDimitry Andric } 7107ae0e2c9SDimitry Andric 71139d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 712284c1978SDimitry Andric assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 7137ae0e2c9SDimitry Andric 71439d628a0SDimitry Andric llvm::GlobalValue::ThreadLocalMode TLM; 7153861d79fSDimitry Andric TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 7167ae0e2c9SDimitry Andric 7177ae0e2c9SDimitry Andric // Override the TLS model if it is explicitly specified. 71859d1ed5bSDimitry Andric if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 7197ae0e2c9SDimitry Andric TLM = GetLLVMTLSModel(Attr->getModel()); 7207ae0e2c9SDimitry Andric } 7217ae0e2c9SDimitry Andric 7227ae0e2c9SDimitry Andric GV->setThreadLocalMode(TLM); 7237ae0e2c9SDimitry Andric } 7247ae0e2c9SDimitry Andric 7256122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 726444ed5c5SDimitry Andric GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 727444ed5c5SDimitry Andric 728444ed5c5SDimitry Andric // Some ABIs don't have constructor variants. Make sure that base and 729444ed5c5SDimitry Andric // complete constructors get mangled the same. 730444ed5c5SDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 731444ed5c5SDimitry Andric if (!getTarget().getCXXABI().hasConstructorVariants()) { 732444ed5c5SDimitry Andric CXXCtorType OrigCtorType = GD.getCtorType(); 733444ed5c5SDimitry Andric assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 734444ed5c5SDimitry Andric if (OrigCtorType == Ctor_Base) 735444ed5c5SDimitry Andric CanonicalGD = GlobalDecl(CD, Ctor_Complete); 736444ed5c5SDimitry Andric } 737444ed5c5SDimitry Andric } 738444ed5c5SDimitry Andric 7399a199699SDimitry Andric auto FoundName = MangledDeclNames.find(CanonicalGD); 7409a199699SDimitry Andric if (FoundName != MangledDeclNames.end()) 7419a199699SDimitry Andric return FoundName->second; 742f22ef01cSRoman Divacky 74359d1ed5bSDimitry Andric const auto *ND = cast<NamedDecl>(GD.getDecl()); 744dff0c46cSDimitry Andric SmallString<256> Buffer; 74559d1ed5bSDimitry Andric StringRef Str; 74659d1ed5bSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 7472754fe60SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 74859d1ed5bSDimitry Andric if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) 7492754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 75059d1ed5bSDimitry Andric else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) 7512754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 752ffd1746dSEd Schouten else 7532754fe60SDimitry Andric getCXXABI().getMangleContext().mangleName(ND, Out); 75459d1ed5bSDimitry Andric Str = Out.str(); 75559d1ed5bSDimitry Andric } else { 75659d1ed5bSDimitry Andric IdentifierInfo *II = ND->getIdentifier(); 75759d1ed5bSDimitry Andric assert(II && "Attempt to mangle unnamed decl."); 75844290647SDimitry Andric const auto *FD = dyn_cast<FunctionDecl>(ND); 75944290647SDimitry Andric 76044290647SDimitry Andric if (FD && 76144290647SDimitry Andric FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 76244290647SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 76344290647SDimitry Andric Out << "__regcall3__" << II->getName(); 76444290647SDimitry Andric Str = Out.str(); 76544290647SDimitry Andric } else { 76659d1ed5bSDimitry Andric Str = II->getName(); 767ffd1746dSEd Schouten } 76844290647SDimitry Andric } 769ffd1746dSEd Schouten 77039d628a0SDimitry Andric // Keep the first result in the case of a mangling collision. 77139d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Str, GD)); 7729a199699SDimitry Andric return MangledDeclNames[CanonicalGD] = Result.first->first(); 77359d1ed5bSDimitry Andric } 77459d1ed5bSDimitry Andric 77559d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 776ffd1746dSEd Schouten const BlockDecl *BD) { 7772754fe60SDimitry Andric MangleContext &MangleCtx = getCXXABI().getMangleContext(); 7782754fe60SDimitry Andric const Decl *D = GD.getDecl(); 77959d1ed5bSDimitry Andric 78059d1ed5bSDimitry Andric SmallString<256> Buffer; 78159d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(Buffer); 78259d1ed5bSDimitry Andric if (!D) 7837ae0e2c9SDimitry Andric MangleCtx.mangleGlobalBlock(BD, 7847ae0e2c9SDimitry Andric dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 78559d1ed5bSDimitry Andric else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 7862754fe60SDimitry Andric MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 78759d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 7882754fe60SDimitry Andric MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 7892754fe60SDimitry Andric else 7902754fe60SDimitry Andric MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 79159d1ed5bSDimitry Andric 79239d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 79339d628a0SDimitry Andric return Result.first->first(); 794f22ef01cSRoman Divacky } 795f22ef01cSRoman Divacky 7966122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 797f22ef01cSRoman Divacky return getModule().getNamedValue(Name); 798f22ef01cSRoman Divacky } 799f22ef01cSRoman Divacky 800f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before 801f22ef01cSRoman Divacky /// main() runs. 80259d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 80359d1ed5bSDimitry Andric llvm::Constant *AssociatedData) { 804f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 80559d1ed5bSDimitry Andric GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 806f22ef01cSRoman Divacky } 807f22ef01cSRoman Divacky 808f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called 809f22ef01cSRoman Divacky /// when the module is unloaded. 810f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) { 811f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 81259d1ed5bSDimitry Andric GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 813f22ef01cSRoman Divacky } 814f22ef01cSRoman Divacky 81544290647SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 81644290647SDimitry Andric if (Fns.empty()) return; 81744290647SDimitry Andric 818f22ef01cSRoman Divacky // Ctor function type is void()*. 819bd5abe19SDimitry Andric llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 820f22ef01cSRoman Divacky llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 821f22ef01cSRoman Divacky 82259d1ed5bSDimitry Andric // Get the type of a ctor entry, { i32, void ()*, i8* }. 82359d1ed5bSDimitry Andric llvm::StructType *CtorStructTy = llvm::StructType::get( 8245517e702SDimitry Andric Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy); 825f22ef01cSRoman Divacky 826f22ef01cSRoman Divacky // Construct the constructor and destructor arrays. 82744290647SDimitry Andric ConstantInitBuilder builder(*this); 82844290647SDimitry Andric auto ctors = builder.beginArray(CtorStructTy); 8298f0fd8f6SDimitry Andric for (const auto &I : Fns) { 83044290647SDimitry Andric auto ctor = ctors.beginStruct(CtorStructTy); 83144290647SDimitry Andric ctor.addInt(Int32Ty, I.Priority); 83244290647SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); 83344290647SDimitry Andric if (I.AssociatedData) 83444290647SDimitry Andric ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); 83544290647SDimitry Andric else 83644290647SDimitry Andric ctor.addNullPointer(VoidPtrTy); 83744290647SDimitry Andric ctor.finishAndAddTo(ctors); 838f22ef01cSRoman Divacky } 839f22ef01cSRoman Divacky 84044290647SDimitry Andric auto list = 84144290647SDimitry Andric ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 84244290647SDimitry Andric /*constant*/ false, 84344290647SDimitry Andric llvm::GlobalValue::AppendingLinkage); 84444290647SDimitry Andric 84544290647SDimitry Andric // The LTO linker doesn't seem to like it when we set an alignment 84644290647SDimitry Andric // on appending variables. Take it off as a workaround. 84744290647SDimitry Andric list->setAlignment(0); 84844290647SDimitry Andric 84944290647SDimitry Andric Fns.clear(); 850f22ef01cSRoman Divacky } 851f22ef01cSRoman Divacky 852f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes 853f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 85459d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 855f785676fSDimitry Andric 856e580952dSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 857f22ef01cSRoman Divacky 85859d1ed5bSDimitry Andric if (isa<CXXDestructorDecl>(D) && 85959d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 86059d1ed5bSDimitry Andric GD.getDtorType())) { 86159d1ed5bSDimitry Andric // Destructor variants in the Microsoft C++ ABI are always internal or 86259d1ed5bSDimitry Andric // linkonce_odr thunks emitted on an as-needed basis. 86359d1ed5bSDimitry Andric return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage 86459d1ed5bSDimitry Andric : llvm::GlobalValue::LinkOnceODRLinkage; 865f22ef01cSRoman Divacky } 866f22ef01cSRoman Divacky 867e7145dcbSDimitry Andric if (isa<CXXConstructorDecl>(D) && 868e7145dcbSDimitry Andric cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 869e7145dcbSDimitry Andric Context.getTargetInfo().getCXXABI().isMicrosoft()) { 870e7145dcbSDimitry Andric // Our approach to inheriting constructors is fundamentally different from 871e7145dcbSDimitry Andric // that used by the MS ABI, so keep our inheriting constructor thunks 872e7145dcbSDimitry Andric // internal rather than trying to pick an unambiguous mangling for them. 873e7145dcbSDimitry Andric return llvm::GlobalValue::InternalLinkage; 874e7145dcbSDimitry Andric } 875e7145dcbSDimitry Andric 87659d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false); 87759d1ed5bSDimitry Andric } 878f22ef01cSRoman Divacky 87997bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) { 88097bc6c73SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 88197bc6c73SDimitry Andric 88297bc6c73SDimitry Andric if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) { 88397bc6c73SDimitry Andric if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) { 88497bc6c73SDimitry Andric // Don't dllexport/import destructor thunks. 88597bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 88697bc6c73SDimitry Andric return; 88797bc6c73SDimitry Andric } 88897bc6c73SDimitry Andric } 88997bc6c73SDimitry Andric 89097bc6c73SDimitry Andric if (FD->hasAttr<DLLImportAttr>()) 89197bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 89297bc6c73SDimitry Andric else if (FD->hasAttr<DLLExportAttr>()) 89397bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 89497bc6c73SDimitry Andric else 89597bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 89697bc6c73SDimitry Andric } 89797bc6c73SDimitry Andric 898e7145dcbSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 8990623d748SDimitry Andric llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 9000623d748SDimitry Andric if (!MDS) return nullptr; 9010623d748SDimitry Andric 90244290647SDimitry Andric return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 9030623d748SDimitry Andric } 9040623d748SDimitry Andric 90559d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D, 90659d1ed5bSDimitry Andric llvm::Function *F) { 90759d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 908f22ef01cSRoman Divacky } 909f22ef01cSRoman Divacky 910f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 911f22ef01cSRoman Divacky const CGFunctionInfo &Info, 912f22ef01cSRoman Divacky llvm::Function *F) { 913f22ef01cSRoman Divacky unsigned CallingConv; 9146bc11b14SDimitry Andric llvm::AttributeList PAL; 9156bc11b14SDimitry Andric ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false); 9166bc11b14SDimitry Andric F->setAttributes(PAL); 917f22ef01cSRoman Divacky F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 918f22ef01cSRoman Divacky } 919f22ef01cSRoman Divacky 9206122f3e6SDimitry Andric /// Determines whether the language options require us to model 9216122f3e6SDimitry Andric /// unwind exceptions. We treat -fexceptions as mandating this 9226122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions 9236122f3e6SDimitry Andric /// enabled. This means, for example, that C with -fexceptions 9246122f3e6SDimitry Andric /// enables this. 925dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) { 9266122f3e6SDimitry Andric // If exceptions are completely disabled, obviously this is false. 927dff0c46cSDimitry Andric if (!LangOpts.Exceptions) return false; 9286122f3e6SDimitry Andric 9296122f3e6SDimitry Andric // If C++ exceptions are enabled, this is true. 930dff0c46cSDimitry Andric if (LangOpts.CXXExceptions) return true; 9316122f3e6SDimitry Andric 9326122f3e6SDimitry Andric // If ObjC exceptions are enabled, this depends on the ABI. 933dff0c46cSDimitry Andric if (LangOpts.ObjCExceptions) { 9347ae0e2c9SDimitry Andric return LangOpts.ObjCRuntime.hasUnwindExceptions(); 9356122f3e6SDimitry Andric } 9366122f3e6SDimitry Andric 9376122f3e6SDimitry Andric return true; 9386122f3e6SDimitry Andric } 9396122f3e6SDimitry Andric 940f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 941f22ef01cSRoman Divacky llvm::Function *F) { 942f785676fSDimitry Andric llvm::AttrBuilder B; 943f785676fSDimitry Andric 944bd5abe19SDimitry Andric if (CodeGenOpts.UnwindTables) 945f785676fSDimitry Andric B.addAttribute(llvm::Attribute::UWTable); 946bd5abe19SDimitry Andric 947dff0c46cSDimitry Andric if (!hasUnwindExceptions(LangOpts)) 948f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoUnwind); 949f22ef01cSRoman Divacky 9500623d748SDimitry Andric if (LangOpts.getStackProtector() == LangOptions::SSPOn) 9510623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtect); 9520623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 9530623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 9540623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 9550623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectReq); 9560623d748SDimitry Andric 9570623d748SDimitry Andric if (!D) { 95844290647SDimitry Andric // If we don't have a declaration to control inlining, the function isn't 95944290647SDimitry Andric // explicitly marked as alwaysinline for semantic reasons, and inlining is 96044290647SDimitry Andric // disabled, mark the function as noinline. 96144290647SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 96244290647SDimitry Andric CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 96344290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 96444290647SDimitry Andric 965f37b6182SDimitry Andric F->addAttributes(llvm::AttributeList::FunctionIndex, B); 9660623d748SDimitry Andric return; 9670623d748SDimitry Andric } 9680623d748SDimitry Andric 969302affcbSDimitry Andric // Track whether we need to add the optnone LLVM attribute, 970302affcbSDimitry Andric // starting with the default for this optimization level. 971302affcbSDimitry Andric bool ShouldAddOptNone = 972302affcbSDimitry Andric !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 973302affcbSDimitry Andric // We can't add optnone in the following cases, it won't pass the verifier. 974302affcbSDimitry Andric ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 975302affcbSDimitry Andric ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline); 976302affcbSDimitry Andric ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 977302affcbSDimitry Andric 978302affcbSDimitry Andric if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) { 97944290647SDimitry Andric B.addAttribute(llvm::Attribute::OptimizeNone); 98044290647SDimitry Andric 98144290647SDimitry Andric // OptimizeNone implies noinline; we should not be inlining such functions. 98244290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 98344290647SDimitry Andric assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 98444290647SDimitry Andric "OptimizeNone and AlwaysInline on same function!"); 98544290647SDimitry Andric 98644290647SDimitry Andric // We still need to handle naked functions even though optnone subsumes 98744290647SDimitry Andric // much of their semantics. 98844290647SDimitry Andric if (D->hasAttr<NakedAttr>()) 98944290647SDimitry Andric B.addAttribute(llvm::Attribute::Naked); 99044290647SDimitry Andric 99144290647SDimitry Andric // OptimizeNone wins over OptimizeForSize and MinSize. 99244290647SDimitry Andric F->removeFnAttr(llvm::Attribute::OptimizeForSize); 99344290647SDimitry Andric F->removeFnAttr(llvm::Attribute::MinSize); 99444290647SDimitry Andric } else if (D->hasAttr<NakedAttr>()) { 9956122f3e6SDimitry Andric // Naked implies noinline: we should not be inlining such functions. 996f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Naked); 997f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 99859d1ed5bSDimitry Andric } else if (D->hasAttr<NoDuplicateAttr>()) { 99959d1ed5bSDimitry Andric B.addAttribute(llvm::Attribute::NoDuplicate); 1000f785676fSDimitry Andric } else if (D->hasAttr<NoInlineAttr>()) { 1001f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 100259d1ed5bSDimitry Andric } else if (D->hasAttr<AlwaysInlineAttr>() && 100344290647SDimitry Andric !F->hasFnAttribute(llvm::Attribute::NoInline)) { 1004f785676fSDimitry Andric // (noinline wins over always_inline, and we can't specify both in IR) 1005f785676fSDimitry Andric B.addAttribute(llvm::Attribute::AlwaysInline); 100644290647SDimitry Andric } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 100744290647SDimitry Andric // If we're not inlining, then force everything that isn't always_inline to 100844290647SDimitry Andric // carry an explicit noinline attribute. 100944290647SDimitry Andric if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 101044290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 101144290647SDimitry Andric } else { 101244290647SDimitry Andric // Otherwise, propagate the inline hint attribute and potentially use its 101344290647SDimitry Andric // absence to mark things as noinline. 101444290647SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) { 101544290647SDimitry Andric if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) { 101644290647SDimitry Andric return Redecl->isInlineSpecified(); 101744290647SDimitry Andric })) { 101844290647SDimitry Andric B.addAttribute(llvm::Attribute::InlineHint); 101944290647SDimitry Andric } else if (CodeGenOpts.getInlining() == 102044290647SDimitry Andric CodeGenOptions::OnlyHintInlining && 102144290647SDimitry Andric !FD->isInlined() && 102244290647SDimitry Andric !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 102344290647SDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 102444290647SDimitry Andric } 102544290647SDimitry Andric } 10266122f3e6SDimitry Andric } 10272754fe60SDimitry Andric 102844290647SDimitry Andric // Add other optimization related attributes if we are optimizing this 102944290647SDimitry Andric // function. 103044290647SDimitry Andric if (!D->hasAttr<OptimizeNoneAttr>()) { 1031f785676fSDimitry Andric if (D->hasAttr<ColdAttr>()) { 1032302affcbSDimitry Andric if (!ShouldAddOptNone) 1033f785676fSDimitry Andric B.addAttribute(llvm::Attribute::OptimizeForSize); 1034f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Cold); 1035f785676fSDimitry Andric } 10363861d79fSDimitry Andric 10373861d79fSDimitry Andric if (D->hasAttr<MinSizeAttr>()) 1038f785676fSDimitry Andric B.addAttribute(llvm::Attribute::MinSize); 103944290647SDimitry Andric } 1040f22ef01cSRoman Divacky 1041f37b6182SDimitry Andric F->addAttributes(llvm::AttributeList::FunctionIndex, B); 1042f785676fSDimitry Andric 1043e580952dSDimitry Andric unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 1044e580952dSDimitry Andric if (alignment) 1045e580952dSDimitry Andric F->setAlignment(alignment); 1046e580952dSDimitry Andric 10470623d748SDimitry Andric // Some C++ ABIs require 2-byte alignment for member functions, in order to 10480623d748SDimitry Andric // reserve a bit for differentiating between virtual and non-virtual member 10490623d748SDimitry Andric // functions. If the current target's C++ ABI requires this and this is a 10500623d748SDimitry Andric // member function, set its alignment accordingly. 10510623d748SDimitry Andric if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 1052f22ef01cSRoman Divacky if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 1053f22ef01cSRoman Divacky F->setAlignment(2); 1054f22ef01cSRoman Divacky } 105544290647SDimitry Andric 105644290647SDimitry Andric // In the cross-dso CFI mode, we want !type attributes on definitions only. 105744290647SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 105844290647SDimitry Andric if (auto *FD = dyn_cast<FunctionDecl>(D)) 105944290647SDimitry Andric CreateFunctionTypeMetadata(FD, F); 10600623d748SDimitry Andric } 1061f22ef01cSRoman Divacky 1062f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D, 1063f22ef01cSRoman Divacky llvm::GlobalValue *GV) { 10640623d748SDimitry Andric if (const auto *ND = dyn_cast_or_null<NamedDecl>(D)) 10659a199699SDimitry Andric setGlobalVisibility(GV, ND, ForDefinition); 10662754fe60SDimitry Andric else 10672754fe60SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 1068f22ef01cSRoman Divacky 10690623d748SDimitry Andric if (D && D->hasAttr<UsedAttr>()) 107059d1ed5bSDimitry Andric addUsedGlobal(GV); 107159d1ed5bSDimitry Andric } 107259d1ed5bSDimitry Andric 107339d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D, 107439d628a0SDimitry Andric llvm::GlobalValue *GV) { 107539d628a0SDimitry Andric SetCommonAttributes(D, GV); 107639d628a0SDimitry Andric 107739d628a0SDimitry Andric // Process the dllexport attribute based on whether the original definition 107839d628a0SDimitry Andric // (not necessarily the aliasee) was exported. 107939d628a0SDimitry Andric if (D->hasAttr<DLLExportAttr>()) 108039d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 108139d628a0SDimitry Andric } 108239d628a0SDimitry Andric 108359d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D, 108459d1ed5bSDimitry Andric llvm::GlobalObject *GO) { 108559d1ed5bSDimitry Andric SetCommonAttributes(D, GO); 1086f22ef01cSRoman Divacky 1087db17bf38SDimitry Andric if (D) { 1088db17bf38SDimitry Andric if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 1089db17bf38SDimitry Andric if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 1090db17bf38SDimitry Andric GV->addAttribute("bss-section", SA->getName()); 1091db17bf38SDimitry Andric if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 1092db17bf38SDimitry Andric GV->addAttribute("data-section", SA->getName()); 1093db17bf38SDimitry Andric if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 1094db17bf38SDimitry Andric GV->addAttribute("rodata-section", SA->getName()); 1095db17bf38SDimitry Andric } 1096db17bf38SDimitry Andric 1097db17bf38SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(GO)) { 1098db17bf38SDimitry Andric if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 1099db17bf38SDimitry Andric if (!D->getAttr<SectionAttr>()) 1100db17bf38SDimitry Andric F->addFnAttr("implicit-section-name", SA->getName()); 1101db17bf38SDimitry Andric } 1102db17bf38SDimitry Andric 1103f22ef01cSRoman Divacky if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 110459d1ed5bSDimitry Andric GO->setSection(SA->getName()); 1105db17bf38SDimitry Andric } 1106f22ef01cSRoman Divacky 11079a199699SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GO, *this, ForDefinition); 1108f22ef01cSRoman Divacky } 1109f22ef01cSRoman Divacky 1110f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 1111f22ef01cSRoman Divacky llvm::Function *F, 1112f22ef01cSRoman Divacky const CGFunctionInfo &FI) { 1113f22ef01cSRoman Divacky SetLLVMFunctionAttributes(D, FI, F); 1114f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, F); 1115f22ef01cSRoman Divacky 1116f22ef01cSRoman Divacky F->setLinkage(llvm::Function::InternalLinkage); 1117f22ef01cSRoman Divacky 111859d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 111959d1ed5bSDimitry Andric } 112059d1ed5bSDimitry Andric 11219a199699SDimitry Andric static void setLinkageForGV(llvm::GlobalValue *GV, 112259d1ed5bSDimitry Andric const NamedDecl *ND) { 112359d1ed5bSDimitry Andric // Set linkage and visibility in case we never see a definition. 112459d1ed5bSDimitry Andric LinkageInfo LV = ND->getLinkageAndVisibility(); 1125c4394386SDimitry Andric if (!isExternallyVisible(LV.getLinkage())) { 112659d1ed5bSDimitry Andric // Don't set internal linkage on declarations. 112759d1ed5bSDimitry Andric } else { 112859d1ed5bSDimitry Andric if (ND->hasAttr<DLLImportAttr>()) { 112959d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 113059d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 113159d1ed5bSDimitry Andric } else if (ND->hasAttr<DLLExportAttr>()) { 113259d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 113359d1ed5bSDimitry Andric } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 113459d1ed5bSDimitry Andric // "extern_weak" is overloaded in LLVM; we probably should have 113559d1ed5bSDimitry Andric // separate linkage types for this. 113659d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 113759d1ed5bSDimitry Andric } 113859d1ed5bSDimitry Andric } 1139f22ef01cSRoman Divacky } 1140f22ef01cSRoman Divacky 1141e7145dcbSDimitry Andric void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD, 11420623d748SDimitry Andric llvm::Function *F) { 11430623d748SDimitry Andric // Only if we are checking indirect calls. 11440623d748SDimitry Andric if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 11450623d748SDimitry Andric return; 11460623d748SDimitry Andric 11470623d748SDimitry Andric // Non-static class methods are handled via vtable pointer checks elsewhere. 11480623d748SDimitry Andric if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 11490623d748SDimitry Andric return; 11500623d748SDimitry Andric 11510623d748SDimitry Andric // Additionally, if building with cross-DSO support... 11520623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 11530623d748SDimitry Andric // Skip available_externally functions. They won't be codegen'ed in the 11540623d748SDimitry Andric // current module anyway. 11550623d748SDimitry Andric if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally) 11560623d748SDimitry Andric return; 11570623d748SDimitry Andric } 11580623d748SDimitry Andric 11590623d748SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 1160e7145dcbSDimitry Andric F->addTypeMetadata(0, MD); 11619a199699SDimitry Andric F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); 11620623d748SDimitry Andric 11630623d748SDimitry Andric // Emit a hash-based bit set entry for cross-DSO calls. 1164e7145dcbSDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 1165e7145dcbSDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 1166e7145dcbSDimitry Andric F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 11670623d748SDimitry Andric } 11680623d748SDimitry Andric 116939d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 117039d628a0SDimitry Andric bool IsIncompleteFunction, 11719a199699SDimitry Andric bool IsThunk, 11729a199699SDimitry Andric ForDefinition_t IsForDefinition) { 11739a199699SDimitry Andric 117433956c43SDimitry Andric if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 11753b0f4066SDimitry Andric // If this is an intrinsic function, set the function's attributes 11763b0f4066SDimitry Andric // to the intrinsic's attributes. 117733956c43SDimitry Andric F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 11783b0f4066SDimitry Andric return; 11793b0f4066SDimitry Andric } 11803b0f4066SDimitry Andric 118159d1ed5bSDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1182f22ef01cSRoman Divacky 11839a199699SDimitry Andric if (!IsIncompleteFunction) { 1184dff0c46cSDimitry Andric SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 11859a199699SDimitry Andric // Setup target-specific attributes. 11869a199699SDimitry Andric if (!IsForDefinition) 11879a199699SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(FD, F, *this, 11889a199699SDimitry Andric NotForDefinition); 11899a199699SDimitry Andric } 1190f22ef01cSRoman Divacky 119159d1ed5bSDimitry Andric // Add the Returned attribute for "this", except for iOS 5 and earlier 119259d1ed5bSDimitry Andric // where substantial code, including the libstdc++ dylib, was compiled with 119359d1ed5bSDimitry Andric // GCC and does not actually return "this". 119439d628a0SDimitry Andric if (!IsThunk && getCXXABI().HasThisReturn(GD) && 119544290647SDimitry Andric !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 1196f785676fSDimitry Andric assert(!F->arg_empty() && 1197f785676fSDimitry Andric F->arg_begin()->getType() 1198f785676fSDimitry Andric ->canLosslesslyBitCastTo(F->getReturnType()) && 1199f785676fSDimitry Andric "unexpected this return"); 1200f785676fSDimitry Andric F->addAttribute(1, llvm::Attribute::Returned); 1201f785676fSDimitry Andric } 1202f785676fSDimitry Andric 1203f22ef01cSRoman Divacky // Only a few attributes are set on declarations; these may later be 1204f22ef01cSRoman Divacky // overridden by a definition. 1205f22ef01cSRoman Divacky 12069a199699SDimitry Andric setLinkageForGV(F, FD); 12079a199699SDimitry Andric setGlobalVisibility(F, FD, NotForDefinition); 12082754fe60SDimitry Andric 1209db17bf38SDimitry Andric if (FD->getAttr<PragmaClangTextSectionAttr>()) { 1210db17bf38SDimitry Andric F->addFnAttr("implicit-section-name"); 1211db17bf38SDimitry Andric } 1212db17bf38SDimitry Andric 1213f22ef01cSRoman Divacky if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 1214f22ef01cSRoman Divacky F->setSection(SA->getName()); 1215f785676fSDimitry Andric 1216e7145dcbSDimitry Andric if (FD->isReplaceableGlobalAllocationFunction()) { 1217f785676fSDimitry Andric // A replaceable global allocation function does not act like a builtin by 1218f785676fSDimitry Andric // default, only if it is invoked by a new-expression or delete-expression. 121920e90f04SDimitry Andric F->addAttribute(llvm::AttributeList::FunctionIndex, 1220f785676fSDimitry Andric llvm::Attribute::NoBuiltin); 12210623d748SDimitry Andric 1222e7145dcbSDimitry Andric // A sane operator new returns a non-aliasing pointer. 1223e7145dcbSDimitry Andric // FIXME: Also add NonNull attribute to the return value 1224e7145dcbSDimitry Andric // for the non-nothrow forms? 1225e7145dcbSDimitry Andric auto Kind = FD->getDeclName().getCXXOverloadedOperator(); 1226e7145dcbSDimitry Andric if (getCodeGenOpts().AssumeSaneOperatorNew && 1227e7145dcbSDimitry Andric (Kind == OO_New || Kind == OO_Array_New)) 122820e90f04SDimitry Andric F->addAttribute(llvm::AttributeList::ReturnIndex, 1229e7145dcbSDimitry Andric llvm::Attribute::NoAlias); 1230e7145dcbSDimitry Andric } 1231e7145dcbSDimitry Andric 1232e7145dcbSDimitry Andric if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 1233e7145dcbSDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1234e7145dcbSDimitry Andric else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 1235e7145dcbSDimitry Andric if (MD->isVirtual()) 1236e7145dcbSDimitry Andric F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1237e7145dcbSDimitry Andric 123844290647SDimitry Andric // Don't emit entries for function declarations in the cross-DSO mode. This 123944290647SDimitry Andric // is handled with better precision by the receiving DSO. 124044290647SDimitry Andric if (!CodeGenOpts.SanitizeCfiCrossDso) 1241e7145dcbSDimitry Andric CreateFunctionTypeMetadata(FD, F); 12429a199699SDimitry Andric 12439a199699SDimitry Andric if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 12449a199699SDimitry Andric getOpenMPRuntime().emitDeclareSimdFunction(FD, F); 1245f22ef01cSRoman Divacky } 1246f22ef01cSRoman Divacky 124759d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 1248f22ef01cSRoman Divacky assert(!GV->isDeclaration() && 1249f22ef01cSRoman Divacky "Only globals with definition can force usage."); 125097bc6c73SDimitry Andric LLVMUsed.emplace_back(GV); 1251f22ef01cSRoman Divacky } 1252f22ef01cSRoman Divacky 125359d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 125459d1ed5bSDimitry Andric assert(!GV->isDeclaration() && 125559d1ed5bSDimitry Andric "Only globals with definition can force usage."); 125697bc6c73SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 125759d1ed5bSDimitry Andric } 125859d1ed5bSDimitry Andric 125959d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name, 1260f37b6182SDimitry Andric std::vector<llvm::WeakTrackingVH> &List) { 1261f22ef01cSRoman Divacky // Don't create llvm.used if there is no need. 126259d1ed5bSDimitry Andric if (List.empty()) 1263f22ef01cSRoman Divacky return; 1264f22ef01cSRoman Divacky 126559d1ed5bSDimitry Andric // Convert List to what ConstantArray needs. 1266dff0c46cSDimitry Andric SmallVector<llvm::Constant*, 8> UsedArray; 126759d1ed5bSDimitry Andric UsedArray.resize(List.size()); 126859d1ed5bSDimitry Andric for (unsigned i = 0, e = List.size(); i != e; ++i) { 1269f22ef01cSRoman Divacky UsedArray[i] = 127044f7b0dcSDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 127144f7b0dcSDimitry Andric cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 1272f22ef01cSRoman Divacky } 1273f22ef01cSRoman Divacky 1274f22ef01cSRoman Divacky if (UsedArray.empty()) 1275f22ef01cSRoman Divacky return; 127659d1ed5bSDimitry Andric llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 1277f22ef01cSRoman Divacky 127859d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 127959d1ed5bSDimitry Andric CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 128059d1ed5bSDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), Name); 1281f22ef01cSRoman Divacky 1282f22ef01cSRoman Divacky GV->setSection("llvm.metadata"); 1283f22ef01cSRoman Divacky } 1284f22ef01cSRoman Divacky 128559d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() { 128659d1ed5bSDimitry Andric emitUsed(*this, "llvm.used", LLVMUsed); 128759d1ed5bSDimitry Andric emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 128859d1ed5bSDimitry Andric } 128959d1ed5bSDimitry Andric 1290f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 129139d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 1292f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1293f785676fSDimitry Andric } 1294f785676fSDimitry Andric 1295f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 1296f785676fSDimitry Andric llvm::SmallString<32> Opt; 1297f785676fSDimitry Andric getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 129839d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1299f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1300f785676fSDimitry Andric } 1301f785676fSDimitry Andric 1302f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) { 1303f785676fSDimitry Andric llvm::SmallString<24> Opt; 1304f785676fSDimitry Andric getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 130539d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1306f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1307f785676fSDimitry Andric } 1308f785676fSDimitry Andric 1309139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules 1310139f7f9bSDimitry Andric /// it depends on, using a postorder walk. 131139d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 131224d58133SDimitry Andric SmallVectorImpl<llvm::MDNode *> &Metadata, 1313139f7f9bSDimitry Andric llvm::SmallPtrSet<Module *, 16> &Visited) { 1314139f7f9bSDimitry Andric // Import this module's parent. 131539d628a0SDimitry Andric if (Mod->Parent && Visited.insert(Mod->Parent).second) { 1316f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 1317139f7f9bSDimitry Andric } 1318139f7f9bSDimitry Andric 1319139f7f9bSDimitry Andric // Import this module's dependencies. 1320139f7f9bSDimitry Andric for (unsigned I = Mod->Imports.size(); I > 0; --I) { 132139d628a0SDimitry Andric if (Visited.insert(Mod->Imports[I - 1]).second) 1322f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 1323139f7f9bSDimitry Andric } 1324139f7f9bSDimitry Andric 1325139f7f9bSDimitry Andric // Add linker options to link against the libraries/frameworks 1326139f7f9bSDimitry Andric // described by this module. 1327f785676fSDimitry Andric llvm::LLVMContext &Context = CGM.getLLVMContext(); 1328139f7f9bSDimitry Andric for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 1329f785676fSDimitry Andric // Link against a framework. Frameworks are currently Darwin only, so we 1330f785676fSDimitry Andric // don't to ask TargetCodeGenInfo for the spelling of the linker option. 1331139f7f9bSDimitry Andric if (Mod->LinkLibraries[I-1].IsFramework) { 133239d628a0SDimitry Andric llvm::Metadata *Args[2] = { 1333139f7f9bSDimitry Andric llvm::MDString::get(Context, "-framework"), 133439d628a0SDimitry Andric llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 1335139f7f9bSDimitry Andric 1336139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 1337139f7f9bSDimitry Andric continue; 1338139f7f9bSDimitry Andric } 1339139f7f9bSDimitry Andric 1340139f7f9bSDimitry Andric // Link against a library. 1341f785676fSDimitry Andric llvm::SmallString<24> Opt; 1342f785676fSDimitry Andric CGM.getTargetCodeGenInfo().getDependentLibraryOption( 1343f785676fSDimitry Andric Mod->LinkLibraries[I-1].Library, Opt); 134439d628a0SDimitry Andric auto *OptString = llvm::MDString::get(Context, Opt); 1345139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, OptString)); 1346139f7f9bSDimitry Andric } 1347139f7f9bSDimitry Andric } 1348139f7f9bSDimitry Andric 1349139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() { 1350139f7f9bSDimitry Andric // Collect the set of all of the modules we want to visit to emit link 1351139f7f9bSDimitry Andric // options, which is essentially the imported modules and all of their 1352139f7f9bSDimitry Andric // non-explicit child modules. 1353139f7f9bSDimitry Andric llvm::SetVector<clang::Module *> LinkModules; 1354139f7f9bSDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 1355139f7f9bSDimitry Andric SmallVector<clang::Module *, 16> Stack; 1356139f7f9bSDimitry Andric 1357139f7f9bSDimitry Andric // Seed the stack with imported modules. 1358f1a29dd3SDimitry Andric for (Module *M : ImportedModules) { 1359f1a29dd3SDimitry Andric // Do not add any link flags when an implementation TU of a module imports 1360f1a29dd3SDimitry Andric // a header of that same module. 1361f1a29dd3SDimitry Andric if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 1362f1a29dd3SDimitry Andric !getLangOpts().isCompilingModule()) 1363f1a29dd3SDimitry Andric continue; 13648f0fd8f6SDimitry Andric if (Visited.insert(M).second) 13658f0fd8f6SDimitry Andric Stack.push_back(M); 1366f1a29dd3SDimitry Andric } 1367139f7f9bSDimitry Andric 1368139f7f9bSDimitry Andric // Find all of the modules to import, making a little effort to prune 1369139f7f9bSDimitry Andric // non-leaf modules. 1370139f7f9bSDimitry Andric while (!Stack.empty()) { 1371f785676fSDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 1372139f7f9bSDimitry Andric 1373139f7f9bSDimitry Andric bool AnyChildren = false; 1374139f7f9bSDimitry Andric 1375139f7f9bSDimitry Andric // Visit the submodules of this module. 1376139f7f9bSDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 1377139f7f9bSDimitry Andric SubEnd = Mod->submodule_end(); 1378139f7f9bSDimitry Andric Sub != SubEnd; ++Sub) { 1379139f7f9bSDimitry Andric // Skip explicit children; they need to be explicitly imported to be 1380139f7f9bSDimitry Andric // linked against. 1381139f7f9bSDimitry Andric if ((*Sub)->IsExplicit) 1382139f7f9bSDimitry Andric continue; 1383139f7f9bSDimitry Andric 138439d628a0SDimitry Andric if (Visited.insert(*Sub).second) { 1385139f7f9bSDimitry Andric Stack.push_back(*Sub); 1386139f7f9bSDimitry Andric AnyChildren = true; 1387139f7f9bSDimitry Andric } 1388139f7f9bSDimitry Andric } 1389139f7f9bSDimitry Andric 1390139f7f9bSDimitry Andric // We didn't find any children, so add this module to the list of 1391139f7f9bSDimitry Andric // modules to link against. 1392139f7f9bSDimitry Andric if (!AnyChildren) { 1393139f7f9bSDimitry Andric LinkModules.insert(Mod); 1394139f7f9bSDimitry Andric } 1395139f7f9bSDimitry Andric } 1396139f7f9bSDimitry Andric 1397139f7f9bSDimitry Andric // Add link options for all of the imported modules in reverse topological 1398f785676fSDimitry Andric // order. We don't do anything to try to order import link flags with respect 1399f785676fSDimitry Andric // to linker options inserted by things like #pragma comment(). 140024d58133SDimitry Andric SmallVector<llvm::MDNode *, 16> MetadataArgs; 1401139f7f9bSDimitry Andric Visited.clear(); 14028f0fd8f6SDimitry Andric for (Module *M : LinkModules) 14038f0fd8f6SDimitry Andric if (Visited.insert(M).second) 14048f0fd8f6SDimitry Andric addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 1405139f7f9bSDimitry Andric std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 1406f785676fSDimitry Andric LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 1407139f7f9bSDimitry Andric 1408139f7f9bSDimitry Andric // Add the linker options metadata flag. 140924d58133SDimitry Andric auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 141024d58133SDimitry Andric for (auto *MD : LinkerOptionsMetadata) 141124d58133SDimitry Andric NMD->addOperand(MD); 1412139f7f9bSDimitry Andric } 1413139f7f9bSDimitry Andric 1414f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() { 1415f22ef01cSRoman Divacky // Emit code for any potentially referenced deferred decls. Since a 1416f22ef01cSRoman Divacky // previously unused static decl may become used during the generation of code 1417f22ef01cSRoman Divacky // for a static function, iterate until no changes are made. 1418f22ef01cSRoman Divacky 1419f22ef01cSRoman Divacky if (!DeferredVTables.empty()) { 1420139f7f9bSDimitry Andric EmitDeferredVTables(); 1421139f7f9bSDimitry Andric 1422e7145dcbSDimitry Andric // Emitting a vtable doesn't directly cause more vtables to 1423139f7f9bSDimitry Andric // become deferred, although it can cause functions to be 1424e7145dcbSDimitry Andric // emitted that then need those vtables. 1425139f7f9bSDimitry Andric assert(DeferredVTables.empty()); 1426f22ef01cSRoman Divacky } 1427f22ef01cSRoman Divacky 1428e7145dcbSDimitry Andric // Stop if we're out of both deferred vtables and deferred declarations. 142933956c43SDimitry Andric if (DeferredDeclsToEmit.empty()) 143033956c43SDimitry Andric return; 1431139f7f9bSDimitry Andric 143233956c43SDimitry Andric // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 143333956c43SDimitry Andric // work, it will not interfere with this. 1434f37b6182SDimitry Andric std::vector<GlobalDecl> CurDeclsToEmit; 143533956c43SDimitry Andric CurDeclsToEmit.swap(DeferredDeclsToEmit); 143633956c43SDimitry Andric 1437f37b6182SDimitry Andric for (GlobalDecl &D : CurDeclsToEmit) { 14380623d748SDimitry Andric // We should call GetAddrOfGlobal with IsForDefinition set to true in order 14390623d748SDimitry Andric // to get GlobalValue with exactly the type we need, not something that 14400623d748SDimitry Andric // might had been created for another decl with the same mangled name but 14410623d748SDimitry Andric // different type. 1442e7145dcbSDimitry Andric llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 144344290647SDimitry Andric GetAddrOfGlobal(D, ForDefinition)); 1444e7145dcbSDimitry Andric 1445e7145dcbSDimitry Andric // In case of different address spaces, we may still get a cast, even with 1446e7145dcbSDimitry Andric // IsForDefinition equal to true. Query mangled names table to get 1447e7145dcbSDimitry Andric // GlobalValue. 144839d628a0SDimitry Andric if (!GV) 144939d628a0SDimitry Andric GV = GetGlobalValue(getMangledName(D)); 145039d628a0SDimitry Andric 1451e7145dcbSDimitry Andric // Make sure GetGlobalValue returned non-null. 1452e7145dcbSDimitry Andric assert(GV); 1453e7145dcbSDimitry Andric 1454f22ef01cSRoman Divacky // Check to see if we've already emitted this. This is necessary 1455f22ef01cSRoman Divacky // for a couple of reasons: first, decls can end up in the 1456f22ef01cSRoman Divacky // deferred-decls queue multiple times, and second, decls can end 1457f22ef01cSRoman Divacky // up with definitions in unusual ways (e.g. by an extern inline 1458f22ef01cSRoman Divacky // function acquiring a strong function redefinition). Just 1459f22ef01cSRoman Divacky // ignore these cases. 1460e7145dcbSDimitry Andric if (!GV->isDeclaration()) 1461f22ef01cSRoman Divacky continue; 1462f22ef01cSRoman Divacky 1463f22ef01cSRoman Divacky // Otherwise, emit the definition and move on to the next one. 146459d1ed5bSDimitry Andric EmitGlobalDefinition(D, GV); 146533956c43SDimitry Andric 146633956c43SDimitry Andric // If we found out that we need to emit more decls, do that recursively. 146733956c43SDimitry Andric // This has the advantage that the decls are emitted in a DFS and related 146833956c43SDimitry Andric // ones are close together, which is convenient for testing. 146933956c43SDimitry Andric if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 147033956c43SDimitry Andric EmitDeferred(); 147133956c43SDimitry Andric assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 147233956c43SDimitry Andric } 1473f22ef01cSRoman Divacky } 1474f22ef01cSRoman Divacky } 1475f22ef01cSRoman Divacky 1476f9448bf3SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() { 1477f9448bf3SDimitry Andric // Try to emit external vtables as available_externally if they have emitted 1478f9448bf3SDimitry Andric // all inlined virtual functions. It runs after EmitDeferred() and therefore 1479f9448bf3SDimitry Andric // is not allowed to create new references to things that need to be emitted 1480f9448bf3SDimitry Andric // lazily. Note that it also uses fact that we eagerly emitting RTTI. 1481f9448bf3SDimitry Andric 1482f9448bf3SDimitry Andric assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 1483f9448bf3SDimitry Andric && "Only emit opportunistic vtables with optimizations"); 1484f9448bf3SDimitry Andric 1485f9448bf3SDimitry Andric for (const CXXRecordDecl *RD : OpportunisticVTables) { 1486f9448bf3SDimitry Andric assert(getVTables().isVTableExternal(RD) && 1487f9448bf3SDimitry Andric "This queue should only contain external vtables"); 1488f9448bf3SDimitry Andric if (getCXXABI().canSpeculativelyEmitVTable(RD)) 1489f9448bf3SDimitry Andric VTables.GenerateClassData(RD); 1490f9448bf3SDimitry Andric } 1491f9448bf3SDimitry Andric OpportunisticVTables.clear(); 1492f9448bf3SDimitry Andric } 1493f9448bf3SDimitry Andric 14946122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() { 14956122f3e6SDimitry Andric if (Annotations.empty()) 14966122f3e6SDimitry Andric return; 14976122f3e6SDimitry Andric 14986122f3e6SDimitry Andric // Create a new global variable for the ConstantStruct in the Module. 14996122f3e6SDimitry Andric llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 15006122f3e6SDimitry Andric Annotations[0]->getType(), Annotations.size()), Annotations); 150159d1ed5bSDimitry Andric auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 150259d1ed5bSDimitry Andric llvm::GlobalValue::AppendingLinkage, 150359d1ed5bSDimitry Andric Array, "llvm.global.annotations"); 15046122f3e6SDimitry Andric gv->setSection(AnnotationSection); 15056122f3e6SDimitry Andric } 15066122f3e6SDimitry Andric 1507139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1508f785676fSDimitry Andric llvm::Constant *&AStr = AnnotationStrings[Str]; 1509f785676fSDimitry Andric if (AStr) 1510f785676fSDimitry Andric return AStr; 15116122f3e6SDimitry Andric 15126122f3e6SDimitry Andric // Not found yet, create a new global. 1513dff0c46cSDimitry Andric llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 151459d1ed5bSDimitry Andric auto *gv = 151559d1ed5bSDimitry Andric new llvm::GlobalVariable(getModule(), s->getType(), true, 151659d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, s, ".str"); 15176122f3e6SDimitry Andric gv->setSection(AnnotationSection); 1518e7145dcbSDimitry Andric gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1519f785676fSDimitry Andric AStr = gv; 15206122f3e6SDimitry Andric return gv; 15216122f3e6SDimitry Andric } 15226122f3e6SDimitry Andric 15236122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 15246122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 15256122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(Loc); 15266122f3e6SDimitry Andric if (PLoc.isValid()) 15276122f3e6SDimitry Andric return EmitAnnotationString(PLoc.getFilename()); 15286122f3e6SDimitry Andric return EmitAnnotationString(SM.getBufferName(Loc)); 15296122f3e6SDimitry Andric } 15306122f3e6SDimitry Andric 15316122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 15326122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 15336122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(L); 15346122f3e6SDimitry Andric unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 15356122f3e6SDimitry Andric SM.getExpansionLineNumber(L); 15366122f3e6SDimitry Andric return llvm::ConstantInt::get(Int32Ty, LineNo); 15376122f3e6SDimitry Andric } 15386122f3e6SDimitry Andric 1539f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1540f22ef01cSRoman Divacky const AnnotateAttr *AA, 15416122f3e6SDimitry Andric SourceLocation L) { 15426122f3e6SDimitry Andric // Get the globals for file name, annotation, and the line number. 15436122f3e6SDimitry Andric llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 15446122f3e6SDimitry Andric *UnitGV = EmitAnnotationUnit(L), 15456122f3e6SDimitry Andric *LineNoCst = EmitAnnotationLineNo(L); 1546f22ef01cSRoman Divacky 1547f22ef01cSRoman Divacky // Create the ConstantStruct for the global annotation. 1548f22ef01cSRoman Divacky llvm::Constant *Fields[4] = { 15496122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 15506122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 15516122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 15526122f3e6SDimitry Andric LineNoCst 1553f22ef01cSRoman Divacky }; 155417a519f9SDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 1555f22ef01cSRoman Divacky } 1556f22ef01cSRoman Divacky 15576122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 15586122f3e6SDimitry Andric llvm::GlobalValue *GV) { 15596122f3e6SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 15606122f3e6SDimitry Andric // Get the struct elements for these annotations. 156159d1ed5bSDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 156259d1ed5bSDimitry Andric Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 15636122f3e6SDimitry Andric } 15646122f3e6SDimitry Andric 15659a199699SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind, 15669a199699SDimitry Andric llvm::Function *Fn, 156739d628a0SDimitry Andric SourceLocation Loc) const { 156839d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 156939d628a0SDimitry Andric // Blacklist by function name. 15709a199699SDimitry Andric if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName())) 157139d628a0SDimitry Andric return true; 157239d628a0SDimitry Andric // Blacklist by location. 15730623d748SDimitry Andric if (Loc.isValid()) 15749a199699SDimitry Andric return SanitizerBL.isBlacklistedLocation(Kind, Loc); 157539d628a0SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 157639d628a0SDimitry Andric // it's located in the main file. 157739d628a0SDimitry Andric auto &SM = Context.getSourceManager(); 157839d628a0SDimitry Andric if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 15799a199699SDimitry Andric return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName()); 158039d628a0SDimitry Andric } 158139d628a0SDimitry Andric return false; 158239d628a0SDimitry Andric } 158339d628a0SDimitry Andric 158439d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 158539d628a0SDimitry Andric SourceLocation Loc, QualType Ty, 158639d628a0SDimitry Andric StringRef Category) const { 15878f0fd8f6SDimitry Andric // For now globals can be blacklisted only in ASan and KASan. 15889a199699SDimitry Andric const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask & 15899a199699SDimitry Andric (SanitizerKind::Address | SanitizerKind::KernelAddress | SanitizerKind::HWAddress); 15909a199699SDimitry Andric if (!EnabledAsanMask) 159139d628a0SDimitry Andric return false; 159239d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 15939a199699SDimitry Andric if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category)) 159439d628a0SDimitry Andric return true; 15959a199699SDimitry Andric if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category)) 159639d628a0SDimitry Andric return true; 159739d628a0SDimitry Andric // Check global type. 159839d628a0SDimitry Andric if (!Ty.isNull()) { 159939d628a0SDimitry Andric // Drill down the array types: if global variable of a fixed type is 160039d628a0SDimitry Andric // blacklisted, we also don't instrument arrays of them. 160139d628a0SDimitry Andric while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 160239d628a0SDimitry Andric Ty = AT->getElementType(); 160339d628a0SDimitry Andric Ty = Ty.getCanonicalType().getUnqualifiedType(); 160439d628a0SDimitry Andric // We allow to blacklist only record types (classes, structs etc.) 160539d628a0SDimitry Andric if (Ty->isRecordType()) { 160639d628a0SDimitry Andric std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 16079a199699SDimitry Andric if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category)) 160839d628a0SDimitry Andric return true; 160939d628a0SDimitry Andric } 161039d628a0SDimitry Andric } 161139d628a0SDimitry Andric return false; 161239d628a0SDimitry Andric } 161339d628a0SDimitry Andric 161420e90f04SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 161520e90f04SDimitry Andric StringRef Category) const { 161620e90f04SDimitry Andric if (!LangOpts.XRayInstrument) 161720e90f04SDimitry Andric return false; 161820e90f04SDimitry Andric const auto &XRayFilter = getContext().getXRayFilter(); 161920e90f04SDimitry Andric using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 162020e90f04SDimitry Andric auto Attr = XRayFunctionFilter::ImbueAttribute::NONE; 162120e90f04SDimitry Andric if (Loc.isValid()) 162220e90f04SDimitry Andric Attr = XRayFilter.shouldImbueLocation(Loc, Category); 162320e90f04SDimitry Andric if (Attr == ImbueAttr::NONE) 162420e90f04SDimitry Andric Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 162520e90f04SDimitry Andric switch (Attr) { 162620e90f04SDimitry Andric case ImbueAttr::NONE: 162720e90f04SDimitry Andric return false; 162820e90f04SDimitry Andric case ImbueAttr::ALWAYS: 162920e90f04SDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 163020e90f04SDimitry Andric break; 1631302affcbSDimitry Andric case ImbueAttr::ALWAYS_ARG1: 1632302affcbSDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 1633302affcbSDimitry Andric Fn->addFnAttr("xray-log-args", "1"); 1634302affcbSDimitry Andric break; 163520e90f04SDimitry Andric case ImbueAttr::NEVER: 163620e90f04SDimitry Andric Fn->addFnAttr("function-instrument", "xray-never"); 163720e90f04SDimitry Andric break; 163820e90f04SDimitry Andric } 163920e90f04SDimitry Andric return true; 164020e90f04SDimitry Andric } 164120e90f04SDimitry Andric 164239d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 1643e580952dSDimitry Andric // Never defer when EmitAllDecls is specified. 1644dff0c46cSDimitry Andric if (LangOpts.EmitAllDecls) 164539d628a0SDimitry Andric return true; 164639d628a0SDimitry Andric 164739d628a0SDimitry Andric return getContext().DeclMustBeEmitted(Global); 164839d628a0SDimitry Andric } 164939d628a0SDimitry Andric 165039d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 165139d628a0SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) 165239d628a0SDimitry Andric if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 165339d628a0SDimitry Andric // Implicit template instantiations may change linkage if they are later 165439d628a0SDimitry Andric // explicitly instantiated, so they should not be emitted eagerly. 1655f22ef01cSRoman Divacky return false; 1656e7145dcbSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(Global)) 1657e7145dcbSDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 1658e7145dcbSDimitry Andric ASTContext::InlineVariableDefinitionKind::WeakUnknown) 1659e7145dcbSDimitry Andric // A definition of an inline constexpr static data member may change 1660e7145dcbSDimitry Andric // linkage later if it's redeclared outside the class. 1661e7145dcbSDimitry Andric return false; 1662875ed548SDimitry Andric // If OpenMP is enabled and threadprivates must be generated like TLS, delay 1663875ed548SDimitry Andric // codegen for global variables, because they may be marked as threadprivate. 1664875ed548SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 1665875ed548SDimitry Andric getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global)) 1666875ed548SDimitry Andric return false; 1667f22ef01cSRoman Divacky 166839d628a0SDimitry Andric return true; 1669f22ef01cSRoman Divacky } 1670f22ef01cSRoman Divacky 16710623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor( 16723861d79fSDimitry Andric const CXXUuidofExpr* E) { 16733861d79fSDimitry Andric // Sema has verified that IIDSource has a __declspec(uuid()), and that its 16743861d79fSDimitry Andric // well-formed. 1675e7145dcbSDimitry Andric StringRef Uuid = E->getUuidStr(); 1676f785676fSDimitry Andric std::string Name = "_GUID_" + Uuid.lower(); 1677f785676fSDimitry Andric std::replace(Name.begin(), Name.end(), '-', '_'); 16783861d79fSDimitry Andric 1679e7145dcbSDimitry Andric // The UUID descriptor should be pointer aligned. 1680e7145dcbSDimitry Andric CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 16810623d748SDimitry Andric 16823861d79fSDimitry Andric // Look for an existing global. 16833861d79fSDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 16840623d748SDimitry Andric return ConstantAddress(GV, Alignment); 16853861d79fSDimitry Andric 168639d628a0SDimitry Andric llvm::Constant *Init = EmitUuidofInitializer(Uuid); 16873861d79fSDimitry Andric assert(Init && "failed to initialize as constant"); 16883861d79fSDimitry Andric 168959d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 1690f785676fSDimitry Andric getModule(), Init->getType(), 1691f785676fSDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 169233956c43SDimitry Andric if (supportsCOMDAT()) 169333956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 16940623d748SDimitry Andric return ConstantAddress(GV, Alignment); 16953861d79fSDimitry Andric } 16963861d79fSDimitry Andric 16970623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1698f22ef01cSRoman Divacky const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1699f22ef01cSRoman Divacky assert(AA && "No alias?"); 1700f22ef01cSRoman Divacky 17010623d748SDimitry Andric CharUnits Alignment = getContext().getDeclAlign(VD); 17026122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1703f22ef01cSRoman Divacky 1704f22ef01cSRoman Divacky // See if there is already something with the target's name in the module. 1705f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 17063861d79fSDimitry Andric if (Entry) { 17073861d79fSDimitry Andric unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 17080623d748SDimitry Andric auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 17090623d748SDimitry Andric return ConstantAddress(Ptr, Alignment); 17103861d79fSDimitry Andric } 1711f22ef01cSRoman Divacky 1712f22ef01cSRoman Divacky llvm::Constant *Aliasee; 1713f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 17143861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 17153861d79fSDimitry Andric GlobalDecl(cast<FunctionDecl>(VD)), 17162754fe60SDimitry Andric /*ForVTable=*/false); 1717f22ef01cSRoman Divacky else 1718f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 171959d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 172059d1ed5bSDimitry Andric nullptr); 17213861d79fSDimitry Andric 172259d1ed5bSDimitry Andric auto *F = cast<llvm::GlobalValue>(Aliasee); 1723f22ef01cSRoman Divacky F->setLinkage(llvm::Function::ExternalWeakLinkage); 1724f22ef01cSRoman Divacky WeakRefReferences.insert(F); 1725f22ef01cSRoman Divacky 17260623d748SDimitry Andric return ConstantAddress(Aliasee, Alignment); 1727f22ef01cSRoman Divacky } 1728f22ef01cSRoman Divacky 1729f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) { 173059d1ed5bSDimitry Andric const auto *Global = cast<ValueDecl>(GD.getDecl()); 1731f22ef01cSRoman Divacky 1732f22ef01cSRoman Divacky // Weak references don't produce any output by themselves. 1733f22ef01cSRoman Divacky if (Global->hasAttr<WeakRefAttr>()) 1734f22ef01cSRoman Divacky return; 1735f22ef01cSRoman Divacky 1736f22ef01cSRoman Divacky // If this is an alias definition (which otherwise looks like a declaration) 1737f22ef01cSRoman Divacky // emit it now. 1738f22ef01cSRoman Divacky if (Global->hasAttr<AliasAttr>()) 1739f22ef01cSRoman Divacky return EmitAliasDefinition(GD); 1740f22ef01cSRoman Divacky 1741e7145dcbSDimitry Andric // IFunc like an alias whose value is resolved at runtime by calling resolver. 1742e7145dcbSDimitry Andric if (Global->hasAttr<IFuncAttr>()) 1743e7145dcbSDimitry Andric return emitIFuncDefinition(GD); 1744e7145dcbSDimitry Andric 17456122f3e6SDimitry Andric // If this is CUDA, be selective about which declarations we emit. 1746dff0c46cSDimitry Andric if (LangOpts.CUDA) { 174733956c43SDimitry Andric if (LangOpts.CUDAIsDevice) { 17486122f3e6SDimitry Andric if (!Global->hasAttr<CUDADeviceAttr>() && 17496122f3e6SDimitry Andric !Global->hasAttr<CUDAGlobalAttr>() && 17506122f3e6SDimitry Andric !Global->hasAttr<CUDAConstantAttr>() && 17516122f3e6SDimitry Andric !Global->hasAttr<CUDASharedAttr>()) 17526122f3e6SDimitry Andric return; 17536122f3e6SDimitry Andric } else { 1754e7145dcbSDimitry Andric // We need to emit host-side 'shadows' for all global 1755e7145dcbSDimitry Andric // device-side variables because the CUDA runtime needs their 1756e7145dcbSDimitry Andric // size and host-side address in order to provide access to 1757e7145dcbSDimitry Andric // their device-side incarnations. 1758e7145dcbSDimitry Andric 1759e7145dcbSDimitry Andric // So device-only functions are the only things we skip. 1760e7145dcbSDimitry Andric if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 1761e7145dcbSDimitry Andric Global->hasAttr<CUDADeviceAttr>()) 17626122f3e6SDimitry Andric return; 1763e7145dcbSDimitry Andric 1764e7145dcbSDimitry Andric assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 1765e7145dcbSDimitry Andric "Expected Variable or Function"); 1766e580952dSDimitry Andric } 1767e580952dSDimitry Andric } 1768e580952dSDimitry Andric 1769e7145dcbSDimitry Andric if (LangOpts.OpenMP) { 1770ea942507SDimitry Andric // If this is OpenMP device, check if it is legal to emit this global 1771ea942507SDimitry Andric // normally. 1772ea942507SDimitry Andric if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 1773ea942507SDimitry Andric return; 1774e7145dcbSDimitry Andric if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 1775e7145dcbSDimitry Andric if (MustBeEmitted(Global)) 1776e7145dcbSDimitry Andric EmitOMPDeclareReduction(DRD); 1777e7145dcbSDimitry Andric return; 1778e7145dcbSDimitry Andric } 1779e7145dcbSDimitry Andric } 1780ea942507SDimitry Andric 17816122f3e6SDimitry Andric // Ignore declarations, they will be emitted on their first use. 178259d1ed5bSDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 1783f22ef01cSRoman Divacky // Forward declarations are emitted lazily on first use. 17846122f3e6SDimitry Andric if (!FD->doesThisDeclarationHaveABody()) { 17856122f3e6SDimitry Andric if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1786f22ef01cSRoman Divacky return; 17876122f3e6SDimitry Andric 17886122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 178959d1ed5bSDimitry Andric 179059d1ed5bSDimitry Andric // Compute the function info and LLVM type. 179159d1ed5bSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 179259d1ed5bSDimitry Andric llvm::Type *Ty = getTypes().GetFunctionType(FI); 179359d1ed5bSDimitry Andric 179459d1ed5bSDimitry Andric GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 179559d1ed5bSDimitry Andric /*DontDefer=*/false); 17966122f3e6SDimitry Andric return; 17976122f3e6SDimitry Andric } 1798f22ef01cSRoman Divacky } else { 179959d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(Global); 1800f22ef01cSRoman Divacky assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1801e7145dcbSDimitry Andric // We need to emit device-side global CUDA variables even if a 1802e7145dcbSDimitry Andric // variable does not have a definition -- we still need to define 1803e7145dcbSDimitry Andric // host-side shadow for it. 1804e7145dcbSDimitry Andric bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice && 1805e7145dcbSDimitry Andric !VD->hasDefinition() && 1806e7145dcbSDimitry Andric (VD->hasAttr<CUDAConstantAttr>() || 1807e7145dcbSDimitry Andric VD->hasAttr<CUDADeviceAttr>()); 1808e7145dcbSDimitry Andric if (!MustEmitForCuda && 1809e7145dcbSDimitry Andric VD->isThisDeclarationADefinition() != VarDecl::Definition && 1810e7145dcbSDimitry Andric !Context.isMSStaticDataMemberInlineDefinition(VD)) { 1811e7145dcbSDimitry Andric // If this declaration may have caused an inline variable definition to 1812e7145dcbSDimitry Andric // change linkage, make sure that it's emitted. 1813e7145dcbSDimitry Andric if (Context.getInlineVariableDefinitionKind(VD) == 1814e7145dcbSDimitry Andric ASTContext::InlineVariableDefinitionKind::Strong) 1815e7145dcbSDimitry Andric GetAddrOfGlobalVar(VD); 1816f22ef01cSRoman Divacky return; 1817f22ef01cSRoman Divacky } 1818e7145dcbSDimitry Andric } 1819f22ef01cSRoman Divacky 182039d628a0SDimitry Andric // Defer code generation to first use when possible, e.g. if this is an inline 182139d628a0SDimitry Andric // function. If the global must always be emitted, do it eagerly if possible 182239d628a0SDimitry Andric // to benefit from cache locality. 182339d628a0SDimitry Andric if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 1824f22ef01cSRoman Divacky // Emit the definition if it can't be deferred. 1825f22ef01cSRoman Divacky EmitGlobalDefinition(GD); 1826f22ef01cSRoman Divacky return; 1827f22ef01cSRoman Divacky } 1828f22ef01cSRoman Divacky 1829e580952dSDimitry Andric // If we're deferring emission of a C++ variable with an 1830e580952dSDimitry Andric // initializer, remember the order in which it appeared in the file. 1831dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1832e580952dSDimitry Andric cast<VarDecl>(Global)->hasInit()) { 1833e580952dSDimitry Andric DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 183459d1ed5bSDimitry Andric CXXGlobalInits.push_back(nullptr); 1835e580952dSDimitry Andric } 1836e580952dSDimitry Andric 18376122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 1838f37b6182SDimitry Andric if (GetGlobalValue(MangledName) != nullptr) { 183939d628a0SDimitry Andric // The value has already been used and should therefore be emitted. 1840f37b6182SDimitry Andric addDeferredDeclToEmit(GD); 184139d628a0SDimitry Andric } else if (MustBeEmitted(Global)) { 184239d628a0SDimitry Andric // The value must be emitted, but cannot be emitted eagerly. 184339d628a0SDimitry Andric assert(!MayBeEmittedEagerly(Global)); 1844f37b6182SDimitry Andric addDeferredDeclToEmit(GD); 184539d628a0SDimitry Andric } else { 1846f22ef01cSRoman Divacky // Otherwise, remember that we saw a deferred decl with this name. The 1847f22ef01cSRoman Divacky // first use of the mangled name will cause it to move into 1848f22ef01cSRoman Divacky // DeferredDeclsToEmit. 1849f22ef01cSRoman Divacky DeferredDecls[MangledName] = GD; 1850f22ef01cSRoman Divacky } 1851f22ef01cSRoman Divacky } 1852f22ef01cSRoman Divacky 185320e90f04SDimitry Andric // Check if T is a class type with a destructor that's not dllimport. 185420e90f04SDimitry Andric static bool HasNonDllImportDtor(QualType T) { 185520e90f04SDimitry Andric if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 185620e90f04SDimitry Andric if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 185720e90f04SDimitry Andric if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 185820e90f04SDimitry Andric return true; 185920e90f04SDimitry Andric 186020e90f04SDimitry Andric return false; 186120e90f04SDimitry Andric } 186220e90f04SDimitry Andric 1863f8254f43SDimitry Andric namespace { 1864f8254f43SDimitry Andric struct FunctionIsDirectlyRecursive : 1865f8254f43SDimitry Andric public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1866f8254f43SDimitry Andric const StringRef Name; 1867dff0c46cSDimitry Andric const Builtin::Context &BI; 1868f8254f43SDimitry Andric bool Result; 1869dff0c46cSDimitry Andric FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1870dff0c46cSDimitry Andric Name(N), BI(C), Result(false) { 1871f8254f43SDimitry Andric } 1872f8254f43SDimitry Andric typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1873f8254f43SDimitry Andric 1874f8254f43SDimitry Andric bool TraverseCallExpr(CallExpr *E) { 1875dff0c46cSDimitry Andric const FunctionDecl *FD = E->getDirectCallee(); 1876dff0c46cSDimitry Andric if (!FD) 1877f8254f43SDimitry Andric return true; 1878dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1879dff0c46cSDimitry Andric if (Attr && Name == Attr->getLabel()) { 1880dff0c46cSDimitry Andric Result = true; 1881dff0c46cSDimitry Andric return false; 1882dff0c46cSDimitry Andric } 1883dff0c46cSDimitry Andric unsigned BuiltinID = FD->getBuiltinID(); 18843dac3a9bSDimitry Andric if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 1885f8254f43SDimitry Andric return true; 18860623d748SDimitry Andric StringRef BuiltinName = BI.getName(BuiltinID); 1887dff0c46cSDimitry Andric if (BuiltinName.startswith("__builtin_") && 1888dff0c46cSDimitry Andric Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1889f8254f43SDimitry Andric Result = true; 1890f8254f43SDimitry Andric return false; 1891f8254f43SDimitry Andric } 1892f8254f43SDimitry Andric return true; 1893f8254f43SDimitry Andric } 1894f8254f43SDimitry Andric }; 18950623d748SDimitry Andric 189620e90f04SDimitry Andric // Make sure we're not referencing non-imported vars or functions. 18970623d748SDimitry Andric struct DLLImportFunctionVisitor 18980623d748SDimitry Andric : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 18990623d748SDimitry Andric bool SafeToInline = true; 19000623d748SDimitry Andric 190144290647SDimitry Andric bool shouldVisitImplicitCode() const { return true; } 190244290647SDimitry Andric 19030623d748SDimitry Andric bool VisitVarDecl(VarDecl *VD) { 190420e90f04SDimitry Andric if (VD->getTLSKind()) { 19050623d748SDimitry Andric // A thread-local variable cannot be imported. 190620e90f04SDimitry Andric SafeToInline = false; 19070623d748SDimitry Andric return SafeToInline; 19080623d748SDimitry Andric } 19090623d748SDimitry Andric 191020e90f04SDimitry Andric // A variable definition might imply a destructor call. 191120e90f04SDimitry Andric if (VD->isThisDeclarationADefinition()) 191220e90f04SDimitry Andric SafeToInline = !HasNonDllImportDtor(VD->getType()); 191320e90f04SDimitry Andric 191420e90f04SDimitry Andric return SafeToInline; 191520e90f04SDimitry Andric } 191620e90f04SDimitry Andric 191720e90f04SDimitry Andric bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 191820e90f04SDimitry Andric if (const auto *D = E->getTemporary()->getDestructor()) 191920e90f04SDimitry Andric SafeToInline = D->hasAttr<DLLImportAttr>(); 192020e90f04SDimitry Andric return SafeToInline; 192120e90f04SDimitry Andric } 192220e90f04SDimitry Andric 19230623d748SDimitry Andric bool VisitDeclRefExpr(DeclRefExpr *E) { 19240623d748SDimitry Andric ValueDecl *VD = E->getDecl(); 19250623d748SDimitry Andric if (isa<FunctionDecl>(VD)) 19260623d748SDimitry Andric SafeToInline = VD->hasAttr<DLLImportAttr>(); 19270623d748SDimitry Andric else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 19280623d748SDimitry Andric SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 19290623d748SDimitry Andric return SafeToInline; 19300623d748SDimitry Andric } 193120e90f04SDimitry Andric 193244290647SDimitry Andric bool VisitCXXConstructExpr(CXXConstructExpr *E) { 193344290647SDimitry Andric SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 193444290647SDimitry Andric return SafeToInline; 193544290647SDimitry Andric } 193620e90f04SDimitry Andric 193720e90f04SDimitry Andric bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 193820e90f04SDimitry Andric CXXMethodDecl *M = E->getMethodDecl(); 193920e90f04SDimitry Andric if (!M) { 194020e90f04SDimitry Andric // Call through a pointer to member function. This is safe to inline. 194120e90f04SDimitry Andric SafeToInline = true; 194220e90f04SDimitry Andric } else { 194320e90f04SDimitry Andric SafeToInline = M->hasAttr<DLLImportAttr>(); 194420e90f04SDimitry Andric } 194520e90f04SDimitry Andric return SafeToInline; 194620e90f04SDimitry Andric } 194720e90f04SDimitry Andric 19480623d748SDimitry Andric bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 19490623d748SDimitry Andric SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 19500623d748SDimitry Andric return SafeToInline; 19510623d748SDimitry Andric } 195220e90f04SDimitry Andric 19530623d748SDimitry Andric bool VisitCXXNewExpr(CXXNewExpr *E) { 19540623d748SDimitry Andric SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 19550623d748SDimitry Andric return SafeToInline; 19560623d748SDimitry Andric } 19570623d748SDimitry Andric }; 1958f8254f43SDimitry Andric } 1959f8254f43SDimitry Andric 1960dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another 1961dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin, 1962dff0c46cSDimitry Andric // ends up pointing to itself. 1963f8254f43SDimitry Andric bool 1964dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1965dff0c46cSDimitry Andric StringRef Name; 1966dff0c46cSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1967dff0c46cSDimitry Andric // asm labels are a special kind of mangling we have to support. 1968dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1969dff0c46cSDimitry Andric if (!Attr) 1970f8254f43SDimitry Andric return false; 1971dff0c46cSDimitry Andric Name = Attr->getLabel(); 1972dff0c46cSDimitry Andric } else { 1973dff0c46cSDimitry Andric Name = FD->getName(); 1974dff0c46cSDimitry Andric } 1975f8254f43SDimitry Andric 1976dff0c46cSDimitry Andric FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1977dff0c46cSDimitry Andric Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1978f8254f43SDimitry Andric return Walker.Result; 1979f8254f43SDimitry Andric } 1980f8254f43SDimitry Andric 198144290647SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1982f785676fSDimitry Andric if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1983f8254f43SDimitry Andric return true; 198459d1ed5bSDimitry Andric const auto *F = cast<FunctionDecl>(GD.getDecl()); 198559d1ed5bSDimitry Andric if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1986f8254f43SDimitry Andric return false; 19870623d748SDimitry Andric 19880623d748SDimitry Andric if (F->hasAttr<DLLImportAttr>()) { 19890623d748SDimitry Andric // Check whether it would be safe to inline this dllimport function. 19900623d748SDimitry Andric DLLImportFunctionVisitor Visitor; 19910623d748SDimitry Andric Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 19920623d748SDimitry Andric if (!Visitor.SafeToInline) 19930623d748SDimitry Andric return false; 199444290647SDimitry Andric 199544290647SDimitry Andric if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 199644290647SDimitry Andric // Implicit destructor invocations aren't captured in the AST, so the 199744290647SDimitry Andric // check above can't see them. Check for them manually here. 199844290647SDimitry Andric for (const Decl *Member : Dtor->getParent()->decls()) 199944290647SDimitry Andric if (isa<FieldDecl>(Member)) 200044290647SDimitry Andric if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 200144290647SDimitry Andric return false; 200244290647SDimitry Andric for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 200344290647SDimitry Andric if (HasNonDllImportDtor(B.getType())) 200444290647SDimitry Andric return false; 200544290647SDimitry Andric } 20060623d748SDimitry Andric } 20070623d748SDimitry Andric 2008f8254f43SDimitry Andric // PR9614. Avoid cases where the source code is lying to us. An available 2009f8254f43SDimitry Andric // externally function should have an equivalent function somewhere else, 2010f8254f43SDimitry Andric // but a function that calls itself is clearly not equivalent to the real 2011f8254f43SDimitry Andric // implementation. 2012f8254f43SDimitry Andric // This happens in glibc's btowc and in some configure checks. 2013dff0c46cSDimitry Andric return !isTriviallyRecursive(F); 2014f8254f43SDimitry Andric } 2015f8254f43SDimitry Andric 2016f9448bf3SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 2017f9448bf3SDimitry Andric return CodeGenOpts.OptimizationLevel > 0; 2018f9448bf3SDimitry Andric } 2019f9448bf3SDimitry Andric 202059d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 202159d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 2022f22ef01cSRoman Divacky 2023f22ef01cSRoman Divacky PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 2024f22ef01cSRoman Divacky Context.getSourceManager(), 2025f22ef01cSRoman Divacky "Generating code for declaration"); 2026f22ef01cSRoman Divacky 2027f785676fSDimitry Andric if (isa<FunctionDecl>(D)) { 2028ffd1746dSEd Schouten // At -O0, don't generate IR for functions with available_externally 2029ffd1746dSEd Schouten // linkage. 2030f785676fSDimitry Andric if (!shouldEmitFunction(GD)) 2031ffd1746dSEd Schouten return; 2032ffd1746dSEd Schouten 203359d1ed5bSDimitry Andric if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 2034bd5abe19SDimitry Andric // Make sure to emit the definition(s) before we emit the thunks. 2035bd5abe19SDimitry Andric // This is necessary for the generation of certain thunks. 203659d1ed5bSDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 203739d628a0SDimitry Andric ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); 203859d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 203939d628a0SDimitry Andric ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); 2040bd5abe19SDimitry Andric else 204159d1ed5bSDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 2042bd5abe19SDimitry Andric 2043f22ef01cSRoman Divacky if (Method->isVirtual()) 2044f22ef01cSRoman Divacky getVTables().EmitThunks(GD); 2045f22ef01cSRoman Divacky 2046bd5abe19SDimitry Andric return; 2047ffd1746dSEd Schouten } 2048f22ef01cSRoman Divacky 204959d1ed5bSDimitry Andric return EmitGlobalFunctionDefinition(GD, GV); 2050ffd1746dSEd Schouten } 2051f22ef01cSRoman Divacky 205259d1ed5bSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 2053e7145dcbSDimitry Andric return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 2054f22ef01cSRoman Divacky 20556122f3e6SDimitry Andric llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 2056f22ef01cSRoman Divacky } 2057f22ef01cSRoman Divacky 20580623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 20590623d748SDimitry Andric llvm::Function *NewFn); 20600623d748SDimitry Andric 2061f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 2062f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there 2063f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 2064f22ef01cSRoman Divacky /// bitcasted to the right type. 2065f22ef01cSRoman Divacky /// 2066f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 2067f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created. 206820e90f04SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 206920e90f04SDimitry Andric StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 207020e90f04SDimitry Andric bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 207144290647SDimitry Andric ForDefinition_t IsForDefinition) { 2072f785676fSDimitry Andric const Decl *D = GD.getDecl(); 2073f785676fSDimitry Andric 2074f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 2075f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2076f22ef01cSRoman Divacky if (Entry) { 20773861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 2078f785676fSDimitry Andric const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 2079f22ef01cSRoman Divacky if (FD && !FD->hasAttr<WeakAttr>()) 2080f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 2081f22ef01cSRoman Divacky } 2082f22ef01cSRoman Divacky 208339d628a0SDimitry Andric // Handle dropped DLL attributes. 208439d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 208539d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 208639d628a0SDimitry Andric 20870623d748SDimitry Andric // If there are two attempts to define the same mangled name, issue an 20880623d748SDimitry Andric // error. 20890623d748SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 20900623d748SDimitry Andric GlobalDecl OtherGD; 2091e7145dcbSDimitry Andric // Check that GD is not yet in DiagnosedConflictingDefinitions is required 2092e7145dcbSDimitry Andric // to make sure that we issue an error only once. 20930623d748SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 20940623d748SDimitry Andric (GD.getCanonicalDecl().getDecl() != 20950623d748SDimitry Andric OtherGD.getCanonicalDecl().getDecl()) && 20960623d748SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 20970623d748SDimitry Andric getDiags().Report(D->getLocation(), 20980623d748SDimitry Andric diag::err_duplicate_mangled_name); 20990623d748SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 21000623d748SDimitry Andric diag::note_previous_definition); 21010623d748SDimitry Andric } 21020623d748SDimitry Andric } 21030623d748SDimitry Andric 21040623d748SDimitry Andric if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 21050623d748SDimitry Andric (Entry->getType()->getElementType() == Ty)) { 2106f22ef01cSRoman Divacky return Entry; 21070623d748SDimitry Andric } 2108f22ef01cSRoman Divacky 2109f22ef01cSRoman Divacky // Make sure the result is of the correct type. 21100623d748SDimitry Andric // (If function is requested for a definition, we always need to create a new 21110623d748SDimitry Andric // function, not just return a bitcast.) 21120623d748SDimitry Andric if (!IsForDefinition) 211317a519f9SDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 2114f22ef01cSRoman Divacky } 2115f22ef01cSRoman Divacky 2116f22ef01cSRoman Divacky // This function doesn't have a complete type (for example, the return 2117f22ef01cSRoman Divacky // type is an incomplete struct). Use a fake type instead, and make 2118f22ef01cSRoman Divacky // sure not to try to set attributes. 2119f22ef01cSRoman Divacky bool IsIncompleteFunction = false; 2120f22ef01cSRoman Divacky 21216122f3e6SDimitry Andric llvm::FunctionType *FTy; 2122f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(Ty)) { 2123f22ef01cSRoman Divacky FTy = cast<llvm::FunctionType>(Ty); 2124f22ef01cSRoman Divacky } else { 2125bd5abe19SDimitry Andric FTy = llvm::FunctionType::get(VoidTy, false); 2126f22ef01cSRoman Divacky IsIncompleteFunction = true; 2127f22ef01cSRoman Divacky } 2128ffd1746dSEd Schouten 21290623d748SDimitry Andric llvm::Function *F = 21300623d748SDimitry Andric llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 21310623d748SDimitry Andric Entry ? StringRef() : MangledName, &getModule()); 21320623d748SDimitry Andric 21330623d748SDimitry Andric // If we already created a function with the same mangled name (but different 21340623d748SDimitry Andric // type) before, take its name and add it to the list of functions to be 21350623d748SDimitry Andric // replaced with F at the end of CodeGen. 21360623d748SDimitry Andric // 21370623d748SDimitry Andric // This happens if there is a prototype for a function (e.g. "int f()") and 21380623d748SDimitry Andric // then a definition of a different type (e.g. "int f(int x)"). 21390623d748SDimitry Andric if (Entry) { 21400623d748SDimitry Andric F->takeName(Entry); 21410623d748SDimitry Andric 21420623d748SDimitry Andric // This might be an implementation of a function without a prototype, in 21430623d748SDimitry Andric // which case, try to do special replacement of calls which match the new 21440623d748SDimitry Andric // prototype. The really key thing here is that we also potentially drop 21450623d748SDimitry Andric // arguments from the call site so as to make a direct call, which makes the 21460623d748SDimitry Andric // inliner happier and suppresses a number of optimizer warnings (!) about 21470623d748SDimitry Andric // dropping arguments. 21480623d748SDimitry Andric if (!Entry->use_empty()) { 21490623d748SDimitry Andric ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 21500623d748SDimitry Andric Entry->removeDeadConstantUsers(); 21510623d748SDimitry Andric } 21520623d748SDimitry Andric 21530623d748SDimitry Andric llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 21540623d748SDimitry Andric F, Entry->getType()->getElementType()->getPointerTo()); 21550623d748SDimitry Andric addGlobalValReplacement(Entry, BC); 21560623d748SDimitry Andric } 21570623d748SDimitry Andric 2158f22ef01cSRoman Divacky assert(F->getName() == MangledName && "name was uniqued!"); 2159f785676fSDimitry Andric if (D) 21609a199699SDimitry Andric SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk, 21619a199699SDimitry Andric IsForDefinition); 216220e90f04SDimitry Andric if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) { 216320e90f04SDimitry Andric llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex); 2164f37b6182SDimitry Andric F->addAttributes(llvm::AttributeList::FunctionIndex, B); 2165139f7f9bSDimitry Andric } 2166f22ef01cSRoman Divacky 216759d1ed5bSDimitry Andric if (!DontDefer) { 216859d1ed5bSDimitry Andric // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 216959d1ed5bSDimitry Andric // each other bottoming out with the base dtor. Therefore we emit non-base 217059d1ed5bSDimitry Andric // dtors on usage, even if there is no dtor definition in the TU. 217159d1ed5bSDimitry Andric if (D && isa<CXXDestructorDecl>(D) && 217259d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 217359d1ed5bSDimitry Andric GD.getDtorType())) 2174f37b6182SDimitry Andric addDeferredDeclToEmit(GD); 217559d1ed5bSDimitry Andric 2176f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 2177f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 2178f22ef01cSRoman Divacky // of the file. 217959d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 2180f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 218159d1ed5bSDimitry Andric // Move the potentially referenced deferred decl to the 218259d1ed5bSDimitry Andric // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 218359d1ed5bSDimitry Andric // don't need it anymore). 2184f37b6182SDimitry Andric addDeferredDeclToEmit(DDI->second); 2185f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 21862754fe60SDimitry Andric 21872754fe60SDimitry Andric // Otherwise, there are cases we have to worry about where we're 21882754fe60SDimitry Andric // using a declaration for which we must emit a definition but where 21892754fe60SDimitry Andric // we might not find a top-level definition: 21902754fe60SDimitry Andric // - member functions defined inline in their classes 21912754fe60SDimitry Andric // - friend functions defined inline in some class 21922754fe60SDimitry Andric // - special member functions with implicit definitions 21932754fe60SDimitry Andric // If we ever change our AST traversal to walk into class methods, 21942754fe60SDimitry Andric // this will be unnecessary. 21952754fe60SDimitry Andric // 219659d1ed5bSDimitry Andric // We also don't emit a definition for a function if it's going to be an 219739d628a0SDimitry Andric // entry in a vtable, unless it's already marked as used. 2198f785676fSDimitry Andric } else if (getLangOpts().CPlusPlus && D) { 21992754fe60SDimitry Andric // Look for a declaration that's lexically in a record. 220039d628a0SDimitry Andric for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 220139d628a0SDimitry Andric FD = FD->getPreviousDecl()) { 22022754fe60SDimitry Andric if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 220339d628a0SDimitry Andric if (FD->doesThisDeclarationHaveABody()) { 2204f37b6182SDimitry Andric addDeferredDeclToEmit(GD.getWithDecl(FD)); 22052754fe60SDimitry Andric break; 2206f22ef01cSRoman Divacky } 2207f22ef01cSRoman Divacky } 220839d628a0SDimitry Andric } 2209f22ef01cSRoman Divacky } 221059d1ed5bSDimitry Andric } 2211f22ef01cSRoman Divacky 2212f22ef01cSRoman Divacky // Make sure the result is of the requested type. 2213f22ef01cSRoman Divacky if (!IsIncompleteFunction) { 2214f22ef01cSRoman Divacky assert(F->getType()->getElementType() == Ty); 2215f22ef01cSRoman Divacky return F; 2216f22ef01cSRoman Divacky } 2217f22ef01cSRoman Divacky 221817a519f9SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2219f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(F, PTy); 2220f22ef01cSRoman Divacky } 2221f22ef01cSRoman Divacky 2222f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function. If Ty is 2223f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to 2224f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function). 2225f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 22266122f3e6SDimitry Andric llvm::Type *Ty, 222759d1ed5bSDimitry Andric bool ForVTable, 22280623d748SDimitry Andric bool DontDefer, 222944290647SDimitry Andric ForDefinition_t IsForDefinition) { 2230f22ef01cSRoman Divacky // If there was no specific requested type, just convert it now. 22310623d748SDimitry Andric if (!Ty) { 22320623d748SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 22330623d748SDimitry Andric auto CanonTy = Context.getCanonicalType(FD->getType()); 22340623d748SDimitry Andric Ty = getTypes().ConvertFunctionType(CanonTy, FD); 22350623d748SDimitry Andric } 2236ffd1746dSEd Schouten 22376122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 22380623d748SDimitry Andric return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 223920e90f04SDimitry Andric /*IsThunk=*/false, llvm::AttributeList(), 22400623d748SDimitry Andric IsForDefinition); 2241f22ef01cSRoman Divacky } 2242f22ef01cSRoman Divacky 224344290647SDimitry Andric static const FunctionDecl * 224444290647SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 224544290647SDimitry Andric TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 224644290647SDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 224744290647SDimitry Andric 224844290647SDimitry Andric IdentifierInfo &CII = C.Idents.get(Name); 224944290647SDimitry Andric for (const auto &Result : DC->lookup(&CII)) 225044290647SDimitry Andric if (const auto FD = dyn_cast<FunctionDecl>(Result)) 225144290647SDimitry Andric return FD; 225244290647SDimitry Andric 225344290647SDimitry Andric if (!C.getLangOpts().CPlusPlus) 225444290647SDimitry Andric return nullptr; 225544290647SDimitry Andric 225644290647SDimitry Andric // Demangle the premangled name from getTerminateFn() 225744290647SDimitry Andric IdentifierInfo &CXXII = 225844290647SDimitry Andric (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ") 225944290647SDimitry Andric ? C.Idents.get("terminate") 226044290647SDimitry Andric : C.Idents.get(Name); 226144290647SDimitry Andric 226244290647SDimitry Andric for (const auto &N : {"__cxxabiv1", "std"}) { 226344290647SDimitry Andric IdentifierInfo &NS = C.Idents.get(N); 226444290647SDimitry Andric for (const auto &Result : DC->lookup(&NS)) { 226544290647SDimitry Andric NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 226644290647SDimitry Andric if (auto LSD = dyn_cast<LinkageSpecDecl>(Result)) 226744290647SDimitry Andric for (const auto &Result : LSD->lookup(&NS)) 226844290647SDimitry Andric if ((ND = dyn_cast<NamespaceDecl>(Result))) 226944290647SDimitry Andric break; 227044290647SDimitry Andric 227144290647SDimitry Andric if (ND) 227244290647SDimitry Andric for (const auto &Result : ND->lookup(&CXXII)) 227344290647SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 227444290647SDimitry Andric return FD; 227544290647SDimitry Andric } 227644290647SDimitry Andric } 227744290647SDimitry Andric 227844290647SDimitry Andric return nullptr; 227944290647SDimitry Andric } 228044290647SDimitry Andric 2281f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified 2282f22ef01cSRoman Divacky /// type and name. 2283f22ef01cSRoman Divacky llvm::Constant * 228444290647SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 228520e90f04SDimitry Andric llvm::AttributeList ExtraAttrs, 228644290647SDimitry Andric bool Local) { 228759d1ed5bSDimitry Andric llvm::Constant *C = 228859d1ed5bSDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 228944290647SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, 229044290647SDimitry Andric ExtraAttrs); 229144290647SDimitry Andric 229244290647SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) { 229344290647SDimitry Andric if (F->empty()) { 2294139f7f9bSDimitry Andric F->setCallingConv(getRuntimeCC()); 229544290647SDimitry Andric 229644290647SDimitry Andric if (!Local && getTriple().isOSBinFormatCOFF() && 22979a199699SDimitry Andric !getCodeGenOpts().LTOVisibilityPublicStd && 22989a199699SDimitry Andric !getTriple().isWindowsGNUEnvironment()) { 229944290647SDimitry Andric const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 230044290647SDimitry Andric if (!FD || FD->hasAttr<DLLImportAttr>()) { 230144290647SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 230244290647SDimitry Andric F->setLinkage(llvm::GlobalValue::ExternalLinkage); 230344290647SDimitry Andric } 230444290647SDimitry Andric } 230544290647SDimitry Andric } 230644290647SDimitry Andric } 230744290647SDimitry Andric 2308139f7f9bSDimitry Andric return C; 2309f22ef01cSRoman Divacky } 2310f22ef01cSRoman Divacky 231139d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified 231239d628a0SDimitry Andric /// type and name. 231339d628a0SDimitry Andric llvm::Constant * 231420e90f04SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name, 231520e90f04SDimitry Andric llvm::AttributeList ExtraAttrs) { 231639d628a0SDimitry Andric llvm::Constant *C = 231739d628a0SDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 231839d628a0SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 231939d628a0SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) 232039d628a0SDimitry Andric if (F->empty()) 232139d628a0SDimitry Andric F->setCallingConv(getBuiltinCC()); 232239d628a0SDimitry Andric return C; 232339d628a0SDimitry Andric } 232439d628a0SDimitry Andric 2325dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted 2326dff0c46cSDimitry Andric /// as a constant. 2327dff0c46cSDimitry Andric /// 2328dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs 2329dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is 2330dff0c46cSDimitry Andric /// not written to during its construction. 2331dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 2332dff0c46cSDimitry Andric if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 2333f22ef01cSRoman Divacky return false; 2334bd5abe19SDimitry Andric 2335dff0c46cSDimitry Andric if (Context.getLangOpts().CPlusPlus) { 2336dff0c46cSDimitry Andric if (const CXXRecordDecl *Record 2337dff0c46cSDimitry Andric = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 2338dff0c46cSDimitry Andric return ExcludeCtor && !Record->hasMutableFields() && 2339dff0c46cSDimitry Andric Record->hasTrivialDestructor(); 2340f22ef01cSRoman Divacky } 2341bd5abe19SDimitry Andric 2342f22ef01cSRoman Divacky return true; 2343f22ef01cSRoman Divacky } 2344f22ef01cSRoman Divacky 2345f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 2346f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type. If there 2347f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 2348f22ef01cSRoman Divacky /// bitcasted to the right type. 2349f22ef01cSRoman Divacky /// 2350f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 2351f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created. 2352e7145dcbSDimitry Andric /// 2353e7145dcbSDimitry Andric /// If IsForDefinition is true, it is guranteed that an actual global with 2354e7145dcbSDimitry Andric /// type Ty will be returned, not conversion of a variable with the same 2355e7145dcbSDimitry Andric /// mangled name but some other type. 2356f22ef01cSRoman Divacky llvm::Constant * 23576122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 23586122f3e6SDimitry Andric llvm::PointerType *Ty, 2359e7145dcbSDimitry Andric const VarDecl *D, 236044290647SDimitry Andric ForDefinition_t IsForDefinition) { 2361f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 2362f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2363f22ef01cSRoman Divacky if (Entry) { 23643861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 2365f22ef01cSRoman Divacky if (D && !D->hasAttr<WeakAttr>()) 2366f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 2367f22ef01cSRoman Divacky } 2368f22ef01cSRoman Divacky 236939d628a0SDimitry Andric // Handle dropped DLL attributes. 237039d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 237139d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 237239d628a0SDimitry Andric 2373f22ef01cSRoman Divacky if (Entry->getType() == Ty) 2374f22ef01cSRoman Divacky return Entry; 2375f22ef01cSRoman Divacky 2376e7145dcbSDimitry Andric // If there are two attempts to define the same mangled name, issue an 2377e7145dcbSDimitry Andric // error. 2378e7145dcbSDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 2379e7145dcbSDimitry Andric GlobalDecl OtherGD; 2380e7145dcbSDimitry Andric const VarDecl *OtherD; 2381e7145dcbSDimitry Andric 2382e7145dcbSDimitry Andric // Check that D is not yet in DiagnosedConflictingDefinitions is required 2383e7145dcbSDimitry Andric // to make sure that we issue an error only once. 2384e7145dcbSDimitry Andric if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 2385e7145dcbSDimitry Andric (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 2386e7145dcbSDimitry Andric (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 2387e7145dcbSDimitry Andric OtherD->hasInit() && 2388e7145dcbSDimitry Andric DiagnosedConflictingDefinitions.insert(D).second) { 2389e7145dcbSDimitry Andric getDiags().Report(D->getLocation(), 2390e7145dcbSDimitry Andric diag::err_duplicate_mangled_name); 2391e7145dcbSDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 2392e7145dcbSDimitry Andric diag::note_previous_definition); 2393e7145dcbSDimitry Andric } 2394e7145dcbSDimitry Andric } 2395e7145dcbSDimitry Andric 2396f22ef01cSRoman Divacky // Make sure the result is of the correct type. 2397f785676fSDimitry Andric if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 2398f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 2399f785676fSDimitry Andric 2400e7145dcbSDimitry Andric // (If global is requested for a definition, we always need to create a new 2401e7145dcbSDimitry Andric // global, not just return a bitcast.) 2402e7145dcbSDimitry Andric if (!IsForDefinition) 2403f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(Entry, Ty); 2404f22ef01cSRoman Divacky } 2405f22ef01cSRoman Divacky 2406c4394386SDimitry Andric auto AddrSpace = GetGlobalVarAddressSpace(D); 2407c4394386SDimitry Andric auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace); 2408c4394386SDimitry Andric 240959d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 241059d1ed5bSDimitry Andric getModule(), Ty->getElementType(), false, 241159d1ed5bSDimitry Andric llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 2412c4394386SDimitry Andric llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace); 241359d1ed5bSDimitry Andric 2414e7145dcbSDimitry Andric // If we already created a global with the same mangled name (but different 2415e7145dcbSDimitry Andric // type) before, take its name and remove it from its parent. 2416e7145dcbSDimitry Andric if (Entry) { 2417e7145dcbSDimitry Andric GV->takeName(Entry); 2418e7145dcbSDimitry Andric 2419e7145dcbSDimitry Andric if (!Entry->use_empty()) { 2420e7145dcbSDimitry Andric llvm::Constant *NewPtrForOldDecl = 2421e7145dcbSDimitry Andric llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2422e7145dcbSDimitry Andric Entry->replaceAllUsesWith(NewPtrForOldDecl); 2423e7145dcbSDimitry Andric } 2424e7145dcbSDimitry Andric 2425e7145dcbSDimitry Andric Entry->eraseFromParent(); 2426e7145dcbSDimitry Andric } 2427e7145dcbSDimitry Andric 2428f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 2429f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 2430f22ef01cSRoman Divacky // of the file. 243159d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 2432f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 2433f22ef01cSRoman Divacky // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 2434f22ef01cSRoman Divacky // list, and remove it from DeferredDecls (since we don't need it anymore). 2435f37b6182SDimitry Andric addDeferredDeclToEmit(DDI->second); 2436f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 2437f22ef01cSRoman Divacky } 2438f22ef01cSRoman Divacky 2439f22ef01cSRoman Divacky // Handle things which are present even on external declarations. 2440f22ef01cSRoman Divacky if (D) { 2441f22ef01cSRoman Divacky // FIXME: This code is overly simple and should be merged with other global 2442f22ef01cSRoman Divacky // handling. 2443dff0c46cSDimitry Andric GV->setConstant(isTypeConstant(D->getType(), false)); 2444f22ef01cSRoman Divacky 244533956c43SDimitry Andric GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 244633956c43SDimitry Andric 24479a199699SDimitry Andric setLinkageForGV(GV, D); 24489a199699SDimitry Andric setGlobalVisibility(GV, D, NotForDefinition); 24492754fe60SDimitry Andric 2450284c1978SDimitry Andric if (D->getTLSKind()) { 2451284c1978SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 24520623d748SDimitry Andric CXXThreadLocals.push_back(D); 24537ae0e2c9SDimitry Andric setTLSMode(GV, *D); 2454f22ef01cSRoman Divacky } 2455f785676fSDimitry Andric 2456f785676fSDimitry Andric // If required by the ABI, treat declarations of static data members with 2457f785676fSDimitry Andric // inline initializers as definitions. 245859d1ed5bSDimitry Andric if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 2459f785676fSDimitry Andric EmitGlobalVarDefinition(D); 2460284c1978SDimitry Andric } 2461f22ef01cSRoman Divacky 24629a199699SDimitry Andric // Emit section information for extern variables. 24639a199699SDimitry Andric if (D->hasExternalStorage()) { 24649a199699SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 24659a199699SDimitry Andric GV->setSection(SA->getName()); 24669a199699SDimitry Andric } 24679a199699SDimitry Andric 246859d1ed5bSDimitry Andric // Handle XCore specific ABI requirements. 246944290647SDimitry Andric if (getTriple().getArch() == llvm::Triple::xcore && 247059d1ed5bSDimitry Andric D->getLanguageLinkage() == CLanguageLinkage && 247159d1ed5bSDimitry Andric D->getType().isConstant(Context) && 247259d1ed5bSDimitry Andric isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 247359d1ed5bSDimitry Andric GV->setSection(".cp.rodata"); 24749a199699SDimitry Andric 24759a199699SDimitry Andric // Check if we a have a const declaration with an initializer, we may be 24769a199699SDimitry Andric // able to emit it as available_externally to expose it's value to the 24779a199699SDimitry Andric // optimizer. 24789a199699SDimitry Andric if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 24799a199699SDimitry Andric D->getType().isConstQualified() && !GV->hasInitializer() && 24809a199699SDimitry Andric !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 24819a199699SDimitry Andric const auto *Record = 24829a199699SDimitry Andric Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 24839a199699SDimitry Andric bool HasMutableFields = Record && Record->hasMutableFields(); 24849a199699SDimitry Andric if (!HasMutableFields) { 24859a199699SDimitry Andric const VarDecl *InitDecl; 24869a199699SDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 24879a199699SDimitry Andric if (InitExpr) { 24889a199699SDimitry Andric ConstantEmitter emitter(*this); 24899a199699SDimitry Andric llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 24909a199699SDimitry Andric if (Init) { 24919a199699SDimitry Andric auto *InitType = Init->getType(); 24929a199699SDimitry Andric if (GV->getType()->getElementType() != InitType) { 24939a199699SDimitry Andric // The type of the initializer does not match the definition. 24949a199699SDimitry Andric // This happens when an initializer has a different type from 24959a199699SDimitry Andric // the type of the global (because of padding at the end of a 24969a199699SDimitry Andric // structure for instance). 24979a199699SDimitry Andric GV->setName(StringRef()); 24989a199699SDimitry Andric // Make a new global with the correct type, this is now guaranteed 24999a199699SDimitry Andric // to work. 25009a199699SDimitry Andric auto *NewGV = cast<llvm::GlobalVariable>( 25019a199699SDimitry Andric GetAddrOfGlobalVar(D, InitType, IsForDefinition)); 25029a199699SDimitry Andric 25039a199699SDimitry Andric // Erase the old global, since it is no longer used. 25049a199699SDimitry Andric cast<llvm::GlobalValue>(GV)->eraseFromParent(); 25059a199699SDimitry Andric GV = NewGV; 25069a199699SDimitry Andric } else { 25079a199699SDimitry Andric GV->setInitializer(Init); 25089a199699SDimitry Andric GV->setConstant(true); 25099a199699SDimitry Andric GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 25109a199699SDimitry Andric } 25119a199699SDimitry Andric emitter.finalize(GV); 25129a199699SDimitry Andric } 25139a199699SDimitry Andric } 25149a199699SDimitry Andric } 25159a199699SDimitry Andric } 251659d1ed5bSDimitry Andric } 251759d1ed5bSDimitry Andric 25189a199699SDimitry Andric LangAS ExpectedAS = 2519c4394386SDimitry Andric D ? D->getType().getAddressSpace() 25209a199699SDimitry Andric : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 2521c4394386SDimitry Andric assert(getContext().getTargetAddressSpace(ExpectedAS) == 2522c4394386SDimitry Andric Ty->getPointerAddressSpace()); 2523c4394386SDimitry Andric if (AddrSpace != ExpectedAS) 2524c4394386SDimitry Andric return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace, 2525c4394386SDimitry Andric ExpectedAS, Ty); 2526f785676fSDimitry Andric 2527f22ef01cSRoman Divacky return GV; 2528f22ef01cSRoman Divacky } 2529f22ef01cSRoman Divacky 25300623d748SDimitry Andric llvm::Constant * 25310623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, 253244290647SDimitry Andric ForDefinition_t IsForDefinition) { 253344290647SDimitry Andric const Decl *D = GD.getDecl(); 253444290647SDimitry Andric if (isa<CXXConstructorDecl>(D)) 253544290647SDimitry Andric return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D), 25360623d748SDimitry Andric getFromCtorType(GD.getCtorType()), 25370623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 25380623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 253944290647SDimitry Andric else if (isa<CXXDestructorDecl>(D)) 254044290647SDimitry Andric return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D), 25410623d748SDimitry Andric getFromDtorType(GD.getDtorType()), 25420623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 25430623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 254444290647SDimitry Andric else if (isa<CXXMethodDecl>(D)) { 25450623d748SDimitry Andric auto FInfo = &getTypes().arrangeCXXMethodDeclaration( 254644290647SDimitry Andric cast<CXXMethodDecl>(D)); 25470623d748SDimitry Andric auto Ty = getTypes().GetFunctionType(*FInfo); 25480623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 25490623d748SDimitry Andric IsForDefinition); 255044290647SDimitry Andric } else if (isa<FunctionDecl>(D)) { 25510623d748SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 25520623d748SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 25530623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 25540623d748SDimitry Andric IsForDefinition); 25550623d748SDimitry Andric } else 255644290647SDimitry Andric return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, 2557e7145dcbSDimitry Andric IsForDefinition); 25580623d748SDimitry Andric } 2559f22ef01cSRoman Divacky 25602754fe60SDimitry Andric llvm::GlobalVariable * 25616122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 25626122f3e6SDimitry Andric llvm::Type *Ty, 25632754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage) { 25642754fe60SDimitry Andric llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 256559d1ed5bSDimitry Andric llvm::GlobalVariable *OldGV = nullptr; 25662754fe60SDimitry Andric 25672754fe60SDimitry Andric if (GV) { 25682754fe60SDimitry Andric // Check if the variable has the right type. 25692754fe60SDimitry Andric if (GV->getType()->getElementType() == Ty) 25702754fe60SDimitry Andric return GV; 25712754fe60SDimitry Andric 25722754fe60SDimitry Andric // Because C++ name mangling, the only way we can end up with an already 25732754fe60SDimitry Andric // existing global with the same name is if it has been declared extern "C". 25742754fe60SDimitry Andric assert(GV->isDeclaration() && "Declaration has wrong type!"); 25752754fe60SDimitry Andric OldGV = GV; 25762754fe60SDimitry Andric } 25772754fe60SDimitry Andric 25782754fe60SDimitry Andric // Create a new variable. 25792754fe60SDimitry Andric GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 258059d1ed5bSDimitry Andric Linkage, nullptr, Name); 25812754fe60SDimitry Andric 25822754fe60SDimitry Andric if (OldGV) { 25832754fe60SDimitry Andric // Replace occurrences of the old variable if needed. 25842754fe60SDimitry Andric GV->takeName(OldGV); 25852754fe60SDimitry Andric 25862754fe60SDimitry Andric if (!OldGV->use_empty()) { 25872754fe60SDimitry Andric llvm::Constant *NewPtrForOldDecl = 25882754fe60SDimitry Andric llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 25892754fe60SDimitry Andric OldGV->replaceAllUsesWith(NewPtrForOldDecl); 25902754fe60SDimitry Andric } 25912754fe60SDimitry Andric 25922754fe60SDimitry Andric OldGV->eraseFromParent(); 25932754fe60SDimitry Andric } 25942754fe60SDimitry Andric 259533956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker() && 259633956c43SDimitry Andric !GV->hasAvailableExternallyLinkage()) 259733956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 259833956c43SDimitry Andric 25992754fe60SDimitry Andric return GV; 26002754fe60SDimitry Andric } 26012754fe60SDimitry Andric 2602f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 2603f22ef01cSRoman Divacky /// given global variable. If Ty is non-null and if the global doesn't exist, 2604cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the 2605e7145dcbSDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guranteed 2606e7145dcbSDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a 2607e7145dcbSDimitry Andric /// variable with the same mangled name but some other type. 2608f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 2609e7145dcbSDimitry Andric llvm::Type *Ty, 261044290647SDimitry Andric ForDefinition_t IsForDefinition) { 2611f22ef01cSRoman Divacky assert(D->hasGlobalStorage() && "Not a global variable"); 2612f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 261359d1ed5bSDimitry Andric if (!Ty) 2614f22ef01cSRoman Divacky Ty = getTypes().ConvertTypeForMem(ASTTy); 2615f22ef01cSRoman Divacky 26166122f3e6SDimitry Andric llvm::PointerType *PTy = 26173b0f4066SDimitry Andric llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 2618f22ef01cSRoman Divacky 26196122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2620e7145dcbSDimitry Andric return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition); 2621f22ef01cSRoman Divacky } 2622f22ef01cSRoman Divacky 2623f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the 2624f22ef01cSRoman Divacky /// specified type and name. 2625f22ef01cSRoman Divacky llvm::Constant * 26266122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 26276122f3e6SDimitry Andric StringRef Name) { 262859d1ed5bSDimitry Andric return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr); 2629f22ef01cSRoman Divacky } 2630f22ef01cSRoman Divacky 2631f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 2632f22ef01cSRoman Divacky assert(!D->getInit() && "Cannot emit definite definitions here!"); 2633f22ef01cSRoman Divacky 26346122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2635e7145dcbSDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(MangledName); 2636e7145dcbSDimitry Andric 2637e7145dcbSDimitry Andric // We already have a definition, not declaration, with the same mangled name. 2638e7145dcbSDimitry Andric // Emitting of declaration is not required (and actually overwrites emitted 2639e7145dcbSDimitry Andric // definition). 2640e7145dcbSDimitry Andric if (GV && !GV->isDeclaration()) 2641e7145dcbSDimitry Andric return; 2642e7145dcbSDimitry Andric 2643e7145dcbSDimitry Andric // If we have not seen a reference to this variable yet, place it into the 2644e7145dcbSDimitry Andric // deferred declarations table to be emitted if needed later. 2645e7145dcbSDimitry Andric if (!MustBeEmitted(D) && !GV) { 2646f22ef01cSRoman Divacky DeferredDecls[MangledName] = D; 2647f22ef01cSRoman Divacky return; 2648f22ef01cSRoman Divacky } 2649f22ef01cSRoman Divacky 2650f22ef01cSRoman Divacky // The tentative definition is the only definition. 2651f22ef01cSRoman Divacky EmitGlobalVarDefinition(D); 2652f22ef01cSRoman Divacky } 2653f22ef01cSRoman Divacky 26546122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 26552754fe60SDimitry Andric return Context.toCharUnitsFromBits( 26560623d748SDimitry Andric getDataLayout().getTypeStoreSizeInBits(Ty)); 2657f22ef01cSRoman Divacky } 2658f22ef01cSRoman Divacky 26599a199699SDimitry Andric LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 26609a199699SDimitry Andric LangAS AddrSpace = LangAS::Default; 2661c4394386SDimitry Andric if (LangOpts.OpenCL) { 26629a199699SDimitry Andric AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global; 2663c4394386SDimitry Andric assert(AddrSpace == LangAS::opencl_global || 2664c4394386SDimitry Andric AddrSpace == LangAS::opencl_constant || 2665c4394386SDimitry Andric AddrSpace == LangAS::opencl_local || 2666c4394386SDimitry Andric AddrSpace >= LangAS::FirstTargetAddressSpace); 2667c4394386SDimitry Andric return AddrSpace; 26687ae0e2c9SDimitry Andric } 26697ae0e2c9SDimitry Andric 2670c4394386SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 2671c4394386SDimitry Andric if (D && D->hasAttr<CUDAConstantAttr>()) 2672c4394386SDimitry Andric return LangAS::cuda_constant; 2673c4394386SDimitry Andric else if (D && D->hasAttr<CUDASharedAttr>()) 2674c4394386SDimitry Andric return LangAS::cuda_shared; 2675c4394386SDimitry Andric else 2676c4394386SDimitry Andric return LangAS::cuda_device; 2677c4394386SDimitry Andric } 2678c4394386SDimitry Andric 2679c4394386SDimitry Andric return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 26807ae0e2c9SDimitry Andric } 26817ae0e2c9SDimitry Andric 2682284c1978SDimitry Andric template<typename SomeDecl> 2683284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 2684284c1978SDimitry Andric llvm::GlobalValue *GV) { 2685284c1978SDimitry Andric if (!getLangOpts().CPlusPlus) 2686284c1978SDimitry Andric return; 2687284c1978SDimitry Andric 2688284c1978SDimitry Andric // Must have 'used' attribute, or else inline assembly can't rely on 2689284c1978SDimitry Andric // the name existing. 2690284c1978SDimitry Andric if (!D->template hasAttr<UsedAttr>()) 2691284c1978SDimitry Andric return; 2692284c1978SDimitry Andric 2693284c1978SDimitry Andric // Must have internal linkage and an ordinary name. 2694f785676fSDimitry Andric if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 2695284c1978SDimitry Andric return; 2696284c1978SDimitry Andric 2697284c1978SDimitry Andric // Must be in an extern "C" context. Entities declared directly within 2698284c1978SDimitry Andric // a record are not extern "C" even if the record is in such a context. 2699f785676fSDimitry Andric const SomeDecl *First = D->getFirstDecl(); 2700284c1978SDimitry Andric if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 2701284c1978SDimitry Andric return; 2702284c1978SDimitry Andric 2703284c1978SDimitry Andric // OK, this is an internal linkage entity inside an extern "C" linkage 2704284c1978SDimitry Andric // specification. Make a note of that so we can give it the "expected" 2705284c1978SDimitry Andric // mangled name if nothing else is using that name. 2706284c1978SDimitry Andric std::pair<StaticExternCMap::iterator, bool> R = 2707284c1978SDimitry Andric StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 2708284c1978SDimitry Andric 2709284c1978SDimitry Andric // If we have multiple internal linkage entities with the same name 2710284c1978SDimitry Andric // in extern "C" regions, none of them gets that name. 2711284c1978SDimitry Andric if (!R.second) 271259d1ed5bSDimitry Andric R.first->second = nullptr; 2713284c1978SDimitry Andric } 2714284c1978SDimitry Andric 271533956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 271633956c43SDimitry Andric if (!CGM.supportsCOMDAT()) 271733956c43SDimitry Andric return false; 271833956c43SDimitry Andric 271933956c43SDimitry Andric if (D.hasAttr<SelectAnyAttr>()) 272033956c43SDimitry Andric return true; 272133956c43SDimitry Andric 272233956c43SDimitry Andric GVALinkage Linkage; 272333956c43SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(&D)) 272433956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 272533956c43SDimitry Andric else 272633956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 272733956c43SDimitry Andric 272833956c43SDimitry Andric switch (Linkage) { 272933956c43SDimitry Andric case GVA_Internal: 273033956c43SDimitry Andric case GVA_AvailableExternally: 273133956c43SDimitry Andric case GVA_StrongExternal: 273233956c43SDimitry Andric return false; 273333956c43SDimitry Andric case GVA_DiscardableODR: 273433956c43SDimitry Andric case GVA_StrongODR: 273533956c43SDimitry Andric return true; 273633956c43SDimitry Andric } 273733956c43SDimitry Andric llvm_unreachable("No such linkage"); 273833956c43SDimitry Andric } 273933956c43SDimitry Andric 274033956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 274133956c43SDimitry Andric llvm::GlobalObject &GO) { 274233956c43SDimitry Andric if (!shouldBeInCOMDAT(*this, D)) 274333956c43SDimitry Andric return; 274433956c43SDimitry Andric GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 274533956c43SDimitry Andric } 274633956c43SDimitry Andric 2747e7145dcbSDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition. 2748e7145dcbSDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 2749e7145dcbSDimitry Andric bool IsTentative) { 275044290647SDimitry Andric // OpenCL global variables of sampler type are translated to function calls, 275144290647SDimitry Andric // therefore no need to be translated. 2752f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 275344290647SDimitry Andric if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 275444290647SDimitry Andric return; 275544290647SDimitry Andric 275644290647SDimitry Andric llvm::Constant *Init = nullptr; 2757dff0c46cSDimitry Andric CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2758dff0c46cSDimitry Andric bool NeedsGlobalCtor = false; 2759dff0c46cSDimitry Andric bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 2760f22ef01cSRoman Divacky 2761dff0c46cSDimitry Andric const VarDecl *InitDecl; 2762dff0c46cSDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 2763f22ef01cSRoman Divacky 27649a199699SDimitry Andric Optional<ConstantEmitter> emitter; 27659a199699SDimitry Andric 2766e7145dcbSDimitry Andric // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 2767e7145dcbSDimitry Andric // as part of their declaration." Sema has already checked for 2768e7145dcbSDimitry Andric // error cases, so we just need to set Init to UndefValue. 2769e7145dcbSDimitry Andric if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 2770e7145dcbSDimitry Andric D->hasAttr<CUDASharedAttr>()) 27710623d748SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 2772e7145dcbSDimitry Andric else if (!InitExpr) { 2773f22ef01cSRoman Divacky // This is a tentative definition; tentative definitions are 2774f22ef01cSRoman Divacky // implicitly initialized with { 0 }. 2775f22ef01cSRoman Divacky // 2776f22ef01cSRoman Divacky // Note that tentative definitions are only emitted at the end of 2777f22ef01cSRoman Divacky // a translation unit, so they should never have incomplete 2778f22ef01cSRoman Divacky // type. In addition, EmitTentativeDefinition makes sure that we 2779f22ef01cSRoman Divacky // never attempt to emit a tentative definition if a real one 2780f22ef01cSRoman Divacky // exists. A use may still exists, however, so we still may need 2781f22ef01cSRoman Divacky // to do a RAUW. 2782f22ef01cSRoman Divacky assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 2783f22ef01cSRoman Divacky Init = EmitNullConstant(D->getType()); 2784f22ef01cSRoman Divacky } else { 27857ae0e2c9SDimitry Andric initializedGlobalDecl = GlobalDecl(D); 27869a199699SDimitry Andric emitter.emplace(*this); 27879a199699SDimitry Andric Init = emitter->tryEmitForInitializer(*InitDecl); 2788f785676fSDimitry Andric 2789f22ef01cSRoman Divacky if (!Init) { 2790f22ef01cSRoman Divacky QualType T = InitExpr->getType(); 2791f22ef01cSRoman Divacky if (D->getType()->isReferenceType()) 2792f22ef01cSRoman Divacky T = D->getType(); 2793f22ef01cSRoman Divacky 2794dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus) { 2795f22ef01cSRoman Divacky Init = EmitNullConstant(T); 2796dff0c46cSDimitry Andric NeedsGlobalCtor = true; 2797f22ef01cSRoman Divacky } else { 2798f22ef01cSRoman Divacky ErrorUnsupported(D, "static initializer"); 2799f22ef01cSRoman Divacky Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 2800f22ef01cSRoman Divacky } 2801e580952dSDimitry Andric } else { 2802e580952dSDimitry Andric // We don't need an initializer, so remove the entry for the delayed 2803dff0c46cSDimitry Andric // initializer position (just in case this entry was delayed) if we 2804dff0c46cSDimitry Andric // also don't need to register a destructor. 2805dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 2806e580952dSDimitry Andric DelayedCXXInitPosition.erase(D); 2807f22ef01cSRoman Divacky } 2808f22ef01cSRoman Divacky } 2809f22ef01cSRoman Divacky 28106122f3e6SDimitry Andric llvm::Type* InitType = Init->getType(); 2811e7145dcbSDimitry Andric llvm::Constant *Entry = 281244290647SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 2813f22ef01cSRoman Divacky 2814f22ef01cSRoman Divacky // Strip off a bitcast if we got one back. 281559d1ed5bSDimitry Andric if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2816f22ef01cSRoman Divacky assert(CE->getOpcode() == llvm::Instruction::BitCast || 2817f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 2818f785676fSDimitry Andric // All zero index gep. 2819f22ef01cSRoman Divacky CE->getOpcode() == llvm::Instruction::GetElementPtr); 2820f22ef01cSRoman Divacky Entry = CE->getOperand(0); 2821f22ef01cSRoman Divacky } 2822f22ef01cSRoman Divacky 2823f22ef01cSRoman Divacky // Entry is now either a Function or GlobalVariable. 282459d1ed5bSDimitry Andric auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 2825f22ef01cSRoman Divacky 2826f22ef01cSRoman Divacky // We have a definition after a declaration with the wrong type. 2827f22ef01cSRoman Divacky // We must make a new GlobalVariable* and update everything that used OldGV 2828f22ef01cSRoman Divacky // (a declaration or tentative definition) with the new GlobalVariable* 2829f22ef01cSRoman Divacky // (which will be a definition). 2830f22ef01cSRoman Divacky // 2831f22ef01cSRoman Divacky // This happens if there is a prototype for a global (e.g. 2832f22ef01cSRoman Divacky // "extern int x[];") and then a definition of a different type (e.g. 2833f22ef01cSRoman Divacky // "int x[10];"). This also happens when an initializer has a different type 2834f22ef01cSRoman Divacky // from the type of the global (this happens with unions). 2835c4394386SDimitry Andric if (!GV || GV->getType()->getElementType() != InitType || 28363b0f4066SDimitry Andric GV->getType()->getAddressSpace() != 2837c4394386SDimitry Andric getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 2838f22ef01cSRoman Divacky 2839f22ef01cSRoman Divacky // Move the old entry aside so that we'll create a new one. 28406122f3e6SDimitry Andric Entry->setName(StringRef()); 2841f22ef01cSRoman Divacky 2842f22ef01cSRoman Divacky // Make a new global with the correct type, this is now guaranteed to work. 2843e7145dcbSDimitry Andric GV = cast<llvm::GlobalVariable>( 284444290647SDimitry Andric GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))); 2845f22ef01cSRoman Divacky 2846f22ef01cSRoman Divacky // Replace all uses of the old global with the new global 2847f22ef01cSRoman Divacky llvm::Constant *NewPtrForOldDecl = 2848f22ef01cSRoman Divacky llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2849f22ef01cSRoman Divacky Entry->replaceAllUsesWith(NewPtrForOldDecl); 2850f22ef01cSRoman Divacky 2851f22ef01cSRoman Divacky // Erase the old global, since it is no longer used. 2852f22ef01cSRoman Divacky cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 2853f22ef01cSRoman Divacky } 2854f22ef01cSRoman Divacky 2855284c1978SDimitry Andric MaybeHandleStaticInExternC(D, GV); 2856284c1978SDimitry Andric 28576122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 28586122f3e6SDimitry Andric AddGlobalAnnotations(D, GV); 2859f22ef01cSRoman Divacky 2860e7145dcbSDimitry Andric // Set the llvm linkage type as appropriate. 2861e7145dcbSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 2862e7145dcbSDimitry Andric getLLVMLinkageVarDefinition(D, GV->isConstant()); 2863e7145dcbSDimitry Andric 28640623d748SDimitry Andric // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 28650623d748SDimitry Andric // the device. [...]" 28660623d748SDimitry Andric // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 28670623d748SDimitry Andric // __device__, declares a variable that: [...] 28680623d748SDimitry Andric // Is accessible from all the threads within the grid and from the host 28690623d748SDimitry Andric // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 28700623d748SDimitry Andric // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 2871e7145dcbSDimitry Andric if (GV && LangOpts.CUDA) { 2872e7145dcbSDimitry Andric if (LangOpts.CUDAIsDevice) { 2873e7145dcbSDimitry Andric if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) 28740623d748SDimitry Andric GV->setExternallyInitialized(true); 2875e7145dcbSDimitry Andric } else { 2876e7145dcbSDimitry Andric // Host-side shadows of external declarations of device-side 2877e7145dcbSDimitry Andric // global variables become internal definitions. These have to 2878e7145dcbSDimitry Andric // be internal in order to prevent name conflicts with global 2879e7145dcbSDimitry Andric // host variables with the same name in a different TUs. 2880e7145dcbSDimitry Andric if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) { 2881e7145dcbSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 2882e7145dcbSDimitry Andric 2883e7145dcbSDimitry Andric // Shadow variables and their properties must be registered 2884e7145dcbSDimitry Andric // with CUDA runtime. 2885e7145dcbSDimitry Andric unsigned Flags = 0; 2886e7145dcbSDimitry Andric if (!D->hasDefinition()) 2887e7145dcbSDimitry Andric Flags |= CGCUDARuntime::ExternDeviceVar; 2888e7145dcbSDimitry Andric if (D->hasAttr<CUDAConstantAttr>()) 2889e7145dcbSDimitry Andric Flags |= CGCUDARuntime::ConstantDeviceVar; 2890e7145dcbSDimitry Andric getCUDARuntime().registerDeviceVar(*GV, Flags); 2891e7145dcbSDimitry Andric } else if (D->hasAttr<CUDASharedAttr>()) 2892e7145dcbSDimitry Andric // __shared__ variables are odd. Shadows do get created, but 2893e7145dcbSDimitry Andric // they are not registered with the CUDA runtime, so they 2894e7145dcbSDimitry Andric // can't really be used to access their device-side 2895e7145dcbSDimitry Andric // counterparts. It's not clear yet whether it's nvcc's bug or 2896e7145dcbSDimitry Andric // a feature, but we've got to do the same for compatibility. 2897e7145dcbSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 2898e7145dcbSDimitry Andric } 28990623d748SDimitry Andric } 29009a199699SDimitry Andric 2901f22ef01cSRoman Divacky GV->setInitializer(Init); 29029a199699SDimitry Andric if (emitter) emitter->finalize(GV); 2903f22ef01cSRoman Divacky 2904f22ef01cSRoman Divacky // If it is safe to mark the global 'constant', do so now. 2905dff0c46cSDimitry Andric GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 2906dff0c46cSDimitry Andric isTypeConstant(D->getType(), true)); 2907f22ef01cSRoman Divacky 290839d628a0SDimitry Andric // If it is in a read-only section, mark it 'constant'. 290939d628a0SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 291039d628a0SDimitry Andric const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 291139d628a0SDimitry Andric if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 291239d628a0SDimitry Andric GV->setConstant(true); 291339d628a0SDimitry Andric } 291439d628a0SDimitry Andric 2915f22ef01cSRoman Divacky GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 2916f22ef01cSRoman Divacky 2917f785676fSDimitry Andric 29180623d748SDimitry Andric // On Darwin, if the normal linkage of a C++ thread_local variable is 29190623d748SDimitry Andric // LinkOnce or Weak, we keep the normal linkage to prevent multiple 29200623d748SDimitry Andric // copies within a linkage unit; otherwise, the backing variable has 29210623d748SDimitry Andric // internal linkage and all accesses should just be calls to the 292259d1ed5bSDimitry Andric // Itanium-specified entry point, which has the normal linkage of the 29230623d748SDimitry Andric // variable. This is to preserve the ability to change the implementation 29240623d748SDimitry Andric // behind the scenes. 292539d628a0SDimitry Andric if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic && 29260623d748SDimitry Andric Context.getTargetInfo().getTriple().isOSDarwin() && 29270623d748SDimitry Andric !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) && 29280623d748SDimitry Andric !llvm::GlobalVariable::isWeakLinkage(Linkage)) 292959d1ed5bSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 293059d1ed5bSDimitry Andric 293159d1ed5bSDimitry Andric GV->setLinkage(Linkage); 293259d1ed5bSDimitry Andric if (D->hasAttr<DLLImportAttr>()) 293359d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 293459d1ed5bSDimitry Andric else if (D->hasAttr<DLLExportAttr>()) 293559d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 293639d628a0SDimitry Andric else 293739d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 2938f785676fSDimitry Andric 293944290647SDimitry Andric if (Linkage == llvm::GlobalVariable::CommonLinkage) { 2940f22ef01cSRoman Divacky // common vars aren't constant even if declared const. 2941f22ef01cSRoman Divacky GV->setConstant(false); 294244290647SDimitry Andric // Tentative definition of global variables may be initialized with 294344290647SDimitry Andric // non-zero null pointers. In this case they should have weak linkage 294444290647SDimitry Andric // since common linkage must have zero initializer and must not have 294544290647SDimitry Andric // explicit section therefore cannot have non-zero initial value. 294644290647SDimitry Andric if (!GV->getInitializer()->isNullValue()) 294744290647SDimitry Andric GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 294844290647SDimitry Andric } 2949f22ef01cSRoman Divacky 295059d1ed5bSDimitry Andric setNonAliasAttributes(D, GV); 2951f22ef01cSRoman Divacky 295239d628a0SDimitry Andric if (D->getTLSKind() && !GV->isThreadLocal()) { 295339d628a0SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 29540623d748SDimitry Andric CXXThreadLocals.push_back(D); 295539d628a0SDimitry Andric setTLSMode(GV, *D); 295639d628a0SDimitry Andric } 295739d628a0SDimitry Andric 295833956c43SDimitry Andric maybeSetTrivialComdat(*D, *GV); 295933956c43SDimitry Andric 29602754fe60SDimitry Andric // Emit the initializer function if necessary. 2961dff0c46cSDimitry Andric if (NeedsGlobalCtor || NeedsGlobalDtor) 2962dff0c46cSDimitry Andric EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 29632754fe60SDimitry Andric 296439d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 29653861d79fSDimitry Andric 2966f22ef01cSRoman Divacky // Emit global variable debug information. 29676122f3e6SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 2968e7145dcbSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 2969f22ef01cSRoman Divacky DI->EmitGlobalVariable(GV, D); 2970f22ef01cSRoman Divacky } 2971f22ef01cSRoman Divacky 297239d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context, 297333956c43SDimitry Andric CodeGenModule &CGM, const VarDecl *D, 297433956c43SDimitry Andric bool NoCommon) { 297559d1ed5bSDimitry Andric // Don't give variables common linkage if -fno-common was specified unless it 297659d1ed5bSDimitry Andric // was overridden by a NoCommon attribute. 297759d1ed5bSDimitry Andric if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 297859d1ed5bSDimitry Andric return true; 297959d1ed5bSDimitry Andric 298059d1ed5bSDimitry Andric // C11 6.9.2/2: 298159d1ed5bSDimitry Andric // A declaration of an identifier for an object that has file scope without 298259d1ed5bSDimitry Andric // an initializer, and without a storage-class specifier or with the 298359d1ed5bSDimitry Andric // storage-class specifier static, constitutes a tentative definition. 298459d1ed5bSDimitry Andric if (D->getInit() || D->hasExternalStorage()) 298559d1ed5bSDimitry Andric return true; 298659d1ed5bSDimitry Andric 298759d1ed5bSDimitry Andric // A variable cannot be both common and exist in a section. 298859d1ed5bSDimitry Andric if (D->hasAttr<SectionAttr>()) 298959d1ed5bSDimitry Andric return true; 299059d1ed5bSDimitry Andric 2991db17bf38SDimitry Andric // A variable cannot be both common and exist in a section. 2992db17bf38SDimitry Andric // We dont try to determine which is the right section in the front-end. 2993db17bf38SDimitry Andric // If no specialized section name is applicable, it will resort to default. 2994db17bf38SDimitry Andric if (D->hasAttr<PragmaClangBSSSectionAttr>() || 2995db17bf38SDimitry Andric D->hasAttr<PragmaClangDataSectionAttr>() || 2996db17bf38SDimitry Andric D->hasAttr<PragmaClangRodataSectionAttr>()) 2997db17bf38SDimitry Andric return true; 2998db17bf38SDimitry Andric 299959d1ed5bSDimitry Andric // Thread local vars aren't considered common linkage. 300059d1ed5bSDimitry Andric if (D->getTLSKind()) 300159d1ed5bSDimitry Andric return true; 300259d1ed5bSDimitry Andric 300359d1ed5bSDimitry Andric // Tentative definitions marked with WeakImportAttr are true definitions. 300459d1ed5bSDimitry Andric if (D->hasAttr<WeakImportAttr>()) 300559d1ed5bSDimitry Andric return true; 300659d1ed5bSDimitry Andric 300733956c43SDimitry Andric // A variable cannot be both common and exist in a comdat. 300833956c43SDimitry Andric if (shouldBeInCOMDAT(CGM, *D)) 300933956c43SDimitry Andric return true; 301033956c43SDimitry Andric 3011e7145dcbSDimitry Andric // Declarations with a required alignment do not have common linkage in MSVC 301239d628a0SDimitry Andric // mode. 30130623d748SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 301433956c43SDimitry Andric if (D->hasAttr<AlignedAttr>()) 301539d628a0SDimitry Andric return true; 301633956c43SDimitry Andric QualType VarType = D->getType(); 301733956c43SDimitry Andric if (Context.isAlignmentRequired(VarType)) 301833956c43SDimitry Andric return true; 301933956c43SDimitry Andric 302033956c43SDimitry Andric if (const auto *RT = VarType->getAs<RecordType>()) { 302133956c43SDimitry Andric const RecordDecl *RD = RT->getDecl(); 302233956c43SDimitry Andric for (const FieldDecl *FD : RD->fields()) { 302333956c43SDimitry Andric if (FD->isBitField()) 302433956c43SDimitry Andric continue; 302533956c43SDimitry Andric if (FD->hasAttr<AlignedAttr>()) 302633956c43SDimitry Andric return true; 302733956c43SDimitry Andric if (Context.isAlignmentRequired(FD->getType())) 302833956c43SDimitry Andric return true; 302933956c43SDimitry Andric } 303033956c43SDimitry Andric } 303133956c43SDimitry Andric } 303239d628a0SDimitry Andric 303359d1ed5bSDimitry Andric return false; 303459d1ed5bSDimitry Andric } 303559d1ed5bSDimitry Andric 303659d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 303759d1ed5bSDimitry Andric const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 30382754fe60SDimitry Andric if (Linkage == GVA_Internal) 30392754fe60SDimitry Andric return llvm::Function::InternalLinkage; 304059d1ed5bSDimitry Andric 304159d1ed5bSDimitry Andric if (D->hasAttr<WeakAttr>()) { 304259d1ed5bSDimitry Andric if (IsConstantVariable) 304359d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 304459d1ed5bSDimitry Andric else 304559d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakAnyLinkage; 304659d1ed5bSDimitry Andric } 304759d1ed5bSDimitry Andric 304859d1ed5bSDimitry Andric // We are guaranteed to have a strong definition somewhere else, 304959d1ed5bSDimitry Andric // so we can use available_externally linkage. 305059d1ed5bSDimitry Andric if (Linkage == GVA_AvailableExternally) 305120e90f04SDimitry Andric return llvm::GlobalValue::AvailableExternallyLinkage; 305259d1ed5bSDimitry Andric 305359d1ed5bSDimitry Andric // Note that Apple's kernel linker doesn't support symbol 305459d1ed5bSDimitry Andric // coalescing, so we need to avoid linkonce and weak linkages there. 305559d1ed5bSDimitry Andric // Normally, this means we just map to internal, but for explicit 305659d1ed5bSDimitry Andric // instantiations we'll map to external. 305759d1ed5bSDimitry Andric 305859d1ed5bSDimitry Andric // In C++, the compiler has to emit a definition in every translation unit 305959d1ed5bSDimitry Andric // that references the function. We should use linkonce_odr because 306059d1ed5bSDimitry Andric // a) if all references in this translation unit are optimized away, we 306159d1ed5bSDimitry Andric // don't need to codegen it. b) if the function persists, it needs to be 306259d1ed5bSDimitry Andric // merged with other definitions. c) C++ has the ODR, so we know the 306359d1ed5bSDimitry Andric // definition is dependable. 306459d1ed5bSDimitry Andric if (Linkage == GVA_DiscardableODR) 306559d1ed5bSDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 306659d1ed5bSDimitry Andric : llvm::Function::InternalLinkage; 306759d1ed5bSDimitry Andric 306859d1ed5bSDimitry Andric // An explicit instantiation of a template has weak linkage, since 306959d1ed5bSDimitry Andric // explicit instantiations can occur in multiple translation units 307059d1ed5bSDimitry Andric // and must all be equivalent. However, we are not allowed to 307159d1ed5bSDimitry Andric // throw away these explicit instantiations. 3072e7145dcbSDimitry Andric // 3073e7145dcbSDimitry Andric // We don't currently support CUDA device code spread out across multiple TUs, 3074e7145dcbSDimitry Andric // so say that CUDA templates are either external (for kernels) or internal. 3075e7145dcbSDimitry Andric // This lets llvm perform aggressive inter-procedural optimizations. 3076e7145dcbSDimitry Andric if (Linkage == GVA_StrongODR) { 3077e7145dcbSDimitry Andric if (Context.getLangOpts().AppleKext) 3078e7145dcbSDimitry Andric return llvm::Function::ExternalLinkage; 3079e7145dcbSDimitry Andric if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) 3080e7145dcbSDimitry Andric return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 3081e7145dcbSDimitry Andric : llvm::Function::InternalLinkage; 3082e7145dcbSDimitry Andric return llvm::Function::WeakODRLinkage; 3083e7145dcbSDimitry Andric } 308459d1ed5bSDimitry Andric 308559d1ed5bSDimitry Andric // C++ doesn't have tentative definitions and thus cannot have common 308659d1ed5bSDimitry Andric // linkage. 308759d1ed5bSDimitry Andric if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 308833956c43SDimitry Andric !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 308939d628a0SDimitry Andric CodeGenOpts.NoCommon)) 309059d1ed5bSDimitry Andric return llvm::GlobalVariable::CommonLinkage; 309159d1ed5bSDimitry Andric 3092f785676fSDimitry Andric // selectany symbols are externally visible, so use weak instead of 3093f785676fSDimitry Andric // linkonce. MSVC optimizes away references to const selectany globals, so 3094f785676fSDimitry Andric // all definitions should be the same and ODR linkage should be used. 3095f785676fSDimitry Andric // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 309659d1ed5bSDimitry Andric if (D->hasAttr<SelectAnyAttr>()) 3097f785676fSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 309859d1ed5bSDimitry Andric 309959d1ed5bSDimitry Andric // Otherwise, we have strong external linkage. 310059d1ed5bSDimitry Andric assert(Linkage == GVA_StrongExternal); 31012754fe60SDimitry Andric return llvm::GlobalVariable::ExternalLinkage; 31022754fe60SDimitry Andric } 31032754fe60SDimitry Andric 310459d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 310559d1ed5bSDimitry Andric const VarDecl *VD, bool IsConstant) { 310659d1ed5bSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 310759d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 310859d1ed5bSDimitry Andric } 310959d1ed5bSDimitry Andric 3110139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type. 3111139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites 3112139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 3113139f7f9bSDimitry Andric llvm::Function *newFn) { 3114139f7f9bSDimitry Andric // Fast path. 3115139f7f9bSDimitry Andric if (old->use_empty()) return; 3116139f7f9bSDimitry Andric 3117139f7f9bSDimitry Andric llvm::Type *newRetTy = newFn->getReturnType(); 3118139f7f9bSDimitry Andric SmallVector<llvm::Value*, 4> newArgs; 31190623d748SDimitry Andric SmallVector<llvm::OperandBundleDef, 1> newBundles; 3120139f7f9bSDimitry Andric 3121139f7f9bSDimitry Andric for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 3122139f7f9bSDimitry Andric ui != ue; ) { 3123139f7f9bSDimitry Andric llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 312459d1ed5bSDimitry Andric llvm::User *user = use->getUser(); 3125139f7f9bSDimitry Andric 3126139f7f9bSDimitry Andric // Recognize and replace uses of bitcasts. Most calls to 3127139f7f9bSDimitry Andric // unprototyped functions will use bitcasts. 312859d1ed5bSDimitry Andric if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 3129139f7f9bSDimitry Andric if (bitcast->getOpcode() == llvm::Instruction::BitCast) 3130139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(bitcast, newFn); 3131139f7f9bSDimitry Andric continue; 3132139f7f9bSDimitry Andric } 3133139f7f9bSDimitry Andric 3134139f7f9bSDimitry Andric // Recognize calls to the function. 3135139f7f9bSDimitry Andric llvm::CallSite callSite(user); 3136139f7f9bSDimitry Andric if (!callSite) continue; 313759d1ed5bSDimitry Andric if (!callSite.isCallee(&*use)) continue; 3138139f7f9bSDimitry Andric 3139139f7f9bSDimitry Andric // If the return types don't match exactly, then we can't 3140139f7f9bSDimitry Andric // transform this call unless it's dead. 3141139f7f9bSDimitry Andric if (callSite->getType() != newRetTy && !callSite->use_empty()) 3142139f7f9bSDimitry Andric continue; 3143139f7f9bSDimitry Andric 3144139f7f9bSDimitry Andric // Get the call site's attribute list. 314520e90f04SDimitry Andric SmallVector<llvm::AttributeSet, 8> newArgAttrs; 314620e90f04SDimitry Andric llvm::AttributeList oldAttrs = callSite.getAttributes(); 3147139f7f9bSDimitry Andric 3148139f7f9bSDimitry Andric // If the function was passed too few arguments, don't transform. 3149139f7f9bSDimitry Andric unsigned newNumArgs = newFn->arg_size(); 3150139f7f9bSDimitry Andric if (callSite.arg_size() < newNumArgs) continue; 3151139f7f9bSDimitry Andric 3152139f7f9bSDimitry Andric // If extra arguments were passed, we silently drop them. 3153139f7f9bSDimitry Andric // If any of the types mismatch, we don't transform. 3154139f7f9bSDimitry Andric unsigned argNo = 0; 3155139f7f9bSDimitry Andric bool dontTransform = false; 315620e90f04SDimitry Andric for (llvm::Argument &A : newFn->args()) { 315720e90f04SDimitry Andric if (callSite.getArgument(argNo)->getType() != A.getType()) { 3158139f7f9bSDimitry Andric dontTransform = true; 3159139f7f9bSDimitry Andric break; 3160139f7f9bSDimitry Andric } 3161139f7f9bSDimitry Andric 3162139f7f9bSDimitry Andric // Add any parameter attributes. 316320e90f04SDimitry Andric newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo)); 316420e90f04SDimitry Andric argNo++; 3165139f7f9bSDimitry Andric } 3166139f7f9bSDimitry Andric if (dontTransform) 3167139f7f9bSDimitry Andric continue; 3168139f7f9bSDimitry Andric 3169139f7f9bSDimitry Andric // Okay, we can transform this. Create the new call instruction and copy 3170139f7f9bSDimitry Andric // over the required information. 3171139f7f9bSDimitry Andric newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 3172139f7f9bSDimitry Andric 31730623d748SDimitry Andric // Copy over any operand bundles. 31740623d748SDimitry Andric callSite.getOperandBundlesAsDefs(newBundles); 31750623d748SDimitry Andric 3176139f7f9bSDimitry Andric llvm::CallSite newCall; 3177139f7f9bSDimitry Andric if (callSite.isCall()) { 31780623d748SDimitry Andric newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "", 3179139f7f9bSDimitry Andric callSite.getInstruction()); 3180139f7f9bSDimitry Andric } else { 318159d1ed5bSDimitry Andric auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction()); 3182139f7f9bSDimitry Andric newCall = llvm::InvokeInst::Create(newFn, 3183139f7f9bSDimitry Andric oldInvoke->getNormalDest(), 3184139f7f9bSDimitry Andric oldInvoke->getUnwindDest(), 31850623d748SDimitry Andric newArgs, newBundles, "", 3186139f7f9bSDimitry Andric callSite.getInstruction()); 3187139f7f9bSDimitry Andric } 3188139f7f9bSDimitry Andric newArgs.clear(); // for the next iteration 3189139f7f9bSDimitry Andric 3190139f7f9bSDimitry Andric if (!newCall->getType()->isVoidTy()) 3191139f7f9bSDimitry Andric newCall->takeName(callSite.getInstruction()); 319220e90f04SDimitry Andric newCall.setAttributes(llvm::AttributeList::get( 319320e90f04SDimitry Andric newFn->getContext(), oldAttrs.getFnAttributes(), 319420e90f04SDimitry Andric oldAttrs.getRetAttributes(), newArgAttrs)); 3195139f7f9bSDimitry Andric newCall.setCallingConv(callSite.getCallingConv()); 3196139f7f9bSDimitry Andric 3197139f7f9bSDimitry Andric // Finally, remove the old call, replacing any uses with the new one. 3198139f7f9bSDimitry Andric if (!callSite->use_empty()) 3199139f7f9bSDimitry Andric callSite->replaceAllUsesWith(newCall.getInstruction()); 3200139f7f9bSDimitry Andric 3201139f7f9bSDimitry Andric // Copy debug location attached to CI. 320233956c43SDimitry Andric if (callSite->getDebugLoc()) 3203139f7f9bSDimitry Andric newCall->setDebugLoc(callSite->getDebugLoc()); 32040623d748SDimitry Andric 3205139f7f9bSDimitry Andric callSite->eraseFromParent(); 3206139f7f9bSDimitry Andric } 3207139f7f9bSDimitry Andric } 3208139f7f9bSDimitry Andric 3209f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 3210f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}". If there are 3211f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to 3212f22ef01cSRoman Divacky /// call the new function directly. 3213f22ef01cSRoman Divacky /// 3214f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to 3215f22ef01cSRoman Divacky /// functions to be able to inline them. If there is a bitcast in the way, it 3216f22ef01cSRoman Divacky /// won't inline them. Instcombine normally deletes these calls, but it isn't 3217f22ef01cSRoman Divacky /// run at -O0. 3218f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 3219f22ef01cSRoman Divacky llvm::Function *NewFn) { 3220f22ef01cSRoman Divacky // If we're redefining a global as a function, don't transform it. 3221139f7f9bSDimitry Andric if (!isa<llvm::Function>(Old)) return; 3222f22ef01cSRoman Divacky 3223139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(Old, NewFn); 3224f22ef01cSRoman Divacky } 3225f22ef01cSRoman Divacky 3226dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 3227e7145dcbSDimitry Andric auto DK = VD->isThisDeclarationADefinition(); 3228e7145dcbSDimitry Andric if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 3229e7145dcbSDimitry Andric return; 3230e7145dcbSDimitry Andric 3231dff0c46cSDimitry Andric TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 3232dff0c46cSDimitry Andric // If we have a definition, this might be a deferred decl. If the 3233dff0c46cSDimitry Andric // instantiation is explicit, make sure we emit it at the end. 3234dff0c46cSDimitry Andric if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 3235dff0c46cSDimitry Andric GetAddrOfGlobalVar(VD); 3236139f7f9bSDimitry Andric 3237139f7f9bSDimitry Andric EmitTopLevelDecl(VD); 3238dff0c46cSDimitry Andric } 3239f22ef01cSRoman Divacky 324059d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 324159d1ed5bSDimitry Andric llvm::GlobalValue *GV) { 324259d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 32433b0f4066SDimitry Andric 32443b0f4066SDimitry Andric // Compute the function info and LLVM type. 3245dff0c46cSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3246dff0c46cSDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 32473b0f4066SDimitry Andric 3248f22ef01cSRoman Divacky // Get or create the prototype for the function. 32490623d748SDimitry Andric if (!GV || (GV->getType()->getElementType() != Ty)) 32500623d748SDimitry Andric GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 32510623d748SDimitry Andric /*DontDefer=*/true, 325244290647SDimitry Andric ForDefinition)); 3253f22ef01cSRoman Divacky 32540623d748SDimitry Andric // Already emitted. 32550623d748SDimitry Andric if (!GV->isDeclaration()) 3256f785676fSDimitry Andric return; 3257f22ef01cSRoman Divacky 32582754fe60SDimitry Andric // We need to set linkage and visibility on the function before 32592754fe60SDimitry Andric // generating code for it because various parts of IR generation 32602754fe60SDimitry Andric // want to propagate this information down (e.g. to local static 32612754fe60SDimitry Andric // declarations). 326259d1ed5bSDimitry Andric auto *Fn = cast<llvm::Function>(GV); 3263f785676fSDimitry Andric setFunctionLinkage(GD, Fn); 326497bc6c73SDimitry Andric setFunctionDLLStorageClass(GD, Fn); 3265f22ef01cSRoman Divacky 326659d1ed5bSDimitry Andric // FIXME: this is redundant with part of setFunctionDefinitionAttributes 32679a199699SDimitry Andric setGlobalVisibility(Fn, D, ForDefinition); 32682754fe60SDimitry Andric 3269284c1978SDimitry Andric MaybeHandleStaticInExternC(D, Fn); 3270284c1978SDimitry Andric 327133956c43SDimitry Andric maybeSetTrivialComdat(*D, *Fn); 327233956c43SDimitry Andric 32733b0f4066SDimitry Andric CodeGenFunction(*this).GenerateCode(D, Fn, FI); 3274f22ef01cSRoman Divacky 327559d1ed5bSDimitry Andric setFunctionDefinitionAttributes(D, Fn); 3276f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, Fn); 3277f22ef01cSRoman Divacky 3278f22ef01cSRoman Divacky if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 3279f22ef01cSRoman Divacky AddGlobalCtor(Fn, CA->getPriority()); 3280f22ef01cSRoman Divacky if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 3281f22ef01cSRoman Divacky AddGlobalDtor(Fn, DA->getPriority()); 32826122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 32836122f3e6SDimitry Andric AddGlobalAnnotations(D, Fn); 3284f22ef01cSRoman Divacky } 3285f22ef01cSRoman Divacky 3286f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 328759d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 3288f22ef01cSRoman Divacky const AliasAttr *AA = D->getAttr<AliasAttr>(); 3289f22ef01cSRoman Divacky assert(AA && "Not an alias?"); 3290f22ef01cSRoman Divacky 32916122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 3292f22ef01cSRoman Divacky 32939a4b3118SDimitry Andric if (AA->getAliasee() == MangledName) { 3294e7145dcbSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 32959a4b3118SDimitry Andric return; 32969a4b3118SDimitry Andric } 32979a4b3118SDimitry Andric 3298f22ef01cSRoman Divacky // If there is a definition in the module, then it wins over the alias. 3299f22ef01cSRoman Divacky // This is dubious, but allow it to be safe. Just ignore the alias. 3300f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3301f22ef01cSRoman Divacky if (Entry && !Entry->isDeclaration()) 3302f22ef01cSRoman Divacky return; 3303f22ef01cSRoman Divacky 3304f785676fSDimitry Andric Aliases.push_back(GD); 3305f785676fSDimitry Andric 33066122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 3307f22ef01cSRoman Divacky 3308f22ef01cSRoman Divacky // Create a reference to the named value. This ensures that it is emitted 3309f22ef01cSRoman Divacky // if a deferred decl. 3310f22ef01cSRoman Divacky llvm::Constant *Aliasee; 3311f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 33123861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 33132754fe60SDimitry Andric /*ForVTable=*/false); 3314f22ef01cSRoman Divacky else 3315f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 331659d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 331739d628a0SDimitry Andric /*D=*/nullptr); 3318f22ef01cSRoman Divacky 3319f22ef01cSRoman Divacky // Create the new alias itself, but don't set a name yet. 332059d1ed5bSDimitry Andric auto *GA = llvm::GlobalAlias::create( 33210623d748SDimitry Andric DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule()); 3322f22ef01cSRoman Divacky 3323f22ef01cSRoman Divacky if (Entry) { 332459d1ed5bSDimitry Andric if (GA->getAliasee() == Entry) { 3325e7145dcbSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 332659d1ed5bSDimitry Andric return; 332759d1ed5bSDimitry Andric } 332859d1ed5bSDimitry Andric 3329f22ef01cSRoman Divacky assert(Entry->isDeclaration()); 3330f22ef01cSRoman Divacky 3331f22ef01cSRoman Divacky // If there is a declaration in the module, then we had an extern followed 3332f22ef01cSRoman Divacky // by the alias, as in: 3333f22ef01cSRoman Divacky // extern int test6(); 3334f22ef01cSRoman Divacky // ... 3335f22ef01cSRoman Divacky // int test6() __attribute__((alias("test7"))); 3336f22ef01cSRoman Divacky // 3337f22ef01cSRoman Divacky // Remove it and replace uses of it with the alias. 3338f22ef01cSRoman Divacky GA->takeName(Entry); 3339f22ef01cSRoman Divacky 3340f22ef01cSRoman Divacky Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 3341f22ef01cSRoman Divacky Entry->getType())); 3342f22ef01cSRoman Divacky Entry->eraseFromParent(); 3343f22ef01cSRoman Divacky } else { 3344ffd1746dSEd Schouten GA->setName(MangledName); 3345f22ef01cSRoman Divacky } 3346f22ef01cSRoman Divacky 3347f22ef01cSRoman Divacky // Set attributes which are particular to an alias; this is a 3348f22ef01cSRoman Divacky // specialization of the attributes which may be set on a global 3349f22ef01cSRoman Divacky // variable/function. 335039d628a0SDimitry Andric if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 33513b0f4066SDimitry Andric D->isWeakImported()) { 3352f22ef01cSRoman Divacky GA->setLinkage(llvm::Function::WeakAnyLinkage); 3353f22ef01cSRoman Divacky } 3354f22ef01cSRoman Divacky 335539d628a0SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 335639d628a0SDimitry Andric if (VD->getTLSKind()) 335739d628a0SDimitry Andric setTLSMode(GA, *VD); 335839d628a0SDimitry Andric 335939d628a0SDimitry Andric setAliasAttributes(D, GA); 3360f22ef01cSRoman Divacky } 3361f22ef01cSRoman Divacky 3362e7145dcbSDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 3363e7145dcbSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 3364e7145dcbSDimitry Andric const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 3365e7145dcbSDimitry Andric assert(IFA && "Not an ifunc?"); 3366e7145dcbSDimitry Andric 3367e7145dcbSDimitry Andric StringRef MangledName = getMangledName(GD); 3368e7145dcbSDimitry Andric 3369e7145dcbSDimitry Andric if (IFA->getResolver() == MangledName) { 3370e7145dcbSDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 3371e7145dcbSDimitry Andric return; 3372e7145dcbSDimitry Andric } 3373e7145dcbSDimitry Andric 3374e7145dcbSDimitry Andric // Report an error if some definition overrides ifunc. 3375e7145dcbSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3376e7145dcbSDimitry Andric if (Entry && !Entry->isDeclaration()) { 3377e7145dcbSDimitry Andric GlobalDecl OtherGD; 3378e7145dcbSDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 3379e7145dcbSDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 3380e7145dcbSDimitry Andric Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name); 3381e7145dcbSDimitry Andric Diags.Report(OtherGD.getDecl()->getLocation(), 3382e7145dcbSDimitry Andric diag::note_previous_definition); 3383e7145dcbSDimitry Andric } 3384e7145dcbSDimitry Andric return; 3385e7145dcbSDimitry Andric } 3386e7145dcbSDimitry Andric 3387e7145dcbSDimitry Andric Aliases.push_back(GD); 3388e7145dcbSDimitry Andric 3389e7145dcbSDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 3390e7145dcbSDimitry Andric llvm::Constant *Resolver = 3391e7145dcbSDimitry Andric GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD, 3392e7145dcbSDimitry Andric /*ForVTable=*/false); 3393e7145dcbSDimitry Andric llvm::GlobalIFunc *GIF = 3394e7145dcbSDimitry Andric llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 3395e7145dcbSDimitry Andric "", Resolver, &getModule()); 3396e7145dcbSDimitry Andric if (Entry) { 3397e7145dcbSDimitry Andric if (GIF->getResolver() == Entry) { 3398e7145dcbSDimitry Andric Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 3399e7145dcbSDimitry Andric return; 3400e7145dcbSDimitry Andric } 3401e7145dcbSDimitry Andric assert(Entry->isDeclaration()); 3402e7145dcbSDimitry Andric 3403e7145dcbSDimitry Andric // If there is a declaration in the module, then we had an extern followed 3404e7145dcbSDimitry Andric // by the ifunc, as in: 3405e7145dcbSDimitry Andric // extern int test(); 3406e7145dcbSDimitry Andric // ... 3407e7145dcbSDimitry Andric // int test() __attribute__((ifunc("resolver"))); 3408e7145dcbSDimitry Andric // 3409e7145dcbSDimitry Andric // Remove it and replace uses of it with the ifunc. 3410e7145dcbSDimitry Andric GIF->takeName(Entry); 3411e7145dcbSDimitry Andric 3412e7145dcbSDimitry Andric Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 3413e7145dcbSDimitry Andric Entry->getType())); 3414e7145dcbSDimitry Andric Entry->eraseFromParent(); 3415e7145dcbSDimitry Andric } else 3416e7145dcbSDimitry Andric GIF->setName(MangledName); 3417e7145dcbSDimitry Andric 3418e7145dcbSDimitry Andric SetCommonAttributes(D, GIF); 3419e7145dcbSDimitry Andric } 3420e7145dcbSDimitry Andric 342117a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 34226122f3e6SDimitry Andric ArrayRef<llvm::Type*> Tys) { 342317a519f9SDimitry Andric return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 342417a519f9SDimitry Andric Tys); 3425f22ef01cSRoman Divacky } 3426f22ef01cSRoman Divacky 342733956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 342833956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 342933956c43SDimitry Andric const StringLiteral *Literal, bool TargetIsLSB, 343033956c43SDimitry Andric bool &IsUTF16, unsigned &StringLength) { 34316122f3e6SDimitry Andric StringRef String = Literal->getString(); 3432e580952dSDimitry Andric unsigned NumBytes = String.size(); 3433f22ef01cSRoman Divacky 3434f22ef01cSRoman Divacky // Check for simple case. 3435f22ef01cSRoman Divacky if (!Literal->containsNonAsciiOrNull()) { 3436f22ef01cSRoman Divacky StringLength = NumBytes; 343739d628a0SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 3438f22ef01cSRoman Divacky } 3439f22ef01cSRoman Divacky 3440dff0c46cSDimitry Andric // Otherwise, convert the UTF8 literals into a string of shorts. 3441dff0c46cSDimitry Andric IsUTF16 = true; 3442dff0c46cSDimitry Andric 344344290647SDimitry Andric SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 344444290647SDimitry Andric const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 344544290647SDimitry Andric llvm::UTF16 *ToPtr = &ToBuf[0]; 3446f22ef01cSRoman Divacky 344744290647SDimitry Andric (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 344844290647SDimitry Andric ToPtr + NumBytes, llvm::strictConversion); 3449f22ef01cSRoman Divacky 3450f22ef01cSRoman Divacky // ConvertUTF8toUTF16 returns the length in ToPtr. 3451f22ef01cSRoman Divacky StringLength = ToPtr - &ToBuf[0]; 3452f22ef01cSRoman Divacky 3453dff0c46cSDimitry Andric // Add an explicit null. 3454dff0c46cSDimitry Andric *ToPtr = 0; 345539d628a0SDimitry Andric return *Map.insert(std::make_pair( 345639d628a0SDimitry Andric StringRef(reinterpret_cast<const char *>(ToBuf.data()), 345739d628a0SDimitry Andric (StringLength + 1) * 2), 345839d628a0SDimitry Andric nullptr)).first; 3459f22ef01cSRoman Divacky } 3460f22ef01cSRoman Divacky 34610623d748SDimitry Andric ConstantAddress 3462f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 3463f22ef01cSRoman Divacky unsigned StringLength = 0; 3464f22ef01cSRoman Divacky bool isUTF16 = false; 346533956c43SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 3466f22ef01cSRoman Divacky GetConstantCFStringEntry(CFConstantStringMap, Literal, 346733956c43SDimitry Andric getDataLayout().isLittleEndian(), isUTF16, 346833956c43SDimitry Andric StringLength); 3469f22ef01cSRoman Divacky 347039d628a0SDimitry Andric if (auto *C = Entry.second) 34710623d748SDimitry Andric return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 3472f22ef01cSRoman Divacky 3473dff0c46cSDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 3474f22ef01cSRoman Divacky llvm::Constant *Zeros[] = { Zero, Zero }; 3475f22ef01cSRoman Divacky 3476f22ef01cSRoman Divacky // If we don't already have it, get __CFConstantStringClassReference. 3477f22ef01cSRoman Divacky if (!CFConstantStringClassRef) { 34786122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 3479f22ef01cSRoman Divacky Ty = llvm::ArrayType::get(Ty, 0); 3480e7145dcbSDimitry Andric llvm::Constant *GV = 3481e7145dcbSDimitry Andric CreateRuntimeVariable(Ty, "__CFConstantStringClassReference"); 3482e7145dcbSDimitry Andric 348344290647SDimitry Andric if (getTriple().isOSBinFormatCOFF()) { 3484e7145dcbSDimitry Andric IdentifierInfo &II = getContext().Idents.get(GV->getName()); 3485e7145dcbSDimitry Andric TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl(); 3486e7145dcbSDimitry Andric DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 3487e7145dcbSDimitry Andric llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV); 3488e7145dcbSDimitry Andric 3489e7145dcbSDimitry Andric const VarDecl *VD = nullptr; 3490e7145dcbSDimitry Andric for (const auto &Result : DC->lookup(&II)) 3491e7145dcbSDimitry Andric if ((VD = dyn_cast<VarDecl>(Result))) 3492e7145dcbSDimitry Andric break; 3493e7145dcbSDimitry Andric 3494e7145dcbSDimitry Andric if (!VD || !VD->hasAttr<DLLExportAttr>()) { 3495e7145dcbSDimitry Andric CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3496e7145dcbSDimitry Andric CGV->setLinkage(llvm::GlobalValue::ExternalLinkage); 3497e7145dcbSDimitry Andric } else { 3498e7145dcbSDimitry Andric CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 3499e7145dcbSDimitry Andric CGV->setLinkage(llvm::GlobalValue::ExternalLinkage); 3500e7145dcbSDimitry Andric } 3501e7145dcbSDimitry Andric } 3502e7145dcbSDimitry Andric 3503f22ef01cSRoman Divacky // Decay array -> ptr 350444290647SDimitry Andric CFConstantStringClassRef = 350544290647SDimitry Andric llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros); 3506e7145dcbSDimitry Andric } 3507f22ef01cSRoman Divacky 3508f22ef01cSRoman Divacky QualType CFTy = getContext().getCFConstantStringType(); 3509f22ef01cSRoman Divacky 351059d1ed5bSDimitry Andric auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 3511f22ef01cSRoman Divacky 351244290647SDimitry Andric ConstantInitBuilder Builder(*this); 351344290647SDimitry Andric auto Fields = Builder.beginStruct(STy); 3514f22ef01cSRoman Divacky 3515f22ef01cSRoman Divacky // Class pointer. 351644290647SDimitry Andric Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef)); 3517f22ef01cSRoman Divacky 3518f22ef01cSRoman Divacky // Flags. 351944290647SDimitry Andric Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 3520f22ef01cSRoman Divacky 3521f22ef01cSRoman Divacky // String pointer. 352259d1ed5bSDimitry Andric llvm::Constant *C = nullptr; 3523dff0c46cSDimitry Andric if (isUTF16) { 35240623d748SDimitry Andric auto Arr = llvm::makeArrayRef( 352539d628a0SDimitry Andric reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 352639d628a0SDimitry Andric Entry.first().size() / 2); 3527dff0c46cSDimitry Andric C = llvm::ConstantDataArray::get(VMContext, Arr); 3528dff0c46cSDimitry Andric } else { 352939d628a0SDimitry Andric C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 3530dff0c46cSDimitry Andric } 3531f22ef01cSRoman Divacky 3532dff0c46cSDimitry Andric // Note: -fwritable-strings doesn't make the backing store strings of 3533dff0c46cSDimitry Andric // CFStrings writable. (See <rdar://problem/10657500>) 353459d1ed5bSDimitry Andric auto *GV = 3535dff0c46cSDimitry Andric new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 353659d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, C, ".str"); 3537e7145dcbSDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3538284c1978SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 3539284c1978SDimitry Andric // of the string is via this class initializer. 3540e7145dcbSDimitry Andric CharUnits Align = isUTF16 3541e7145dcbSDimitry Andric ? getContext().getTypeAlignInChars(getContext().ShortTy) 3542e7145dcbSDimitry Andric : getContext().getTypeAlignInChars(getContext().CharTy); 3543f22ef01cSRoman Divacky GV->setAlignment(Align.getQuantity()); 3544e7145dcbSDimitry Andric 3545e7145dcbSDimitry Andric // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 3546e7145dcbSDimitry Andric // Without it LLVM can merge the string with a non unnamed_addr one during 3547e7145dcbSDimitry Andric // LTO. Doing that changes the section it ends in, which surprises ld64. 354844290647SDimitry Andric if (getTriple().isOSBinFormatMachO()) 3549e7145dcbSDimitry Andric GV->setSection(isUTF16 ? "__TEXT,__ustring" 3550e7145dcbSDimitry Andric : "__TEXT,__cstring,cstring_literals"); 3551dff0c46cSDimitry Andric 3552dff0c46cSDimitry Andric // String. 355344290647SDimitry Andric llvm::Constant *Str = 355433956c43SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 3555f22ef01cSRoman Divacky 3556dff0c46cSDimitry Andric if (isUTF16) 3557dff0c46cSDimitry Andric // Cast the UTF16 string to the correct type. 355844290647SDimitry Andric Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 355944290647SDimitry Andric Fields.add(Str); 3560dff0c46cSDimitry Andric 3561f22ef01cSRoman Divacky // String length. 356244290647SDimitry Andric auto Ty = getTypes().ConvertType(getContext().LongTy); 356344290647SDimitry Andric Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength); 3564f22ef01cSRoman Divacky 35650623d748SDimitry Andric CharUnits Alignment = getPointerAlign(); 35660623d748SDimitry Andric 3567f22ef01cSRoman Divacky // The struct. 356844290647SDimitry Andric GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 356944290647SDimitry Andric /*isConstant=*/false, 357044290647SDimitry Andric llvm::GlobalVariable::PrivateLinkage); 357144290647SDimitry Andric switch (getTriple().getObjectFormat()) { 3572e7145dcbSDimitry Andric case llvm::Triple::UnknownObjectFormat: 3573e7145dcbSDimitry Andric llvm_unreachable("unknown file format"); 3574e7145dcbSDimitry Andric case llvm::Triple::COFF: 3575e7145dcbSDimitry Andric case llvm::Triple::ELF: 357620e90f04SDimitry Andric case llvm::Triple::Wasm: 3577e7145dcbSDimitry Andric GV->setSection("cfstring"); 3578e7145dcbSDimitry Andric break; 3579e7145dcbSDimitry Andric case llvm::Triple::MachO: 3580e7145dcbSDimitry Andric GV->setSection("__DATA,__cfstring"); 3581e7145dcbSDimitry Andric break; 3582e7145dcbSDimitry Andric } 358339d628a0SDimitry Andric Entry.second = GV; 3584f22ef01cSRoman Divacky 35850623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3586f22ef01cSRoman Divacky } 3587f22ef01cSRoman Divacky 35889a199699SDimitry Andric bool CodeGenModule::getExpressionLocationsEnabled() const { 35899a199699SDimitry Andric return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 35909a199699SDimitry Andric } 35919a199699SDimitry Andric 35926122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() { 35936122f3e6SDimitry Andric if (ObjCFastEnumerationStateType.isNull()) { 359459d1ed5bSDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 35956122f3e6SDimitry Andric D->startDefinition(); 35966122f3e6SDimitry Andric 35976122f3e6SDimitry Andric QualType FieldTypes[] = { 35986122f3e6SDimitry Andric Context.UnsignedLongTy, 35996122f3e6SDimitry Andric Context.getPointerType(Context.getObjCIdType()), 36006122f3e6SDimitry Andric Context.getPointerType(Context.UnsignedLongTy), 36016122f3e6SDimitry Andric Context.getConstantArrayType(Context.UnsignedLongTy, 36026122f3e6SDimitry Andric llvm::APInt(32, 5), ArrayType::Normal, 0) 36036122f3e6SDimitry Andric }; 36046122f3e6SDimitry Andric 36056122f3e6SDimitry Andric for (size_t i = 0; i < 4; ++i) { 36066122f3e6SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, 36076122f3e6SDimitry Andric D, 36086122f3e6SDimitry Andric SourceLocation(), 360959d1ed5bSDimitry Andric SourceLocation(), nullptr, 361059d1ed5bSDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 361159d1ed5bSDimitry Andric /*BitWidth=*/nullptr, 36126122f3e6SDimitry Andric /*Mutable=*/false, 36137ae0e2c9SDimitry Andric ICIS_NoInit); 36146122f3e6SDimitry Andric Field->setAccess(AS_public); 36156122f3e6SDimitry Andric D->addDecl(Field); 36166122f3e6SDimitry Andric } 36176122f3e6SDimitry Andric 36186122f3e6SDimitry Andric D->completeDefinition(); 36196122f3e6SDimitry Andric ObjCFastEnumerationStateType = Context.getTagDeclType(D); 36206122f3e6SDimitry Andric } 36216122f3e6SDimitry Andric 36226122f3e6SDimitry Andric return ObjCFastEnumerationStateType; 36236122f3e6SDimitry Andric } 36246122f3e6SDimitry Andric 3625dff0c46cSDimitry Andric llvm::Constant * 3626dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 3627dff0c46cSDimitry Andric assert(!E->getType()->isPointerType() && "Strings are always arrays"); 3628f22ef01cSRoman Divacky 3629dff0c46cSDimitry Andric // Don't emit it as the address of the string, emit the string data itself 3630dff0c46cSDimitry Andric // as an inline array. 3631dff0c46cSDimitry Andric if (E->getCharByteWidth() == 1) { 3632dff0c46cSDimitry Andric SmallString<64> Str(E->getString()); 3633f22ef01cSRoman Divacky 3634dff0c46cSDimitry Andric // Resize the string to the right size, which is indicated by its type. 3635dff0c46cSDimitry Andric const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 3636dff0c46cSDimitry Andric Str.resize(CAT->getSize().getZExtValue()); 3637dff0c46cSDimitry Andric return llvm::ConstantDataArray::getString(VMContext, Str, false); 36386122f3e6SDimitry Andric } 3639f22ef01cSRoman Divacky 364059d1ed5bSDimitry Andric auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 3641dff0c46cSDimitry Andric llvm::Type *ElemTy = AType->getElementType(); 3642dff0c46cSDimitry Andric unsigned NumElements = AType->getNumElements(); 3643f22ef01cSRoman Divacky 3644dff0c46cSDimitry Andric // Wide strings have either 2-byte or 4-byte elements. 3645dff0c46cSDimitry Andric if (ElemTy->getPrimitiveSizeInBits() == 16) { 3646dff0c46cSDimitry Andric SmallVector<uint16_t, 32> Elements; 3647dff0c46cSDimitry Andric Elements.reserve(NumElements); 3648dff0c46cSDimitry Andric 3649dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3650dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 3651dff0c46cSDimitry Andric Elements.resize(NumElements); 3652dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 3653dff0c46cSDimitry Andric } 3654dff0c46cSDimitry Andric 3655dff0c46cSDimitry Andric assert(ElemTy->getPrimitiveSizeInBits() == 32); 3656dff0c46cSDimitry Andric SmallVector<uint32_t, 32> Elements; 3657dff0c46cSDimitry Andric Elements.reserve(NumElements); 3658dff0c46cSDimitry Andric 3659dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3660dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 3661dff0c46cSDimitry Andric Elements.resize(NumElements); 3662dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 3663f22ef01cSRoman Divacky } 3664f22ef01cSRoman Divacky 366559d1ed5bSDimitry Andric static llvm::GlobalVariable * 366659d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 366759d1ed5bSDimitry Andric CodeGenModule &CGM, StringRef GlobalName, 36680623d748SDimitry Andric CharUnits Alignment) { 366959d1ed5bSDimitry Andric // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 367059d1ed5bSDimitry Andric unsigned AddrSpace = 0; 367159d1ed5bSDimitry Andric if (CGM.getLangOpts().OpenCL) 367259d1ed5bSDimitry Andric AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 3673dff0c46cSDimitry Andric 367433956c43SDimitry Andric llvm::Module &M = CGM.getModule(); 367559d1ed5bSDimitry Andric // Create a global variable for this string 367659d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 367733956c43SDimitry Andric M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 367833956c43SDimitry Andric nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 36790623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 3680e7145dcbSDimitry Andric GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 368133956c43SDimitry Andric if (GV->isWeakForLinker()) { 368233956c43SDimitry Andric assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 368333956c43SDimitry Andric GV->setComdat(M.getOrInsertComdat(GV->getName())); 368433956c43SDimitry Andric } 368533956c43SDimitry Andric 368659d1ed5bSDimitry Andric return GV; 3687f22ef01cSRoman Divacky } 3688dff0c46cSDimitry Andric 368959d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 369059d1ed5bSDimitry Andric /// constant array for the given string literal. 36910623d748SDimitry Andric ConstantAddress 369239d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 369339d628a0SDimitry Andric StringRef Name) { 36940623d748SDimitry Andric CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 3695dff0c46cSDimitry Andric 369659d1ed5bSDimitry Andric llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 369759d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 369859d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 369959d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 370059d1ed5bSDimitry Andric if (auto GV = *Entry) { 37010623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 37020623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 37030623d748SDimitry Andric return ConstantAddress(GV, Alignment); 370459d1ed5bSDimitry Andric } 370559d1ed5bSDimitry Andric } 370659d1ed5bSDimitry Andric 370759d1ed5bSDimitry Andric SmallString<256> MangledNameBuffer; 370859d1ed5bSDimitry Andric StringRef GlobalVariableName; 370959d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes LT; 371059d1ed5bSDimitry Andric 371159d1ed5bSDimitry Andric // Mangle the string literal if the ABI allows for it. However, we cannot 371259d1ed5bSDimitry Andric // do this if we are compiling with ASan or -fwritable-strings because they 371359d1ed5bSDimitry Andric // rely on strings having normal linkage. 371439d628a0SDimitry Andric if (!LangOpts.WritableStrings && 371539d628a0SDimitry Andric !LangOpts.Sanitize.has(SanitizerKind::Address) && 371659d1ed5bSDimitry Andric getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { 371759d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(MangledNameBuffer); 371859d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 371959d1ed5bSDimitry Andric 372059d1ed5bSDimitry Andric LT = llvm::GlobalValue::LinkOnceODRLinkage; 372159d1ed5bSDimitry Andric GlobalVariableName = MangledNameBuffer; 372259d1ed5bSDimitry Andric } else { 372359d1ed5bSDimitry Andric LT = llvm::GlobalValue::PrivateLinkage; 372439d628a0SDimitry Andric GlobalVariableName = Name; 372559d1ed5bSDimitry Andric } 372659d1ed5bSDimitry Andric 372759d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 372859d1ed5bSDimitry Andric if (Entry) 372959d1ed5bSDimitry Andric *Entry = GV; 373059d1ed5bSDimitry Andric 373139d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 373239d628a0SDimitry Andric QualType()); 37330623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3734f22ef01cSRoman Divacky } 3735f22ef01cSRoman Divacky 3736f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 3737f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node. 37380623d748SDimitry Andric ConstantAddress 3739f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 3740f22ef01cSRoman Divacky std::string Str; 3741f22ef01cSRoman Divacky getContext().getObjCEncodingForType(E->getEncodedType(), Str); 3742f22ef01cSRoman Divacky 3743f22ef01cSRoman Divacky return GetAddrOfConstantCString(Str); 3744f22ef01cSRoman Divacky } 3745f22ef01cSRoman Divacky 374659d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing 374759d1ed5bSDimitry Andric /// the literal and a terminating '\0' character. 374859d1ed5bSDimitry Andric /// The result has pointer to array type. 37490623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString( 37500623d748SDimitry Andric const std::string &Str, const char *GlobalName) { 375159d1ed5bSDimitry Andric StringRef StrWithNull(Str.c_str(), Str.size() + 1); 37520623d748SDimitry Andric CharUnits Alignment = 37530623d748SDimitry Andric getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 3754f22ef01cSRoman Divacky 375559d1ed5bSDimitry Andric llvm::Constant *C = 375659d1ed5bSDimitry Andric llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 375759d1ed5bSDimitry Andric 375859d1ed5bSDimitry Andric // Don't share any string literals if strings aren't constant. 375959d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 376059d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 376159d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 376259d1ed5bSDimitry Andric if (auto GV = *Entry) { 37630623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 37640623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 37650623d748SDimitry Andric return ConstantAddress(GV, Alignment); 376659d1ed5bSDimitry Andric } 376759d1ed5bSDimitry Andric } 376859d1ed5bSDimitry Andric 3769f22ef01cSRoman Divacky // Get the default prefix if a name wasn't specified. 3770f22ef01cSRoman Divacky if (!GlobalName) 3771f22ef01cSRoman Divacky GlobalName = ".str"; 3772f22ef01cSRoman Divacky // Create a global variable for this. 377359d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 377459d1ed5bSDimitry Andric GlobalName, Alignment); 377559d1ed5bSDimitry Andric if (Entry) 377659d1ed5bSDimitry Andric *Entry = GV; 37770623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3778f22ef01cSRoman Divacky } 3779f22ef01cSRoman Divacky 37800623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 3781f785676fSDimitry Andric const MaterializeTemporaryExpr *E, const Expr *Init) { 3782f785676fSDimitry Andric assert((E->getStorageDuration() == SD_Static || 3783f785676fSDimitry Andric E->getStorageDuration() == SD_Thread) && "not a global temporary"); 378459d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 3785f785676fSDimitry Andric 3786f785676fSDimitry Andric // If we're not materializing a subobject of the temporary, keep the 3787f785676fSDimitry Andric // cv-qualifiers from the type of the MaterializeTemporaryExpr. 3788f785676fSDimitry Andric QualType MaterializedType = Init->getType(); 3789f785676fSDimitry Andric if (Init == E->GetTemporaryExpr()) 3790f785676fSDimitry Andric MaterializedType = E->getType(); 3791f785676fSDimitry Andric 37920623d748SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 37930623d748SDimitry Andric 37940623d748SDimitry Andric if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E]) 37950623d748SDimitry Andric return ConstantAddress(Slot, Align); 3796f785676fSDimitry Andric 3797f785676fSDimitry Andric // FIXME: If an externally-visible declaration extends multiple temporaries, 3798f785676fSDimitry Andric // we need to give each temporary the same name in every translation unit (and 3799f785676fSDimitry Andric // we also need to make the temporaries externally-visible). 3800f785676fSDimitry Andric SmallString<256> Name; 3801f785676fSDimitry Andric llvm::raw_svector_ostream Out(Name); 380259d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleReferenceTemporary( 380359d1ed5bSDimitry Andric VD, E->getManglingNumber(), Out); 3804f785676fSDimitry Andric 380559d1ed5bSDimitry Andric APValue *Value = nullptr; 3806f785676fSDimitry Andric if (E->getStorageDuration() == SD_Static) { 3807f785676fSDimitry Andric // We might have a cached constant initializer for this temporary. Note 3808f785676fSDimitry Andric // that this might have a different value from the value computed by 3809f785676fSDimitry Andric // evaluating the initializer if the surrounding constant expression 3810f785676fSDimitry Andric // modifies the temporary. 3811f785676fSDimitry Andric Value = getContext().getMaterializedTemporaryValue(E, false); 3812f785676fSDimitry Andric if (Value && Value->isUninit()) 381359d1ed5bSDimitry Andric Value = nullptr; 3814f785676fSDimitry Andric } 3815f785676fSDimitry Andric 3816f785676fSDimitry Andric // Try evaluating it now, it might have a constant initializer. 3817f785676fSDimitry Andric Expr::EvalResult EvalResult; 3818f785676fSDimitry Andric if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 3819f785676fSDimitry Andric !EvalResult.hasSideEffects()) 3820f785676fSDimitry Andric Value = &EvalResult.Val; 3821f785676fSDimitry Andric 38229a199699SDimitry Andric LangAS AddrSpace = 38239a199699SDimitry Andric VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace(); 38249a199699SDimitry Andric 38259a199699SDimitry Andric Optional<ConstantEmitter> emitter; 382659d1ed5bSDimitry Andric llvm::Constant *InitialValue = nullptr; 3827f785676fSDimitry Andric bool Constant = false; 3828f785676fSDimitry Andric llvm::Type *Type; 3829f785676fSDimitry Andric if (Value) { 3830f785676fSDimitry Andric // The temporary has a constant initializer, use it. 38319a199699SDimitry Andric emitter.emplace(*this); 38329a199699SDimitry Andric InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 38339a199699SDimitry Andric MaterializedType); 3834f785676fSDimitry Andric Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 3835f785676fSDimitry Andric Type = InitialValue->getType(); 3836f785676fSDimitry Andric } else { 3837f785676fSDimitry Andric // No initializer, the initialization will be provided when we 3838f785676fSDimitry Andric // initialize the declaration which performed lifetime extension. 3839f785676fSDimitry Andric Type = getTypes().ConvertTypeForMem(MaterializedType); 3840f785676fSDimitry Andric } 3841f785676fSDimitry Andric 3842f785676fSDimitry Andric // Create a global variable for this lifetime-extended temporary. 384359d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 384459d1ed5bSDimitry Andric getLLVMLinkageVarDefinition(VD, Constant); 384533956c43SDimitry Andric if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 384633956c43SDimitry Andric const VarDecl *InitVD; 384733956c43SDimitry Andric if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 384833956c43SDimitry Andric isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 384933956c43SDimitry Andric // Temporaries defined inside a class get linkonce_odr linkage because the 385033956c43SDimitry Andric // class can be defined in multipe translation units. 385133956c43SDimitry Andric Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 385233956c43SDimitry Andric } else { 385333956c43SDimitry Andric // There is no need for this temporary to have external linkage if the 385433956c43SDimitry Andric // VarDecl has external linkage. 385533956c43SDimitry Andric Linkage = llvm::GlobalVariable::InternalLinkage; 385633956c43SDimitry Andric } 385733956c43SDimitry Andric } 3858c4394386SDimitry Andric auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 385959d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 386059d1ed5bSDimitry Andric getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 3861c4394386SDimitry Andric /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 38629a199699SDimitry Andric if (emitter) emitter->finalize(GV); 38639a199699SDimitry Andric setGlobalVisibility(GV, VD, ForDefinition); 38640623d748SDimitry Andric GV->setAlignment(Align.getQuantity()); 386533956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker()) 386633956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3867f785676fSDimitry Andric if (VD->getTLSKind()) 3868f785676fSDimitry Andric setTLSMode(GV, *VD); 3869c4394386SDimitry Andric llvm::Constant *CV = GV; 3870c4394386SDimitry Andric if (AddrSpace != LangAS::Default) 3871c4394386SDimitry Andric CV = getTargetCodeGenInfo().performAddrSpaceCast( 3872c4394386SDimitry Andric *this, GV, AddrSpace, LangAS::Default, 3873c4394386SDimitry Andric Type->getPointerTo( 3874c4394386SDimitry Andric getContext().getTargetAddressSpace(LangAS::Default))); 3875c4394386SDimitry Andric MaterializedGlobalTemporaryMap[E] = CV; 3876c4394386SDimitry Andric return ConstantAddress(CV, Align); 3877f785676fSDimitry Andric } 3878f785676fSDimitry Andric 3879f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized 3880f22ef01cSRoman Divacky /// properties for an implementation. 3881f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const 3882f22ef01cSRoman Divacky ObjCImplementationDecl *D) { 388359d1ed5bSDimitry Andric for (const auto *PID : D->property_impls()) { 3884f22ef01cSRoman Divacky // Dynamic is just for type-checking. 3885f22ef01cSRoman Divacky if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 3886f22ef01cSRoman Divacky ObjCPropertyDecl *PD = PID->getPropertyDecl(); 3887f22ef01cSRoman Divacky 3888f22ef01cSRoman Divacky // Determine which methods need to be implemented, some may have 38893861d79fSDimitry Andric // been overridden. Note that ::isPropertyAccessor is not the method 3890f22ef01cSRoman Divacky // we want, that just indicates if the decl came from a 3891f22ef01cSRoman Divacky // property. What we want to know is if the method is defined in 3892f22ef01cSRoman Divacky // this implementation. 3893f22ef01cSRoman Divacky if (!D->getInstanceMethod(PD->getGetterName())) 3894f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCGetter( 3895f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3896f22ef01cSRoman Divacky if (!PD->isReadOnly() && 3897f22ef01cSRoman Divacky !D->getInstanceMethod(PD->getSetterName())) 3898f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCSetter( 3899f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3900f22ef01cSRoman Divacky } 3901f22ef01cSRoman Divacky } 3902f22ef01cSRoman Divacky } 3903f22ef01cSRoman Divacky 39043b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) { 39056122f3e6SDimitry Andric const ObjCInterfaceDecl *iface = impl->getClassInterface(); 39066122f3e6SDimitry Andric for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 39073b0f4066SDimitry Andric ivar; ivar = ivar->getNextIvar()) 39083b0f4066SDimitry Andric if (ivar->getType().isDestructedType()) 39093b0f4066SDimitry Andric return true; 39103b0f4066SDimitry Andric 39113b0f4066SDimitry Andric return false; 39123b0f4066SDimitry Andric } 39133b0f4066SDimitry Andric 391439d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM, 391539d628a0SDimitry Andric ObjCImplementationDecl *D) { 391639d628a0SDimitry Andric CodeGenFunction CGF(CGM); 391739d628a0SDimitry Andric for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 391839d628a0SDimitry Andric E = D->init_end(); B != E; ++B) { 391939d628a0SDimitry Andric CXXCtorInitializer *CtorInitExp = *B; 392039d628a0SDimitry Andric Expr *Init = CtorInitExp->getInit(); 392139d628a0SDimitry Andric if (!CGF.isTrivialInitializer(Init)) 392239d628a0SDimitry Andric return false; 392339d628a0SDimitry Andric } 392439d628a0SDimitry Andric return true; 392539d628a0SDimitry Andric } 392639d628a0SDimitry Andric 3927f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization 3928f22ef01cSRoman Divacky /// for an implementation. 3929f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 39303b0f4066SDimitry Andric // We might need a .cxx_destruct even if we don't have any ivar initializers. 39313b0f4066SDimitry Andric if (needsDestructMethod(D)) { 3932f22ef01cSRoman Divacky IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 3933f22ef01cSRoman Divacky Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 39343b0f4066SDimitry Andric ObjCMethodDecl *DTORMethod = 39353b0f4066SDimitry Andric ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 393659d1ed5bSDimitry Andric cxxSelector, getContext().VoidTy, nullptr, D, 39376122f3e6SDimitry Andric /*isInstance=*/true, /*isVariadic=*/false, 39383861d79fSDimitry Andric /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 39396122f3e6SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 3940f22ef01cSRoman Divacky D->addInstanceMethod(DTORMethod); 3941f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 39423861d79fSDimitry Andric D->setHasDestructors(true); 39433b0f4066SDimitry Andric } 3944f22ef01cSRoman Divacky 39453b0f4066SDimitry Andric // If the implementation doesn't have any ivar initializers, we don't need 39463b0f4066SDimitry Andric // a .cxx_construct. 394739d628a0SDimitry Andric if (D->getNumIvarInitializers() == 0 || 394839d628a0SDimitry Andric AllTrivialInitializers(*this, D)) 39493b0f4066SDimitry Andric return; 39503b0f4066SDimitry Andric 39513b0f4066SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 39523b0f4066SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 3953f22ef01cSRoman Divacky // The constructor returns 'self'. 3954f22ef01cSRoman Divacky ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 3955f22ef01cSRoman Divacky D->getLocation(), 39566122f3e6SDimitry Andric D->getLocation(), 39576122f3e6SDimitry Andric cxxSelector, 395859d1ed5bSDimitry Andric getContext().getObjCIdType(), 395959d1ed5bSDimitry Andric nullptr, D, /*isInstance=*/true, 39606122f3e6SDimitry Andric /*isVariadic=*/false, 39613861d79fSDimitry Andric /*isPropertyAccessor=*/true, 39626122f3e6SDimitry Andric /*isImplicitlyDeclared=*/true, 39636122f3e6SDimitry Andric /*isDefined=*/false, 3964f22ef01cSRoman Divacky ObjCMethodDecl::Required); 3965f22ef01cSRoman Divacky D->addInstanceMethod(CTORMethod); 3966f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 39673861d79fSDimitry Andric D->setHasNonZeroConstructors(true); 3968f22ef01cSRoman Divacky } 3969f22ef01cSRoman Divacky 3970f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec. 3971f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 3972f22ef01cSRoman Divacky if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 3973f22ef01cSRoman Divacky LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 3974f22ef01cSRoman Divacky ErrorUnsupported(LSD, "linkage spec"); 3975f22ef01cSRoman Divacky return; 3976f22ef01cSRoman Divacky } 3977f22ef01cSRoman Divacky 397844290647SDimitry Andric EmitDeclContext(LSD); 397944290647SDimitry Andric } 398044290647SDimitry Andric 398144290647SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 398244290647SDimitry Andric for (auto *I : DC->decls()) { 398344290647SDimitry Andric // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 398444290647SDimitry Andric // are themselves considered "top-level", so EmitTopLevelDecl on an 398544290647SDimitry Andric // ObjCImplDecl does not recursively visit them. We need to do that in 398644290647SDimitry Andric // case they're nested inside another construct (LinkageSpecDecl / 398744290647SDimitry Andric // ExportDecl) that does stop them from being considered "top-level". 398859d1ed5bSDimitry Andric if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 398959d1ed5bSDimitry Andric for (auto *M : OID->methods()) 399059d1ed5bSDimitry Andric EmitTopLevelDecl(M); 39913861d79fSDimitry Andric } 399244290647SDimitry Andric 399359d1ed5bSDimitry Andric EmitTopLevelDecl(I); 3994f22ef01cSRoman Divacky } 39953861d79fSDimitry Andric } 3996f22ef01cSRoman Divacky 3997f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration. 3998f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) { 3999f22ef01cSRoman Divacky // Ignore dependent declarations. 4000f22ef01cSRoman Divacky if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 4001f22ef01cSRoman Divacky return; 4002f22ef01cSRoman Divacky 4003f22ef01cSRoman Divacky switch (D->getKind()) { 4004f22ef01cSRoman Divacky case Decl::CXXConversion: 4005f22ef01cSRoman Divacky case Decl::CXXMethod: 4006f22ef01cSRoman Divacky case Decl::Function: 4007f22ef01cSRoman Divacky // Skip function templates 40083b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 40093b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 4010f22ef01cSRoman Divacky return; 4011f22ef01cSRoman Divacky 4012f22ef01cSRoman Divacky EmitGlobal(cast<FunctionDecl>(D)); 401339d628a0SDimitry Andric // Always provide some coverage mapping 401439d628a0SDimitry Andric // even for the functions that aren't emitted. 401539d628a0SDimitry Andric AddDeferredUnusedCoverageMapping(D); 4016f22ef01cSRoman Divacky break; 4017f22ef01cSRoman Divacky 40186bc11b14SDimitry Andric case Decl::CXXDeductionGuide: 40196bc11b14SDimitry Andric // Function-like, but does not result in code emission. 40206bc11b14SDimitry Andric break; 40216bc11b14SDimitry Andric 4022f22ef01cSRoman Divacky case Decl::Var: 402344290647SDimitry Andric case Decl::Decomposition: 4024f785676fSDimitry Andric // Skip variable templates 4025f785676fSDimitry Andric if (cast<VarDecl>(D)->getDescribedVarTemplate()) 4026f785676fSDimitry Andric return; 40276d97bb29SDimitry Andric LLVM_FALLTHROUGH; 4028f785676fSDimitry Andric case Decl::VarTemplateSpecialization: 4029f22ef01cSRoman Divacky EmitGlobal(cast<VarDecl>(D)); 403044290647SDimitry Andric if (auto *DD = dyn_cast<DecompositionDecl>(D)) 403144290647SDimitry Andric for (auto *B : DD->bindings()) 403244290647SDimitry Andric if (auto *HD = B->getHoldingVar()) 403344290647SDimitry Andric EmitGlobal(HD); 4034f22ef01cSRoman Divacky break; 4035f22ef01cSRoman Divacky 40363b0f4066SDimitry Andric // Indirect fields from global anonymous structs and unions can be 40373b0f4066SDimitry Andric // ignored; only the actual variable requires IR gen support. 40383b0f4066SDimitry Andric case Decl::IndirectField: 40393b0f4066SDimitry Andric break; 40403b0f4066SDimitry Andric 4041f22ef01cSRoman Divacky // C++ Decls 4042f22ef01cSRoman Divacky case Decl::Namespace: 404344290647SDimitry Andric EmitDeclContext(cast<NamespaceDecl>(D)); 4044f22ef01cSRoman Divacky break; 40459a199699SDimitry Andric case Decl::ClassTemplateSpecialization: { 40469a199699SDimitry Andric const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 40479a199699SDimitry Andric if (DebugInfo && 40489a199699SDimitry Andric Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition && 40499a199699SDimitry Andric Spec->hasDefinition()) 40509a199699SDimitry Andric DebugInfo->completeTemplateDefinition(*Spec); 40519a199699SDimitry Andric } LLVM_FALLTHROUGH; 4052e7145dcbSDimitry Andric case Decl::CXXRecord: 405320e90f04SDimitry Andric if (DebugInfo) { 405420e90f04SDimitry Andric if (auto *ES = D->getASTContext().getExternalSource()) 405520e90f04SDimitry Andric if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 405620e90f04SDimitry Andric DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D)); 405720e90f04SDimitry Andric } 4058e7145dcbSDimitry Andric // Emit any static data members, they may be definitions. 4059e7145dcbSDimitry Andric for (auto *I : cast<CXXRecordDecl>(D)->decls()) 4060e7145dcbSDimitry Andric if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 4061e7145dcbSDimitry Andric EmitTopLevelDecl(I); 4062e7145dcbSDimitry Andric break; 4063f22ef01cSRoman Divacky // No code generation needed. 4064f22ef01cSRoman Divacky case Decl::UsingShadow: 4065f22ef01cSRoman Divacky case Decl::ClassTemplate: 4066f785676fSDimitry Andric case Decl::VarTemplate: 4067f785676fSDimitry Andric case Decl::VarTemplatePartialSpecialization: 4068f22ef01cSRoman Divacky case Decl::FunctionTemplate: 4069bd5abe19SDimitry Andric case Decl::TypeAliasTemplate: 4070bd5abe19SDimitry Andric case Decl::Block: 4071139f7f9bSDimitry Andric case Decl::Empty: 4072f22ef01cSRoman Divacky break; 407359d1ed5bSDimitry Andric case Decl::Using: // using X; [C++] 407459d1ed5bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 407559d1ed5bSDimitry Andric DI->EmitUsingDecl(cast<UsingDecl>(*D)); 407659d1ed5bSDimitry Andric return; 4077f785676fSDimitry Andric case Decl::NamespaceAlias: 4078f785676fSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 4079f785676fSDimitry Andric DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 4080f785676fSDimitry Andric return; 4081284c1978SDimitry Andric case Decl::UsingDirective: // using namespace X; [C++] 4082284c1978SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 4083284c1978SDimitry Andric DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 4084284c1978SDimitry Andric return; 4085f22ef01cSRoman Divacky case Decl::CXXConstructor: 4086f22ef01cSRoman Divacky // Skip function templates 40873b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 40883b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 4089f22ef01cSRoman Divacky return; 4090f22ef01cSRoman Divacky 4091f785676fSDimitry Andric getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 4092f22ef01cSRoman Divacky break; 4093f22ef01cSRoman Divacky case Decl::CXXDestructor: 40943b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 40953b0f4066SDimitry Andric return; 4096f785676fSDimitry Andric getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 4097f22ef01cSRoman Divacky break; 4098f22ef01cSRoman Divacky 4099f22ef01cSRoman Divacky case Decl::StaticAssert: 4100f22ef01cSRoman Divacky // Nothing to do. 4101f22ef01cSRoman Divacky break; 4102f22ef01cSRoman Divacky 4103f22ef01cSRoman Divacky // Objective-C Decls 4104f22ef01cSRoman Divacky 4105f22ef01cSRoman Divacky // Forward declarations, no (immediate) code generation. 4106f22ef01cSRoman Divacky case Decl::ObjCInterface: 41077ae0e2c9SDimitry Andric case Decl::ObjCCategory: 4108f22ef01cSRoman Divacky break; 4109f22ef01cSRoman Divacky 4110dff0c46cSDimitry Andric case Decl::ObjCProtocol: { 411159d1ed5bSDimitry Andric auto *Proto = cast<ObjCProtocolDecl>(D); 4112dff0c46cSDimitry Andric if (Proto->isThisDeclarationADefinition()) 4113dff0c46cSDimitry Andric ObjCRuntime->GenerateProtocol(Proto); 4114f22ef01cSRoman Divacky break; 4115dff0c46cSDimitry Andric } 4116f22ef01cSRoman Divacky 4117f22ef01cSRoman Divacky case Decl::ObjCCategoryImpl: 4118f22ef01cSRoman Divacky // Categories have properties but don't support synthesize so we 4119f22ef01cSRoman Divacky // can ignore them here. 41206122f3e6SDimitry Andric ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 4121f22ef01cSRoman Divacky break; 4122f22ef01cSRoman Divacky 4123f22ef01cSRoman Divacky case Decl::ObjCImplementation: { 412459d1ed5bSDimitry Andric auto *OMD = cast<ObjCImplementationDecl>(D); 4125f22ef01cSRoman Divacky EmitObjCPropertyImplementations(OMD); 4126f22ef01cSRoman Divacky EmitObjCIvarInitializations(OMD); 41276122f3e6SDimitry Andric ObjCRuntime->GenerateClass(OMD); 4128dff0c46cSDimitry Andric // Emit global variable debug information. 4129dff0c46cSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 4130e7145dcbSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) 4131139f7f9bSDimitry Andric DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 4132139f7f9bSDimitry Andric OMD->getClassInterface()), OMD->getLocation()); 4133f22ef01cSRoman Divacky break; 4134f22ef01cSRoman Divacky } 4135f22ef01cSRoman Divacky case Decl::ObjCMethod: { 413659d1ed5bSDimitry Andric auto *OMD = cast<ObjCMethodDecl>(D); 4137f22ef01cSRoman Divacky // If this is not a prototype, emit the body. 4138f22ef01cSRoman Divacky if (OMD->getBody()) 4139f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCMethod(OMD); 4140f22ef01cSRoman Divacky break; 4141f22ef01cSRoman Divacky } 4142f22ef01cSRoman Divacky case Decl::ObjCCompatibleAlias: 4143dff0c46cSDimitry Andric ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 4144f22ef01cSRoman Divacky break; 4145f22ef01cSRoman Divacky 4146e7145dcbSDimitry Andric case Decl::PragmaComment: { 4147e7145dcbSDimitry Andric const auto *PCD = cast<PragmaCommentDecl>(D); 4148e7145dcbSDimitry Andric switch (PCD->getCommentKind()) { 4149e7145dcbSDimitry Andric case PCK_Unknown: 4150e7145dcbSDimitry Andric llvm_unreachable("unexpected pragma comment kind"); 4151e7145dcbSDimitry Andric case PCK_Linker: 4152e7145dcbSDimitry Andric AppendLinkerOptions(PCD->getArg()); 4153e7145dcbSDimitry Andric break; 4154e7145dcbSDimitry Andric case PCK_Lib: 4155e7145dcbSDimitry Andric AddDependentLib(PCD->getArg()); 4156e7145dcbSDimitry Andric break; 4157e7145dcbSDimitry Andric case PCK_Compiler: 4158e7145dcbSDimitry Andric case PCK_ExeStr: 4159e7145dcbSDimitry Andric case PCK_User: 4160e7145dcbSDimitry Andric break; // We ignore all of these. 4161e7145dcbSDimitry Andric } 4162e7145dcbSDimitry Andric break; 4163e7145dcbSDimitry Andric } 4164e7145dcbSDimitry Andric 4165e7145dcbSDimitry Andric case Decl::PragmaDetectMismatch: { 4166e7145dcbSDimitry Andric const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 4167e7145dcbSDimitry Andric AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 4168e7145dcbSDimitry Andric break; 4169e7145dcbSDimitry Andric } 4170e7145dcbSDimitry Andric 4171f22ef01cSRoman Divacky case Decl::LinkageSpec: 4172f22ef01cSRoman Divacky EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 4173f22ef01cSRoman Divacky break; 4174f22ef01cSRoman Divacky 4175f22ef01cSRoman Divacky case Decl::FileScopeAsm: { 417633956c43SDimitry Andric // File-scope asm is ignored during device-side CUDA compilation. 417733956c43SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 417833956c43SDimitry Andric break; 4179ea942507SDimitry Andric // File-scope asm is ignored during device-side OpenMP compilation. 4180ea942507SDimitry Andric if (LangOpts.OpenMPIsDevice) 4181ea942507SDimitry Andric break; 418259d1ed5bSDimitry Andric auto *AD = cast<FileScopeAsmDecl>(D); 418333956c43SDimitry Andric getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 4184f22ef01cSRoman Divacky break; 4185f22ef01cSRoman Divacky } 4186f22ef01cSRoman Divacky 4187139f7f9bSDimitry Andric case Decl::Import: { 418859d1ed5bSDimitry Andric auto *Import = cast<ImportDecl>(D); 4189139f7f9bSDimitry Andric 419044290647SDimitry Andric // If we've already imported this module, we're done. 419144290647SDimitry Andric if (!ImportedModules.insert(Import->getImportedModule())) 4192139f7f9bSDimitry Andric break; 419344290647SDimitry Andric 419444290647SDimitry Andric // Emit debug information for direct imports. 419544290647SDimitry Andric if (!Import->getImportedOwningModule()) { 41963dac3a9bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 41973dac3a9bSDimitry Andric DI->EmitImportDecl(*Import); 419844290647SDimitry Andric } 4199139f7f9bSDimitry Andric 420044290647SDimitry Andric // Find all of the submodules and emit the module initializers. 420144290647SDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 420244290647SDimitry Andric SmallVector<clang::Module *, 16> Stack; 420344290647SDimitry Andric Visited.insert(Import->getImportedModule()); 420444290647SDimitry Andric Stack.push_back(Import->getImportedModule()); 420544290647SDimitry Andric 420644290647SDimitry Andric while (!Stack.empty()) { 420744290647SDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 420844290647SDimitry Andric if (!EmittedModuleInitializers.insert(Mod).second) 420944290647SDimitry Andric continue; 421044290647SDimitry Andric 421144290647SDimitry Andric for (auto *D : Context.getModuleInitializers(Mod)) 421244290647SDimitry Andric EmitTopLevelDecl(D); 421344290647SDimitry Andric 421444290647SDimitry Andric // Visit the submodules of this module. 421544290647SDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 421644290647SDimitry Andric SubEnd = Mod->submodule_end(); 421744290647SDimitry Andric Sub != SubEnd; ++Sub) { 421844290647SDimitry Andric // Skip explicit children; they need to be explicitly imported to emit 421944290647SDimitry Andric // the initializers. 422044290647SDimitry Andric if ((*Sub)->IsExplicit) 422144290647SDimitry Andric continue; 422244290647SDimitry Andric 422344290647SDimitry Andric if (Visited.insert(*Sub).second) 422444290647SDimitry Andric Stack.push_back(*Sub); 422544290647SDimitry Andric } 422644290647SDimitry Andric } 4227139f7f9bSDimitry Andric break; 4228139f7f9bSDimitry Andric } 4229139f7f9bSDimitry Andric 423044290647SDimitry Andric case Decl::Export: 423144290647SDimitry Andric EmitDeclContext(cast<ExportDecl>(D)); 423244290647SDimitry Andric break; 423344290647SDimitry Andric 423439d628a0SDimitry Andric case Decl::OMPThreadPrivate: 423539d628a0SDimitry Andric EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 423639d628a0SDimitry Andric break; 423739d628a0SDimitry Andric 4238e7145dcbSDimitry Andric case Decl::OMPDeclareReduction: 4239e7145dcbSDimitry Andric EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 4240e7145dcbSDimitry Andric break; 4241e7145dcbSDimitry Andric 4242f22ef01cSRoman Divacky default: 4243f22ef01cSRoman Divacky // Make sure we handled everything we should, every other kind is a 4244f22ef01cSRoman Divacky // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 4245f22ef01cSRoman Divacky // function. Need to recode Decl::Kind to do that easily. 4246f22ef01cSRoman Divacky assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 424739d628a0SDimitry Andric break; 424839d628a0SDimitry Andric } 424939d628a0SDimitry Andric } 425039d628a0SDimitry Andric 425139d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 425239d628a0SDimitry Andric // Do we need to generate coverage mapping? 425339d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 425439d628a0SDimitry Andric return; 425539d628a0SDimitry Andric switch (D->getKind()) { 425639d628a0SDimitry Andric case Decl::CXXConversion: 425739d628a0SDimitry Andric case Decl::CXXMethod: 425839d628a0SDimitry Andric case Decl::Function: 425939d628a0SDimitry Andric case Decl::ObjCMethod: 426039d628a0SDimitry Andric case Decl::CXXConstructor: 426139d628a0SDimitry Andric case Decl::CXXDestructor: { 42620623d748SDimitry Andric if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 426339d628a0SDimitry Andric return; 42649a199699SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 42659a199699SDimitry Andric if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart())) 42669a199699SDimitry Andric return; 426739d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 426839d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 426939d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = true; 427039d628a0SDimitry Andric break; 427139d628a0SDimitry Andric } 427239d628a0SDimitry Andric default: 427339d628a0SDimitry Andric break; 427439d628a0SDimitry Andric }; 427539d628a0SDimitry Andric } 427639d628a0SDimitry Andric 427739d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 427839d628a0SDimitry Andric // Do we need to generate coverage mapping? 427939d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 428039d628a0SDimitry Andric return; 428139d628a0SDimitry Andric if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 428239d628a0SDimitry Andric if (Fn->isTemplateInstantiation()) 428339d628a0SDimitry Andric ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 428439d628a0SDimitry Andric } 428539d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 428639d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 428739d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = false; 428839d628a0SDimitry Andric else 428939d628a0SDimitry Andric I->second = false; 429039d628a0SDimitry Andric } 429139d628a0SDimitry Andric 429239d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 429313ddaa84SDimitry Andric // We call takeVector() here to avoid use-after-free. 429413ddaa84SDimitry Andric // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 429513ddaa84SDimitry Andric // we deserialize function bodies to emit coverage info for them, and that 429613ddaa84SDimitry Andric // deserializes more declarations. How should we handle that case? 429713ddaa84SDimitry Andric for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 42989a199699SDimitry Andric if (!Entry.second) 429939d628a0SDimitry Andric continue; 43009a199699SDimitry Andric const Decl *D = Entry.first; 430139d628a0SDimitry Andric switch (D->getKind()) { 430239d628a0SDimitry Andric case Decl::CXXConversion: 430339d628a0SDimitry Andric case Decl::CXXMethod: 430439d628a0SDimitry Andric case Decl::Function: 430539d628a0SDimitry Andric case Decl::ObjCMethod: { 430639d628a0SDimitry Andric CodeGenPGO PGO(*this); 430739d628a0SDimitry Andric GlobalDecl GD(cast<FunctionDecl>(D)); 430839d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 430939d628a0SDimitry Andric getFunctionLinkage(GD)); 431039d628a0SDimitry Andric break; 431139d628a0SDimitry Andric } 431239d628a0SDimitry Andric case Decl::CXXConstructor: { 431339d628a0SDimitry Andric CodeGenPGO PGO(*this); 431439d628a0SDimitry Andric GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 431539d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 431639d628a0SDimitry Andric getFunctionLinkage(GD)); 431739d628a0SDimitry Andric break; 431839d628a0SDimitry Andric } 431939d628a0SDimitry Andric case Decl::CXXDestructor: { 432039d628a0SDimitry Andric CodeGenPGO PGO(*this); 432139d628a0SDimitry Andric GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 432239d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 432339d628a0SDimitry Andric getFunctionLinkage(GD)); 432439d628a0SDimitry Andric break; 432539d628a0SDimitry Andric } 432639d628a0SDimitry Andric default: 432739d628a0SDimitry Andric break; 432839d628a0SDimitry Andric }; 4329f22ef01cSRoman Divacky } 4330f22ef01cSRoman Divacky } 4331ffd1746dSEd Schouten 4332ffd1746dSEd Schouten /// Turns the given pointer into a constant. 4333ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 4334ffd1746dSEd Schouten const void *Ptr) { 4335ffd1746dSEd Schouten uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 43366122f3e6SDimitry Andric llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 4337ffd1746dSEd Schouten return llvm::ConstantInt::get(i64, PtrInt); 4338ffd1746dSEd Schouten } 4339ffd1746dSEd Schouten 4340ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 4341ffd1746dSEd Schouten llvm::NamedMDNode *&GlobalMetadata, 4342ffd1746dSEd Schouten GlobalDecl D, 4343ffd1746dSEd Schouten llvm::GlobalValue *Addr) { 4344ffd1746dSEd Schouten if (!GlobalMetadata) 4345ffd1746dSEd Schouten GlobalMetadata = 4346ffd1746dSEd Schouten CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 4347ffd1746dSEd Schouten 4348ffd1746dSEd Schouten // TODO: should we report variant information for ctors/dtors? 434939d628a0SDimitry Andric llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 435039d628a0SDimitry Andric llvm::ConstantAsMetadata::get(GetPointerConstant( 435139d628a0SDimitry Andric CGM.getLLVMContext(), D.getDecl()))}; 43523b0f4066SDimitry Andric GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 4353ffd1746dSEd Schouten } 4354ffd1746dSEd Schouten 4355284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked 4356284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled 4357284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer 4358284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the 4359284c1978SDimitry Andric /// same translation unit. 4360284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() { 4361e7145dcbSDimitry Andric // Don't do anything if we're generating CUDA device code -- the NVPTX 4362e7145dcbSDimitry Andric // assembly target doesn't support aliases. 4363e7145dcbSDimitry Andric if (Context.getTargetInfo().getTriple().isNVPTX()) 4364e7145dcbSDimitry Andric return; 43658f0fd8f6SDimitry Andric for (auto &I : StaticExternCValues) { 43668f0fd8f6SDimitry Andric IdentifierInfo *Name = I.first; 43678f0fd8f6SDimitry Andric llvm::GlobalValue *Val = I.second; 4368284c1978SDimitry Andric if (Val && !getModule().getNamedValue(Name->getName())) 436959d1ed5bSDimitry Andric addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 4370284c1978SDimitry Andric } 4371284c1978SDimitry Andric } 4372284c1978SDimitry Andric 437359d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 437459d1ed5bSDimitry Andric GlobalDecl &Result) const { 437559d1ed5bSDimitry Andric auto Res = Manglings.find(MangledName); 437659d1ed5bSDimitry Andric if (Res == Manglings.end()) 437759d1ed5bSDimitry Andric return false; 437859d1ed5bSDimitry Andric Result = Res->getValue(); 437959d1ed5bSDimitry Andric return true; 438059d1ed5bSDimitry Andric } 438159d1ed5bSDimitry Andric 4382ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the 4383ffd1746dSEd Schouten /// current module with the Decls they came from. This is useful for 4384ffd1746dSEd Schouten /// projects using IR gen as a subroutine. 4385ffd1746dSEd Schouten /// 4386ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly 4387ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata 4388ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'. 4389ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() { 439059d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 4391ffd1746dSEd Schouten 439259d1ed5bSDimitry Andric for (auto &I : MangledDeclNames) { 439359d1ed5bSDimitry Andric llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 43940623d748SDimitry Andric // Some mangled names don't necessarily have an associated GlobalValue 43950623d748SDimitry Andric // in this module, e.g. if we mangled it for DebugInfo. 43960623d748SDimitry Andric if (Addr) 439759d1ed5bSDimitry Andric EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 4398ffd1746dSEd Schouten } 4399ffd1746dSEd Schouten } 4400ffd1746dSEd Schouten 4401ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current 4402ffd1746dSEd Schouten /// function. 4403ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() { 4404ffd1746dSEd Schouten if (LocalDeclMap.empty()) return; 4405ffd1746dSEd Schouten 4406ffd1746dSEd Schouten llvm::LLVMContext &Context = getLLVMContext(); 4407ffd1746dSEd Schouten 4408ffd1746dSEd Schouten // Find the unique metadata ID for this name. 4409ffd1746dSEd Schouten unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 4410ffd1746dSEd Schouten 441159d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 4412ffd1746dSEd Schouten 441359d1ed5bSDimitry Andric for (auto &I : LocalDeclMap) { 441459d1ed5bSDimitry Andric const Decl *D = I.first; 44150623d748SDimitry Andric llvm::Value *Addr = I.second.getPointer(); 441659d1ed5bSDimitry Andric if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 4417ffd1746dSEd Schouten llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 441839d628a0SDimitry Andric Alloca->setMetadata( 441939d628a0SDimitry Andric DeclPtrKind, llvm::MDNode::get( 442039d628a0SDimitry Andric Context, llvm::ValueAsMetadata::getConstant(DAddr))); 442159d1ed5bSDimitry Andric } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 4422ffd1746dSEd Schouten GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 4423ffd1746dSEd Schouten EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 4424ffd1746dSEd Schouten } 4425ffd1746dSEd Schouten } 4426ffd1746dSEd Schouten } 4427e580952dSDimitry Andric 4428f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() { 4429f785676fSDimitry Andric llvm::NamedMDNode *IdentMetadata = 4430f785676fSDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.ident"); 4431f785676fSDimitry Andric std::string Version = getClangFullVersion(); 4432f785676fSDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 4433f785676fSDimitry Andric 443439d628a0SDimitry Andric llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 4435f785676fSDimitry Andric IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 4436f785676fSDimitry Andric } 4437f785676fSDimitry Andric 443859d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() { 443939d628a0SDimitry Andric // Warning, new MangledDeclNames may be appended within this loop. 444039d628a0SDimitry Andric // We rely on MapVector insertions adding new elements to the end 444139d628a0SDimitry Andric // of the container. 444239d628a0SDimitry Andric // FIXME: Move this loop into the one target that needs it, and only 444339d628a0SDimitry Andric // loop over those declarations for which we couldn't emit the target 444439d628a0SDimitry Andric // metadata when we emitted the declaration. 444539d628a0SDimitry Andric for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 444639d628a0SDimitry Andric auto Val = *(MangledDeclNames.begin() + I); 444739d628a0SDimitry Andric const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 444839d628a0SDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(Val.second); 444959d1ed5bSDimitry Andric getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 445059d1ed5bSDimitry Andric } 445159d1ed5bSDimitry Andric } 445259d1ed5bSDimitry Andric 4453bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() { 445444290647SDimitry Andric if (getCodeGenOpts().CoverageDataFile.empty() && 445544290647SDimitry Andric getCodeGenOpts().CoverageNotesFile.empty()) 445644290647SDimitry Andric return; 445744290647SDimitry Andric 445844290647SDimitry Andric llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 445944290647SDimitry Andric if (!CUNode) 446044290647SDimitry Andric return; 446144290647SDimitry Andric 4462bd5abe19SDimitry Andric llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 4463bd5abe19SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 446444290647SDimitry Andric auto *CoverageDataFile = 446544290647SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 446644290647SDimitry Andric auto *CoverageNotesFile = 446744290647SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 4468bd5abe19SDimitry Andric for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 4469bd5abe19SDimitry Andric llvm::MDNode *CU = CUNode->getOperand(i); 447044290647SDimitry Andric llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 447139d628a0SDimitry Andric GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 4472bd5abe19SDimitry Andric } 4473bd5abe19SDimitry Andric } 44743861d79fSDimitry Andric 447539d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { 44763861d79fSDimitry Andric // Sema has checked that all uuid strings are of the form 44773861d79fSDimitry Andric // "12345678-1234-1234-1234-1234567890ab". 44783861d79fSDimitry Andric assert(Uuid.size() == 36); 4479f785676fSDimitry Andric for (unsigned i = 0; i < 36; ++i) { 4480f785676fSDimitry Andric if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 4481f785676fSDimitry Andric else assert(isHexDigit(Uuid[i])); 44823861d79fSDimitry Andric } 44833861d79fSDimitry Andric 448439d628a0SDimitry Andric // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". 4485f785676fSDimitry Andric const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 44863861d79fSDimitry Andric 4487f785676fSDimitry Andric llvm::Constant *Field3[8]; 4488f785676fSDimitry Andric for (unsigned Idx = 0; Idx < 8; ++Idx) 4489f785676fSDimitry Andric Field3[Idx] = llvm::ConstantInt::get( 4490f785676fSDimitry Andric Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 44913861d79fSDimitry Andric 4492f785676fSDimitry Andric llvm::Constant *Fields[4] = { 4493f785676fSDimitry Andric llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 4494f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 4495f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 4496f785676fSDimitry Andric llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 4497f785676fSDimitry Andric }; 4498f785676fSDimitry Andric 4499f785676fSDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 45003861d79fSDimitry Andric } 450159d1ed5bSDimitry Andric 450259d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 450359d1ed5bSDimitry Andric bool ForEH) { 450459d1ed5bSDimitry Andric // Return a bogus pointer if RTTI is disabled, unless it's for EH. 450559d1ed5bSDimitry Andric // FIXME: should we even be calling this method if RTTI is disabled 450659d1ed5bSDimitry Andric // and it's not for EH? 450759d1ed5bSDimitry Andric if (!ForEH && !getLangOpts().RTTI) 450859d1ed5bSDimitry Andric return llvm::Constant::getNullValue(Int8PtrTy); 450959d1ed5bSDimitry Andric 451059d1ed5bSDimitry Andric if (ForEH && Ty->isObjCObjectPointerType() && 451159d1ed5bSDimitry Andric LangOpts.ObjCRuntime.isGNUFamily()) 451259d1ed5bSDimitry Andric return ObjCRuntime->GetEHType(Ty); 451359d1ed5bSDimitry Andric 451459d1ed5bSDimitry Andric return getCXXABI().getAddrOfRTTIDescriptor(Ty); 451559d1ed5bSDimitry Andric } 451659d1ed5bSDimitry Andric 451739d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 451839d628a0SDimitry Andric for (auto RefExpr : D->varlists()) { 451939d628a0SDimitry Andric auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 452039d628a0SDimitry Andric bool PerformInit = 452139d628a0SDimitry Andric VD->getAnyInitializer() && 452239d628a0SDimitry Andric !VD->getAnyInitializer()->isConstantInitializer(getContext(), 452339d628a0SDimitry Andric /*ForRef=*/false); 45240623d748SDimitry Andric 45250623d748SDimitry Andric Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 452633956c43SDimitry Andric if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 45270623d748SDimitry Andric VD, Addr, RefExpr->getLocStart(), PerformInit)) 452839d628a0SDimitry Andric CXXGlobalInits.push_back(InitFunction); 452939d628a0SDimitry Andric } 453039d628a0SDimitry Andric } 45318f0fd8f6SDimitry Andric 45320623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 45330623d748SDimitry Andric llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()]; 45340623d748SDimitry Andric if (InternalId) 45350623d748SDimitry Andric return InternalId; 45360623d748SDimitry Andric 45370623d748SDimitry Andric if (isExternallyVisible(T->getLinkage())) { 45388f0fd8f6SDimitry Andric std::string OutName; 45398f0fd8f6SDimitry Andric llvm::raw_string_ostream Out(OutName); 45400623d748SDimitry Andric getCXXABI().getMangleContext().mangleTypeName(T, Out); 45418f0fd8f6SDimitry Andric 45420623d748SDimitry Andric InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 45430623d748SDimitry Andric } else { 45440623d748SDimitry Andric InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 45450623d748SDimitry Andric llvm::ArrayRef<llvm::Metadata *>()); 45460623d748SDimitry Andric } 45470623d748SDimitry Andric 45480623d748SDimitry Andric return InternalId; 45490623d748SDimitry Andric } 45500623d748SDimitry Andric 45519a199699SDimitry Andric // Generalize pointer types to a void pointer with the qualifiers of the 45529a199699SDimitry Andric // originally pointed-to type, e.g. 'const char *' and 'char * const *' 45539a199699SDimitry Andric // generalize to 'const void *' while 'char *' and 'const char **' generalize to 45549a199699SDimitry Andric // 'void *'. 45559a199699SDimitry Andric static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 45569a199699SDimitry Andric if (!Ty->isPointerType()) 45579a199699SDimitry Andric return Ty; 45589a199699SDimitry Andric 45599a199699SDimitry Andric return Ctx.getPointerType( 45609a199699SDimitry Andric QualType(Ctx.VoidTy).withCVRQualifiers( 45619a199699SDimitry Andric Ty->getPointeeType().getCVRQualifiers())); 45629a199699SDimitry Andric } 45639a199699SDimitry Andric 45649a199699SDimitry Andric // Apply type generalization to a FunctionType's return and argument types 45659a199699SDimitry Andric static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 45669a199699SDimitry Andric if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 45679a199699SDimitry Andric SmallVector<QualType, 8> GeneralizedParams; 45689a199699SDimitry Andric for (auto &Param : FnType->param_types()) 45699a199699SDimitry Andric GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 45709a199699SDimitry Andric 45719a199699SDimitry Andric return Ctx.getFunctionType( 45729a199699SDimitry Andric GeneralizeType(Ctx, FnType->getReturnType()), 45739a199699SDimitry Andric GeneralizedParams, FnType->getExtProtoInfo()); 45749a199699SDimitry Andric } 45759a199699SDimitry Andric 45769a199699SDimitry Andric if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 45779a199699SDimitry Andric return Ctx.getFunctionNoProtoType( 45789a199699SDimitry Andric GeneralizeType(Ctx, FnType->getReturnType())); 45799a199699SDimitry Andric 45809a199699SDimitry Andric llvm_unreachable("Encountered unknown FunctionType"); 45819a199699SDimitry Andric } 45829a199699SDimitry Andric 45839a199699SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 45849a199699SDimitry Andric T = GeneralizeFunctionType(getContext(), T); 45859a199699SDimitry Andric 45869a199699SDimitry Andric llvm::Metadata *&InternalId = GeneralizedMetadataIdMap[T.getCanonicalType()]; 45879a199699SDimitry Andric if (InternalId) 45889a199699SDimitry Andric return InternalId; 45899a199699SDimitry Andric 45909a199699SDimitry Andric if (isExternallyVisible(T->getLinkage())) { 45919a199699SDimitry Andric std::string OutName; 45929a199699SDimitry Andric llvm::raw_string_ostream Out(OutName); 45939a199699SDimitry Andric getCXXABI().getMangleContext().mangleTypeName(T, Out); 45949a199699SDimitry Andric Out << ".generalized"; 45959a199699SDimitry Andric 45969a199699SDimitry Andric InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 45979a199699SDimitry Andric } else { 45989a199699SDimitry Andric InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 45999a199699SDimitry Andric llvm::ArrayRef<llvm::Metadata *>()); 46009a199699SDimitry Andric } 46019a199699SDimitry Andric 46029a199699SDimitry Andric return InternalId; 46039a199699SDimitry Andric } 46049a199699SDimitry Andric 4605e7145dcbSDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier. 4606e7145dcbSDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const { 4607e7145dcbSDimitry Andric // Returns true if at least one of vtable-based CFI checkers is enabled and 4608e7145dcbSDimitry Andric // is not in the trapping mode. 4609e7145dcbSDimitry Andric return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 4610e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 4611e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 4612e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 4613e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 4614e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 4615e7145dcbSDimitry Andric (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 4616e7145dcbSDimitry Andric !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 4617e7145dcbSDimitry Andric } 4618e7145dcbSDimitry Andric 4619e7145dcbSDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 46200623d748SDimitry Andric CharUnits Offset, 46210623d748SDimitry Andric const CXXRecordDecl *RD) { 46220623d748SDimitry Andric llvm::Metadata *MD = 46230623d748SDimitry Andric CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 4624e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 46250623d748SDimitry Andric 4626e7145dcbSDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) 4627e7145dcbSDimitry Andric if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 4628e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), 4629e7145dcbSDimitry Andric llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 4630e7145dcbSDimitry Andric 4631e7145dcbSDimitry Andric if (NeedAllVtablesTypeId()) { 4632e7145dcbSDimitry Andric llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 4633e7145dcbSDimitry Andric VTable->addTypeMetadata(Offset.getQuantity(), MD); 46340623d748SDimitry Andric } 46350623d748SDimitry Andric } 46360623d748SDimitry Andric 46370623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the 46380623d748SDimitry Andric // passed in function. 46390623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 46400623d748SDimitry Andric const FunctionDecl *FD) { 46410623d748SDimitry Andric StringRef TargetCPU = Target.getTargetOpts().CPU; 46420623d748SDimitry Andric if (const auto *TD = FD->getAttr<TargetAttr>()) { 46430623d748SDimitry Andric // If we have a TargetAttr build up the feature map based on that. 46440623d748SDimitry Andric TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); 46450623d748SDimitry Andric 46469a199699SDimitry Andric ParsedAttr.Features.erase( 46479a199699SDimitry Andric llvm::remove_if(ParsedAttr.Features, 46489a199699SDimitry Andric [&](const std::string &Feat) { 46499a199699SDimitry Andric return !Target.isValidFeatureName( 46509a199699SDimitry Andric StringRef{Feat}.substr(1)); 46519a199699SDimitry Andric }), 46529a199699SDimitry Andric ParsedAttr.Features.end()); 46539a199699SDimitry Andric 46540623d748SDimitry Andric // Make a copy of the features as passed on the command line into the 46550623d748SDimitry Andric // beginning of the additional features from the function to override. 4656b40b48b8SDimitry Andric ParsedAttr.Features.insert(ParsedAttr.Features.begin(), 46570623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.begin(), 46580623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.end()); 46590623d748SDimitry Andric 46609a199699SDimitry Andric if (ParsedAttr.Architecture != "" && 46619a199699SDimitry Andric Target.isValidCPUName(ParsedAttr.Architecture)) 4662b40b48b8SDimitry Andric TargetCPU = ParsedAttr.Architecture; 46630623d748SDimitry Andric 46640623d748SDimitry Andric // Now populate the feature map, first with the TargetCPU which is either 46650623d748SDimitry Andric // the default or a new one from the target attribute string. Then we'll use 46660623d748SDimitry Andric // the passed in features (FeaturesAsWritten) along with the new ones from 46670623d748SDimitry Andric // the attribute. 4668b40b48b8SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 4669b40b48b8SDimitry Andric ParsedAttr.Features); 46700623d748SDimitry Andric } else { 46710623d748SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 46720623d748SDimitry Andric Target.getTargetOpts().Features); 46730623d748SDimitry Andric } 46748f0fd8f6SDimitry Andric } 4675e7145dcbSDimitry Andric 4676e7145dcbSDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 4677e7145dcbSDimitry Andric if (!SanStats) 4678e7145dcbSDimitry Andric SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule()); 4679e7145dcbSDimitry Andric 4680e7145dcbSDimitry Andric return *SanStats; 4681e7145dcbSDimitry Andric } 468244290647SDimitry Andric llvm::Value * 468344290647SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 468444290647SDimitry Andric CodeGenFunction &CGF) { 46859a199699SDimitry Andric llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 46869a199699SDimitry Andric auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 468744290647SDimitry Andric auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 468844290647SDimitry Andric return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy, 468944290647SDimitry Andric "__translate_sampler_initializer"), 469044290647SDimitry Andric {C}); 469144290647SDimitry Andric } 4692