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" 23139f7f9bSDimitry Andric #include "CodeGenFunction.h" 2459d1ed5bSDimitry Andric #include "CodeGenPGO.h" 25139f7f9bSDimitry Andric #include "CodeGenTBAA.h" 2639d628a0SDimitry Andric #include "CoverageMappingGen.h" 27f22ef01cSRoman Divacky #include "TargetInfo.h" 28f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h" 29f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h" 30f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h" 31139f7f9bSDimitry Andric #include "clang/AST/DeclObjC.h" 32ffd1746dSEd Schouten #include "clang/AST/DeclTemplate.h" 332754fe60SDimitry Andric #include "clang/AST/Mangle.h" 34f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h" 35f8254f43SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h" 36dff0c46cSDimitry Andric #include "clang/Basic/Builtins.h" 37139f7f9bSDimitry Andric #include "clang/Basic/CharInfo.h" 38f22ef01cSRoman Divacky #include "clang/Basic/Diagnostic.h" 39139f7f9bSDimitry Andric #include "clang/Basic/Module.h" 40f22ef01cSRoman Divacky #include "clang/Basic/SourceManager.h" 41f22ef01cSRoman Divacky #include "clang/Basic/TargetInfo.h" 42f785676fSDimitry Andric #include "clang/Basic/Version.h" 43139f7f9bSDimitry Andric #include "clang/Frontend/CodeGenOptions.h" 44f785676fSDimitry Andric #include "clang/Sema/SemaDiagnostic.h" 45dff0c46cSDimitry Andric #include "llvm/ADT/APSInt.h" 46f22ef01cSRoman Divacky #include "llvm/ADT/Triple.h" 4759d1ed5bSDimitry Andric #include "llvm/IR/CallSite.h" 48139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h" 49139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h" 50139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h" 51139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h" 52139f7f9bSDimitry Andric #include "llvm/IR/Module.h" 5359d1ed5bSDimitry Andric #include "llvm/ProfileData/InstrProfReader.h" 54139f7f9bSDimitry Andric #include "llvm/Support/ConvertUTF.h" 55f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h" 560623d748SDimitry Andric #include "llvm/Support/MD5.h" 57139f7f9bSDimitry Andric 58f22ef01cSRoman Divacky using namespace clang; 59f22ef01cSRoman Divacky using namespace CodeGen; 60f22ef01cSRoman Divacky 616122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata"; 626122f3e6SDimitry Andric 6359d1ed5bSDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 64284c1978SDimitry Andric switch (CGM.getTarget().getCXXABI().getKind()) { 65139f7f9bSDimitry Andric case TargetCXXABI::GenericAArch64: 66139f7f9bSDimitry Andric case TargetCXXABI::GenericARM: 67139f7f9bSDimitry Andric case TargetCXXABI::iOS: 6859d1ed5bSDimitry Andric case TargetCXXABI::iOS64: 690623d748SDimitry Andric case TargetCXXABI::WatchOS: 70ef6fa9e2SDimitry Andric case TargetCXXABI::GenericMIPS: 71139f7f9bSDimitry Andric case TargetCXXABI::GenericItanium: 720623d748SDimitry Andric case TargetCXXABI::WebAssembly: 7359d1ed5bSDimitry Andric return CreateItaniumCXXABI(CGM); 74139f7f9bSDimitry Andric case TargetCXXABI::Microsoft: 7559d1ed5bSDimitry Andric return CreateMicrosoftCXXABI(CGM); 76e580952dSDimitry Andric } 77e580952dSDimitry Andric 78e580952dSDimitry Andric llvm_unreachable("invalid C++ ABI kind"); 79e580952dSDimitry Andric } 80e580952dSDimitry Andric 813dac3a9bSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO, 823dac3a9bSDimitry Andric const PreprocessorOptions &PPO, 833dac3a9bSDimitry Andric const CodeGenOptions &CGO, llvm::Module &M, 8439d628a0SDimitry Andric DiagnosticsEngine &diags, 8539d628a0SDimitry Andric CoverageSourceInfo *CoverageInfo) 863dac3a9bSDimitry Andric : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO), 873dac3a9bSDimitry Andric PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), 880623d748SDimitry Andric Target(C.getTargetInfo()), ABI(createCXXABI(*this)), 893dac3a9bSDimitry Andric VMContext(M.getContext()), TBAA(nullptr), TheTargetCodeGenInfo(nullptr), 903dac3a9bSDimitry Andric Types(*this), VTables(*this), ObjCRuntime(nullptr), 913dac3a9bSDimitry Andric OpenCLRuntime(nullptr), OpenMPRuntime(nullptr), CUDARuntime(nullptr), 920623d748SDimitry Andric DebugInfo(nullptr), ObjCData(nullptr), 930623d748SDimitry Andric NoObjCARCExceptionsMetadata(nullptr), PGOReader(nullptr), 9459d1ed5bSDimitry Andric CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr), 9559d1ed5bSDimitry Andric NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr), 9659d1ed5bSDimitry Andric NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr), 9759d1ed5bSDimitry Andric BlockObjectDispose(nullptr), BlockDescriptorType(nullptr), 9859d1ed5bSDimitry Andric GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr), 9939d628a0SDimitry Andric LifetimeEndFn(nullptr), SanitizerMD(new SanitizerMetadata(*this)) { 100dff0c46cSDimitry Andric 101dff0c46cSDimitry Andric // Initialize the type cache. 102dff0c46cSDimitry Andric llvm::LLVMContext &LLVMContext = M.getContext(); 103dff0c46cSDimitry Andric VoidTy = llvm::Type::getVoidTy(LLVMContext); 104dff0c46cSDimitry Andric Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 105dff0c46cSDimitry Andric Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 106dff0c46cSDimitry Andric Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 107dff0c46cSDimitry Andric Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 108dff0c46cSDimitry Andric FloatTy = llvm::Type::getFloatTy(LLVMContext); 109dff0c46cSDimitry Andric DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 110dff0c46cSDimitry Andric PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 111dff0c46cSDimitry Andric PointerAlignInBytes = 112dff0c46cSDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 1130623d748SDimitry Andric IntAlignInBytes = 1140623d748SDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 115dff0c46cSDimitry Andric IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 116dff0c46cSDimitry Andric IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits); 117dff0c46cSDimitry Andric Int8PtrTy = Int8Ty->getPointerTo(0); 118dff0c46cSDimitry Andric Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 119dff0c46cSDimitry Andric 120139f7f9bSDimitry Andric RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 12139d628a0SDimitry Andric BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC(); 122139f7f9bSDimitry Andric 123dff0c46cSDimitry Andric if (LangOpts.ObjC1) 1243b0f4066SDimitry Andric createObjCRuntime(); 125dff0c46cSDimitry Andric if (LangOpts.OpenCL) 1266122f3e6SDimitry Andric createOpenCLRuntime(); 12759d1ed5bSDimitry Andric if (LangOpts.OpenMP) 12859d1ed5bSDimitry Andric createOpenMPRuntime(); 129dff0c46cSDimitry Andric if (LangOpts.CUDA) 1306122f3e6SDimitry Andric createCUDARuntime(); 131f22ef01cSRoman Divacky 1327ae0e2c9SDimitry Andric // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 13339d628a0SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 1347ae0e2c9SDimitry Andric (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 1357ae0e2c9SDimitry Andric TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(), 13659d1ed5bSDimitry Andric getCXXABI().getMangleContext()); 1372754fe60SDimitry Andric 1383b0f4066SDimitry Andric // If debug info or coverage generation is enabled, create the CGDebugInfo 1393b0f4066SDimitry Andric // object. 1403861d79fSDimitry Andric if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo || 1417ae0e2c9SDimitry Andric CodeGenOpts.EmitGcovArcs || 1423b0f4066SDimitry Andric CodeGenOpts.EmitGcovNotes) 1433b0f4066SDimitry Andric DebugInfo = new CGDebugInfo(*this); 1442754fe60SDimitry Andric 1452754fe60SDimitry Andric Block.GlobalUniqueCount = 0; 1462754fe60SDimitry Andric 1470623d748SDimitry Andric if (C.getLangOpts().ObjC1) 1480623d748SDimitry Andric ObjCData = new ObjCEntrypoints(); 14959d1ed5bSDimitry Andric 15059d1ed5bSDimitry Andric if (!CodeGenOpts.InstrProfileInput.empty()) { 15133956c43SDimitry Andric auto ReaderOrErr = 15233956c43SDimitry Andric llvm::IndexedInstrProfReader::create(CodeGenOpts.InstrProfileInput); 15333956c43SDimitry Andric if (std::error_code EC = ReaderOrErr.getError()) { 15459d1ed5bSDimitry Andric unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 1553dac3a9bSDimitry Andric "Could not read profile %0: %1"); 1563dac3a9bSDimitry Andric getDiags().Report(DiagID) << CodeGenOpts.InstrProfileInput 1573dac3a9bSDimitry Andric << EC.message(); 15833956c43SDimitry Andric } else 15933956c43SDimitry Andric PGOReader = std::move(ReaderOrErr.get()); 16059d1ed5bSDimitry Andric } 16139d628a0SDimitry Andric 16239d628a0SDimitry Andric // If coverage mapping generation is enabled, create the 16339d628a0SDimitry Andric // CoverageMappingModuleGen object. 16439d628a0SDimitry Andric if (CodeGenOpts.CoverageMapping) 16539d628a0SDimitry Andric CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 166f22ef01cSRoman Divacky } 167f22ef01cSRoman Divacky 168f22ef01cSRoman Divacky CodeGenModule::~CodeGenModule() { 1696122f3e6SDimitry Andric delete ObjCRuntime; 1706122f3e6SDimitry Andric delete OpenCLRuntime; 17159d1ed5bSDimitry Andric delete OpenMPRuntime; 1726122f3e6SDimitry Andric delete CUDARuntime; 1736122f3e6SDimitry Andric delete TheTargetCodeGenInfo; 1742754fe60SDimitry Andric delete TBAA; 175f22ef01cSRoman Divacky delete DebugInfo; 1760623d748SDimitry Andric delete ObjCData; 177f22ef01cSRoman Divacky } 178f22ef01cSRoman Divacky 179f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() { 1807ae0e2c9SDimitry Andric // This is just isGNUFamily(), but we want to force implementors of 1817ae0e2c9SDimitry Andric // new ABIs to decide how best to do this. 1827ae0e2c9SDimitry Andric switch (LangOpts.ObjCRuntime.getKind()) { 1837ae0e2c9SDimitry Andric case ObjCRuntime::GNUstep: 1847ae0e2c9SDimitry Andric case ObjCRuntime::GCC: 1857ae0e2c9SDimitry Andric case ObjCRuntime::ObjFW: 1866122f3e6SDimitry Andric ObjCRuntime = CreateGNUObjCRuntime(*this); 1877ae0e2c9SDimitry Andric return; 1887ae0e2c9SDimitry Andric 1897ae0e2c9SDimitry Andric case ObjCRuntime::FragileMacOSX: 1907ae0e2c9SDimitry Andric case ObjCRuntime::MacOSX: 1917ae0e2c9SDimitry Andric case ObjCRuntime::iOS: 1920623d748SDimitry Andric case ObjCRuntime::WatchOS: 1936122f3e6SDimitry Andric ObjCRuntime = CreateMacObjCRuntime(*this); 1947ae0e2c9SDimitry Andric return; 1957ae0e2c9SDimitry Andric } 1967ae0e2c9SDimitry Andric llvm_unreachable("bad runtime kind"); 1976122f3e6SDimitry Andric } 1986122f3e6SDimitry Andric 1996122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() { 2006122f3e6SDimitry Andric OpenCLRuntime = new CGOpenCLRuntime(*this); 2016122f3e6SDimitry Andric } 2026122f3e6SDimitry Andric 20359d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() { 20459d1ed5bSDimitry Andric OpenMPRuntime = new CGOpenMPRuntime(*this); 20559d1ed5bSDimitry Andric } 20659d1ed5bSDimitry Andric 2076122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() { 2086122f3e6SDimitry Andric CUDARuntime = CreateNVCUDARuntime(*this); 209f22ef01cSRoman Divacky } 210f22ef01cSRoman Divacky 21139d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 21239d628a0SDimitry Andric Replacements[Name] = C; 21339d628a0SDimitry Andric } 21439d628a0SDimitry Andric 215f785676fSDimitry Andric void CodeGenModule::applyReplacements() { 2168f0fd8f6SDimitry Andric for (auto &I : Replacements) { 2178f0fd8f6SDimitry Andric StringRef MangledName = I.first(); 2188f0fd8f6SDimitry Andric llvm::Constant *Replacement = I.second; 219f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 220f785676fSDimitry Andric if (!Entry) 221f785676fSDimitry Andric continue; 22259d1ed5bSDimitry Andric auto *OldF = cast<llvm::Function>(Entry); 22359d1ed5bSDimitry Andric auto *NewF = dyn_cast<llvm::Function>(Replacement); 224f785676fSDimitry Andric if (!NewF) { 22559d1ed5bSDimitry Andric if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 22659d1ed5bSDimitry Andric NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 22759d1ed5bSDimitry Andric } else { 22859d1ed5bSDimitry Andric auto *CE = cast<llvm::ConstantExpr>(Replacement); 229f785676fSDimitry Andric assert(CE->getOpcode() == llvm::Instruction::BitCast || 230f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::GetElementPtr); 231f785676fSDimitry Andric NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 232f785676fSDimitry Andric } 23359d1ed5bSDimitry Andric } 234f785676fSDimitry Andric 235f785676fSDimitry Andric // Replace old with new, but keep the old order. 236f785676fSDimitry Andric OldF->replaceAllUsesWith(Replacement); 237f785676fSDimitry Andric if (NewF) { 238f785676fSDimitry Andric NewF->removeFromParent(); 2390623d748SDimitry Andric OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 2400623d748SDimitry Andric NewF); 241f785676fSDimitry Andric } 242f785676fSDimitry Andric OldF->eraseFromParent(); 243f785676fSDimitry Andric } 244f785676fSDimitry Andric } 245f785676fSDimitry Andric 2460623d748SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 2470623d748SDimitry Andric GlobalValReplacements.push_back(std::make_pair(GV, C)); 2480623d748SDimitry Andric } 2490623d748SDimitry Andric 2500623d748SDimitry Andric void CodeGenModule::applyGlobalValReplacements() { 2510623d748SDimitry Andric for (auto &I : GlobalValReplacements) { 2520623d748SDimitry Andric llvm::GlobalValue *GV = I.first; 2530623d748SDimitry Andric llvm::Constant *C = I.second; 2540623d748SDimitry Andric 2550623d748SDimitry Andric GV->replaceAllUsesWith(C); 2560623d748SDimitry Andric GV->eraseFromParent(); 2570623d748SDimitry Andric } 2580623d748SDimitry Andric } 2590623d748SDimitry Andric 26059d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a 26159d1ed5bSDimitry Andric // linear structure. 26259d1ed5bSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) { 26359d1ed5bSDimitry Andric llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited; 26459d1ed5bSDimitry Andric const llvm::Constant *C = &GA; 26559d1ed5bSDimitry Andric for (;;) { 26659d1ed5bSDimitry Andric C = C->stripPointerCasts(); 26759d1ed5bSDimitry Andric if (auto *GO = dyn_cast<llvm::GlobalObject>(C)) 26859d1ed5bSDimitry Andric return GO; 26959d1ed5bSDimitry Andric // stripPointerCasts will not walk over weak aliases. 27059d1ed5bSDimitry Andric auto *GA2 = dyn_cast<llvm::GlobalAlias>(C); 27159d1ed5bSDimitry Andric if (!GA2) 27259d1ed5bSDimitry Andric return nullptr; 27339d628a0SDimitry Andric if (!Visited.insert(GA2).second) 27459d1ed5bSDimitry Andric return nullptr; 27559d1ed5bSDimitry Andric C = GA2->getAliasee(); 27659d1ed5bSDimitry Andric } 27759d1ed5bSDimitry Andric } 27859d1ed5bSDimitry Andric 279f785676fSDimitry Andric void CodeGenModule::checkAliases() { 28059d1ed5bSDimitry Andric // Check if the constructed aliases are well formed. It is really unfortunate 28159d1ed5bSDimitry Andric // that we have to do this in CodeGen, but we only construct mangled names 28259d1ed5bSDimitry Andric // and aliases during codegen. 283f785676fSDimitry Andric bool Error = false; 28459d1ed5bSDimitry Andric DiagnosticsEngine &Diags = getDiags(); 2858f0fd8f6SDimitry Andric for (const GlobalDecl &GD : Aliases) { 28659d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 287f785676fSDimitry Andric const AliasAttr *AA = D->getAttr<AliasAttr>(); 288f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 289f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 29059d1ed5bSDimitry Andric auto *Alias = cast<llvm::GlobalAlias>(Entry); 29159d1ed5bSDimitry Andric const llvm::GlobalValue *GV = getAliasedGlobal(*Alias); 29259d1ed5bSDimitry Andric if (!GV) { 293f785676fSDimitry Andric Error = true; 29459d1ed5bSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 29559d1ed5bSDimitry Andric } else if (GV->isDeclaration()) { 296f785676fSDimitry Andric Error = true; 29759d1ed5bSDimitry Andric Diags.Report(AA->getLocation(), diag::err_alias_to_undefined); 29859d1ed5bSDimitry Andric } 29959d1ed5bSDimitry Andric 30059d1ed5bSDimitry Andric llvm::Constant *Aliasee = Alias->getAliasee(); 30159d1ed5bSDimitry Andric llvm::GlobalValue *AliaseeGV; 30259d1ed5bSDimitry Andric if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 30359d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 30459d1ed5bSDimitry Andric else 30559d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 30659d1ed5bSDimitry Andric 30759d1ed5bSDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 30859d1ed5bSDimitry Andric StringRef AliasSection = SA->getName(); 30959d1ed5bSDimitry Andric if (AliasSection != AliaseeGV->getSection()) 31059d1ed5bSDimitry Andric Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 31159d1ed5bSDimitry Andric << AliasSection; 31259d1ed5bSDimitry Andric } 31359d1ed5bSDimitry Andric 31459d1ed5bSDimitry Andric // We have to handle alias to weak aliases in here. LLVM itself disallows 31559d1ed5bSDimitry Andric // this since the object semantics would not match the IL one. For 31659d1ed5bSDimitry Andric // compatibility with gcc we implement it by just pointing the alias 31759d1ed5bSDimitry Andric // to its aliasee's aliasee. We also warn, since the user is probably 31859d1ed5bSDimitry Andric // expecting the link to be weak. 31959d1ed5bSDimitry Andric if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) { 32059d1ed5bSDimitry Andric if (GA->mayBeOverridden()) { 32159d1ed5bSDimitry Andric Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias) 32259d1ed5bSDimitry Andric << GV->getName() << GA->getName(); 32359d1ed5bSDimitry Andric Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 32459d1ed5bSDimitry Andric GA->getAliasee(), Alias->getType()); 32559d1ed5bSDimitry Andric Alias->setAliasee(Aliasee); 32659d1ed5bSDimitry Andric } 327f785676fSDimitry Andric } 328f785676fSDimitry Andric } 329f785676fSDimitry Andric if (!Error) 330f785676fSDimitry Andric return; 331f785676fSDimitry Andric 3328f0fd8f6SDimitry Andric for (const GlobalDecl &GD : Aliases) { 333f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 334f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 33559d1ed5bSDimitry Andric auto *Alias = cast<llvm::GlobalAlias>(Entry); 336f785676fSDimitry Andric Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 337f785676fSDimitry Andric Alias->eraseFromParent(); 338f785676fSDimitry Andric } 339f785676fSDimitry Andric } 340f785676fSDimitry Andric 34159d1ed5bSDimitry Andric void CodeGenModule::clear() { 34259d1ed5bSDimitry Andric DeferredDeclsToEmit.clear(); 34333956c43SDimitry Andric if (OpenMPRuntime) 34433956c43SDimitry Andric OpenMPRuntime->clear(); 34559d1ed5bSDimitry Andric } 34659d1ed5bSDimitry Andric 34759d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 34859d1ed5bSDimitry Andric StringRef MainFile) { 34959d1ed5bSDimitry Andric if (!hasDiagnostics()) 35059d1ed5bSDimitry Andric return; 35159d1ed5bSDimitry Andric if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 35259d1ed5bSDimitry Andric if (MainFile.empty()) 35359d1ed5bSDimitry Andric MainFile = "<stdin>"; 35459d1ed5bSDimitry Andric Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 35559d1ed5bSDimitry Andric } else 35659d1ed5bSDimitry Andric Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing 35759d1ed5bSDimitry Andric << Mismatched; 35859d1ed5bSDimitry Andric } 35959d1ed5bSDimitry Andric 360f22ef01cSRoman Divacky void CodeGenModule::Release() { 361f22ef01cSRoman Divacky EmitDeferred(); 3620623d748SDimitry Andric applyGlobalValReplacements(); 363f785676fSDimitry Andric applyReplacements(); 364f785676fSDimitry Andric checkAliases(); 365f22ef01cSRoman Divacky EmitCXXGlobalInitFunc(); 366f22ef01cSRoman Divacky EmitCXXGlobalDtorFunc(); 367284c1978SDimitry Andric EmitCXXThreadLocalInitFunc(); 3686122f3e6SDimitry Andric if (ObjCRuntime) 3696122f3e6SDimitry Andric if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 370f22ef01cSRoman Divacky AddGlobalCtor(ObjCInitFunction); 37133956c43SDimitry Andric if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice && 37233956c43SDimitry Andric CUDARuntime) { 37333956c43SDimitry Andric if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction()) 37433956c43SDimitry Andric AddGlobalCtor(CudaCtorFunction); 37533956c43SDimitry Andric if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction()) 37633956c43SDimitry Andric AddGlobalDtor(CudaDtorFunction); 37733956c43SDimitry Andric } 3780623d748SDimitry Andric if (PGOReader) { 3790623d748SDimitry Andric getModule().setMaximumFunctionCount(PGOReader->getMaximumFunctionCount()); 3800623d748SDimitry Andric if (PGOStats.hasDiagnostics()) 38159d1ed5bSDimitry Andric PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 3820623d748SDimitry Andric } 383f22ef01cSRoman Divacky EmitCtorList(GlobalCtors, "llvm.global_ctors"); 384f22ef01cSRoman Divacky EmitCtorList(GlobalDtors, "llvm.global_dtors"); 3856122f3e6SDimitry Andric EmitGlobalAnnotations(); 386284c1978SDimitry Andric EmitStaticExternCAliases(); 38739d628a0SDimitry Andric EmitDeferredUnusedCoverageMappings(); 38839d628a0SDimitry Andric if (CoverageMapping) 38939d628a0SDimitry Andric CoverageMapping->emit(); 39059d1ed5bSDimitry Andric emitLLVMUsed(); 391ffd1746dSEd Schouten 392f785676fSDimitry Andric if (CodeGenOpts.Autolink && 393f785676fSDimitry Andric (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 394139f7f9bSDimitry Andric EmitModuleLinkOptions(); 395139f7f9bSDimitry Andric } 3960623d748SDimitry Andric if (CodeGenOpts.DwarfVersion) { 397f785676fSDimitry Andric // We actually want the latest version when there are conflicts. 398f785676fSDimitry Andric // We can change from Warning to Latest if such mode is supported. 399f785676fSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 400f785676fSDimitry Andric CodeGenOpts.DwarfVersion); 4010623d748SDimitry Andric } 4020623d748SDimitry Andric if (CodeGenOpts.EmitCodeView) { 4030623d748SDimitry Andric // Indicate that we want CodeView in the metadata. 4040623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 4050623d748SDimitry Andric } 4060623d748SDimitry Andric if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 4070623d748SDimitry Andric // We don't support LTO with 2 with different StrictVTablePointers 4080623d748SDimitry Andric // FIXME: we could support it by stripping all the information introduced 4090623d748SDimitry Andric // by StrictVTablePointers. 4100623d748SDimitry Andric 4110623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 4120623d748SDimitry Andric 4130623d748SDimitry Andric llvm::Metadata *Ops[2] = { 4140623d748SDimitry Andric llvm::MDString::get(VMContext, "StrictVTablePointers"), 4150623d748SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 4160623d748SDimitry Andric llvm::Type::getInt32Ty(VMContext), 1))}; 4170623d748SDimitry Andric 4180623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Require, 4190623d748SDimitry Andric "StrictVTablePointersRequirement", 4200623d748SDimitry Andric llvm::MDNode::get(VMContext, Ops)); 4210623d748SDimitry Andric } 422f785676fSDimitry Andric if (DebugInfo) 42359d1ed5bSDimitry Andric // We support a single version in the linked module. The LLVM 42459d1ed5bSDimitry Andric // parser will drop debug info with a different version number 42559d1ed5bSDimitry Andric // (and warn about it, too). 42659d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 427f785676fSDimitry Andric llvm::DEBUG_METADATA_VERSION); 428139f7f9bSDimitry Andric 42959d1ed5bSDimitry Andric // We need to record the widths of enums and wchar_t, so that we can generate 43059d1ed5bSDimitry Andric // the correct build attributes in the ARM backend. 43159d1ed5bSDimitry Andric llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 43259d1ed5bSDimitry Andric if ( Arch == llvm::Triple::arm 43359d1ed5bSDimitry Andric || Arch == llvm::Triple::armeb 43459d1ed5bSDimitry Andric || Arch == llvm::Triple::thumb 43559d1ed5bSDimitry Andric || Arch == llvm::Triple::thumbeb) { 43659d1ed5bSDimitry Andric // Width of wchar_t in bytes 43759d1ed5bSDimitry Andric uint64_t WCharWidth = 43859d1ed5bSDimitry Andric Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 43959d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 44059d1ed5bSDimitry Andric 44159d1ed5bSDimitry Andric // The minimum width of an enum in bytes 44259d1ed5bSDimitry Andric uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 44359d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 44459d1ed5bSDimitry Andric } 44559d1ed5bSDimitry Andric 4460623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 4470623d748SDimitry Andric // Indicate that we want cross-DSO control flow integrity checks. 4480623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 4490623d748SDimitry Andric } 4500623d748SDimitry Andric 45139d628a0SDimitry Andric if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 45239d628a0SDimitry Andric llvm::PICLevel::Level PL = llvm::PICLevel::Default; 45339d628a0SDimitry Andric switch (PLevel) { 45439d628a0SDimitry Andric case 0: break; 45539d628a0SDimitry Andric case 1: PL = llvm::PICLevel::Small; break; 45639d628a0SDimitry Andric case 2: PL = llvm::PICLevel::Large; break; 45739d628a0SDimitry Andric default: llvm_unreachable("Invalid PIC Level"); 45839d628a0SDimitry Andric } 45939d628a0SDimitry Andric 46039d628a0SDimitry Andric getModule().setPICLevel(PL); 46139d628a0SDimitry Andric } 46239d628a0SDimitry Andric 4632754fe60SDimitry Andric SimplifyPersonality(); 4642754fe60SDimitry Andric 465ffd1746dSEd Schouten if (getCodeGenOpts().EmitDeclMetadata) 466ffd1746dSEd Schouten EmitDeclMetadata(); 467bd5abe19SDimitry Andric 468bd5abe19SDimitry Andric if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 469bd5abe19SDimitry Andric EmitCoverageFile(); 4706122f3e6SDimitry Andric 4716122f3e6SDimitry Andric if (DebugInfo) 4726122f3e6SDimitry Andric DebugInfo->finalize(); 473f785676fSDimitry Andric 474f785676fSDimitry Andric EmitVersionIdentMetadata(); 47559d1ed5bSDimitry Andric 47659d1ed5bSDimitry Andric EmitTargetMetadata(); 477f22ef01cSRoman Divacky } 478f22ef01cSRoman Divacky 4793b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 4803b0f4066SDimitry Andric // Make sure that this type is translated. 4813b0f4066SDimitry Andric Types.UpdateCompletedType(TD); 4823b0f4066SDimitry Andric } 4833b0f4066SDimitry Andric 4842754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 4852754fe60SDimitry Andric if (!TBAA) 48659d1ed5bSDimitry Andric return nullptr; 4872754fe60SDimitry Andric return TBAA->getTBAAInfo(QTy); 4882754fe60SDimitry Andric } 4892754fe60SDimitry Andric 490dff0c46cSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 491dff0c46cSDimitry Andric if (!TBAA) 49259d1ed5bSDimitry Andric return nullptr; 493dff0c46cSDimitry Andric return TBAA->getTBAAInfoForVTablePtr(); 494dff0c46cSDimitry Andric } 495dff0c46cSDimitry Andric 4963861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 4973861d79fSDimitry Andric if (!TBAA) 49859d1ed5bSDimitry Andric return nullptr; 4993861d79fSDimitry Andric return TBAA->getTBAAStructInfo(QTy); 5003861d79fSDimitry Andric } 5013861d79fSDimitry Andric 502139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy, 503139f7f9bSDimitry Andric llvm::MDNode *AccessN, 504139f7f9bSDimitry Andric uint64_t O) { 505139f7f9bSDimitry Andric if (!TBAA) 50659d1ed5bSDimitry Andric return nullptr; 507139f7f9bSDimitry Andric return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O); 508139f7f9bSDimitry Andric } 509139f7f9bSDimitry Andric 510f785676fSDimitry Andric /// Decorate the instruction with a TBAA tag. For both scalar TBAA 511f785676fSDimitry Andric /// and struct-path aware TBAA, the tag has the same format: 512f785676fSDimitry Andric /// base type, access type and offset. 513284c1978SDimitry Andric /// When ConvertTypeToTag is true, we create a tag based on the scalar type. 5140623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 515284c1978SDimitry Andric llvm::MDNode *TBAAInfo, 516284c1978SDimitry Andric bool ConvertTypeToTag) { 517f785676fSDimitry Andric if (ConvertTypeToTag && TBAA) 518284c1978SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, 519284c1978SDimitry Andric TBAA->getTBAAScalarTagInfo(TBAAInfo)); 520284c1978SDimitry Andric else 5212754fe60SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 5222754fe60SDimitry Andric } 5232754fe60SDimitry Andric 5240623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup( 5250623d748SDimitry Andric llvm::Instruction *I, const CXXRecordDecl *RD) { 5260623d748SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 5270623d748SDimitry Andric auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD); 5280623d748SDimitry Andric // Check if we have to wrap MDString in MDNode. 5290623d748SDimitry Andric if (!MetaDataNode) 5300623d748SDimitry Andric MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD); 5310623d748SDimitry Andric I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode); 5320623d748SDimitry Andric } 5330623d748SDimitry Andric 53459d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) { 53559d1ed5bSDimitry Andric unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 53659d1ed5bSDimitry Andric getDiags().Report(Context.getFullLoc(loc), diagID) << message; 537f22ef01cSRoman Divacky } 538f22ef01cSRoman Divacky 539f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 540f22ef01cSRoman Divacky /// specified stmt yet. 541f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 5426122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 543f22ef01cSRoman Divacky "cannot compile this %0 yet"); 544f22ef01cSRoman Divacky std::string Msg = Type; 545f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 546f22ef01cSRoman Divacky << Msg << S->getSourceRange(); 547f22ef01cSRoman Divacky } 548f22ef01cSRoman Divacky 549f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 550f22ef01cSRoman Divacky /// specified decl yet. 551f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 5526122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 553f22ef01cSRoman Divacky "cannot compile this %0 yet"); 554f22ef01cSRoman Divacky std::string Msg = Type; 555f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 556f22ef01cSRoman Divacky } 557f22ef01cSRoman Divacky 55817a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 55917a519f9SDimitry Andric return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 56017a519f9SDimitry Andric } 56117a519f9SDimitry Andric 562f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 5632754fe60SDimitry Andric const NamedDecl *D) const { 564f22ef01cSRoman Divacky // Internal definitions always have default visibility. 565f22ef01cSRoman Divacky if (GV->hasLocalLinkage()) { 566f22ef01cSRoman Divacky GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 567f22ef01cSRoman Divacky return; 568f22ef01cSRoman Divacky } 569f22ef01cSRoman Divacky 5702754fe60SDimitry Andric // Set visibility for definitions. 571139f7f9bSDimitry Andric LinkageInfo LV = D->getLinkageAndVisibility(); 572139f7f9bSDimitry Andric if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 573139f7f9bSDimitry Andric GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 574f22ef01cSRoman Divacky } 575f22ef01cSRoman Divacky 5767ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 5777ae0e2c9SDimitry Andric return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 5787ae0e2c9SDimitry Andric .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 5797ae0e2c9SDimitry Andric .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 5807ae0e2c9SDimitry Andric .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 5817ae0e2c9SDimitry Andric .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 5827ae0e2c9SDimitry Andric } 5837ae0e2c9SDimitry Andric 5847ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 5857ae0e2c9SDimitry Andric CodeGenOptions::TLSModel M) { 5867ae0e2c9SDimitry Andric switch (M) { 5877ae0e2c9SDimitry Andric case CodeGenOptions::GeneralDynamicTLSModel: 5887ae0e2c9SDimitry Andric return llvm::GlobalVariable::GeneralDynamicTLSModel; 5897ae0e2c9SDimitry Andric case CodeGenOptions::LocalDynamicTLSModel: 5907ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalDynamicTLSModel; 5917ae0e2c9SDimitry Andric case CodeGenOptions::InitialExecTLSModel: 5927ae0e2c9SDimitry Andric return llvm::GlobalVariable::InitialExecTLSModel; 5937ae0e2c9SDimitry Andric case CodeGenOptions::LocalExecTLSModel: 5947ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalExecTLSModel; 5957ae0e2c9SDimitry Andric } 5967ae0e2c9SDimitry Andric llvm_unreachable("Invalid TLS model!"); 5977ae0e2c9SDimitry Andric } 5987ae0e2c9SDimitry Andric 59939d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 600284c1978SDimitry Andric assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 6017ae0e2c9SDimitry Andric 60239d628a0SDimitry Andric llvm::GlobalValue::ThreadLocalMode TLM; 6033861d79fSDimitry Andric TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 6047ae0e2c9SDimitry Andric 6057ae0e2c9SDimitry Andric // Override the TLS model if it is explicitly specified. 60659d1ed5bSDimitry Andric if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 6077ae0e2c9SDimitry Andric TLM = GetLLVMTLSModel(Attr->getModel()); 6087ae0e2c9SDimitry Andric } 6097ae0e2c9SDimitry Andric 6107ae0e2c9SDimitry Andric GV->setThreadLocalMode(TLM); 6117ae0e2c9SDimitry Andric } 6127ae0e2c9SDimitry Andric 6136122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 61459d1ed5bSDimitry Andric StringRef &FoundStr = MangledDeclNames[GD.getCanonicalDecl()]; 61559d1ed5bSDimitry Andric if (!FoundStr.empty()) 61659d1ed5bSDimitry Andric return FoundStr; 617f22ef01cSRoman Divacky 61859d1ed5bSDimitry Andric const auto *ND = cast<NamedDecl>(GD.getDecl()); 619dff0c46cSDimitry Andric SmallString<256> Buffer; 62059d1ed5bSDimitry Andric StringRef Str; 62159d1ed5bSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 6222754fe60SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 62359d1ed5bSDimitry Andric if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) 6242754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 62559d1ed5bSDimitry Andric else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) 6262754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 627ffd1746dSEd Schouten else 6282754fe60SDimitry Andric getCXXABI().getMangleContext().mangleName(ND, Out); 62959d1ed5bSDimitry Andric Str = Out.str(); 63059d1ed5bSDimitry Andric } else { 63159d1ed5bSDimitry Andric IdentifierInfo *II = ND->getIdentifier(); 63259d1ed5bSDimitry Andric assert(II && "Attempt to mangle unnamed decl."); 63359d1ed5bSDimitry Andric Str = II->getName(); 634ffd1746dSEd Schouten } 635ffd1746dSEd Schouten 63639d628a0SDimitry Andric // Keep the first result in the case of a mangling collision. 63739d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Str, GD)); 63839d628a0SDimitry Andric return FoundStr = Result.first->first(); 63959d1ed5bSDimitry Andric } 64059d1ed5bSDimitry Andric 64159d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 642ffd1746dSEd Schouten const BlockDecl *BD) { 6432754fe60SDimitry Andric MangleContext &MangleCtx = getCXXABI().getMangleContext(); 6442754fe60SDimitry Andric const Decl *D = GD.getDecl(); 64559d1ed5bSDimitry Andric 64659d1ed5bSDimitry Andric SmallString<256> Buffer; 64759d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(Buffer); 64859d1ed5bSDimitry Andric if (!D) 6497ae0e2c9SDimitry Andric MangleCtx.mangleGlobalBlock(BD, 6507ae0e2c9SDimitry Andric dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 65159d1ed5bSDimitry Andric else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 6522754fe60SDimitry Andric MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 65359d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 6542754fe60SDimitry Andric MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 6552754fe60SDimitry Andric else 6562754fe60SDimitry Andric MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 65759d1ed5bSDimitry Andric 65839d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 65939d628a0SDimitry Andric return Result.first->first(); 660f22ef01cSRoman Divacky } 661f22ef01cSRoman Divacky 6626122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 663f22ef01cSRoman Divacky return getModule().getNamedValue(Name); 664f22ef01cSRoman Divacky } 665f22ef01cSRoman Divacky 666f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before 667f22ef01cSRoman Divacky /// main() runs. 66859d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 66959d1ed5bSDimitry Andric llvm::Constant *AssociatedData) { 670f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 67159d1ed5bSDimitry Andric GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 672f22ef01cSRoman Divacky } 673f22ef01cSRoman Divacky 674f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called 675f22ef01cSRoman Divacky /// when the module is unloaded. 676f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) { 677f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 67859d1ed5bSDimitry Andric GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 679f22ef01cSRoman Divacky } 680f22ef01cSRoman Divacky 681f22ef01cSRoman Divacky void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 682f22ef01cSRoman Divacky // Ctor function type is void()*. 683bd5abe19SDimitry Andric llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 684f22ef01cSRoman Divacky llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 685f22ef01cSRoman Divacky 68659d1ed5bSDimitry Andric // Get the type of a ctor entry, { i32, void ()*, i8* }. 68759d1ed5bSDimitry Andric llvm::StructType *CtorStructTy = llvm::StructType::get( 68839d628a0SDimitry Andric Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr); 689f22ef01cSRoman Divacky 690f22ef01cSRoman Divacky // Construct the constructor and destructor arrays. 691dff0c46cSDimitry Andric SmallVector<llvm::Constant *, 8> Ctors; 6928f0fd8f6SDimitry Andric for (const auto &I : Fns) { 693dff0c46cSDimitry Andric llvm::Constant *S[] = { 6948f0fd8f6SDimitry Andric llvm::ConstantInt::get(Int32Ty, I.Priority, false), 6958f0fd8f6SDimitry Andric llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy), 6968f0fd8f6SDimitry Andric (I.AssociatedData 6978f0fd8f6SDimitry Andric ? llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy) 6988f0fd8f6SDimitry Andric : llvm::Constant::getNullValue(VoidPtrTy))}; 699f22ef01cSRoman Divacky Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 700f22ef01cSRoman Divacky } 701f22ef01cSRoman Divacky 702f22ef01cSRoman Divacky if (!Ctors.empty()) { 703f22ef01cSRoman Divacky llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 704f22ef01cSRoman Divacky new llvm::GlobalVariable(TheModule, AT, false, 705f22ef01cSRoman Divacky llvm::GlobalValue::AppendingLinkage, 706f22ef01cSRoman Divacky llvm::ConstantArray::get(AT, Ctors), 707f22ef01cSRoman Divacky GlobalName); 708f22ef01cSRoman Divacky } 709f22ef01cSRoman Divacky } 710f22ef01cSRoman Divacky 711f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes 712f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 71359d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 714f785676fSDimitry Andric 715e580952dSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 716f22ef01cSRoman Divacky 71759d1ed5bSDimitry Andric if (isa<CXXDestructorDecl>(D) && 71859d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 71959d1ed5bSDimitry Andric GD.getDtorType())) { 72059d1ed5bSDimitry Andric // Destructor variants in the Microsoft C++ ABI are always internal or 72159d1ed5bSDimitry Andric // linkonce_odr thunks emitted on an as-needed basis. 72259d1ed5bSDimitry Andric return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage 72359d1ed5bSDimitry Andric : llvm::GlobalValue::LinkOnceODRLinkage; 724f22ef01cSRoman Divacky } 725f22ef01cSRoman Divacky 72659d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false); 72759d1ed5bSDimitry Andric } 728f22ef01cSRoman Divacky 72997bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) { 73097bc6c73SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 73197bc6c73SDimitry Andric 73297bc6c73SDimitry Andric if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) { 73397bc6c73SDimitry Andric if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) { 73497bc6c73SDimitry Andric // Don't dllexport/import destructor thunks. 73597bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 73697bc6c73SDimitry Andric return; 73797bc6c73SDimitry Andric } 73897bc6c73SDimitry Andric } 73997bc6c73SDimitry Andric 74097bc6c73SDimitry Andric if (FD->hasAttr<DLLImportAttr>()) 74197bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 74297bc6c73SDimitry Andric else if (FD->hasAttr<DLLExportAttr>()) 74397bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 74497bc6c73SDimitry Andric else 74597bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 74697bc6c73SDimitry Andric } 74797bc6c73SDimitry Andric 7480623d748SDimitry Andric llvm::ConstantInt * 7490623d748SDimitry Andric CodeGenModule::CreateCfiIdForTypeMetadata(llvm::Metadata *MD) { 7500623d748SDimitry Andric llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 7510623d748SDimitry Andric if (!MDS) return nullptr; 7520623d748SDimitry Andric 7530623d748SDimitry Andric llvm::MD5 md5; 7540623d748SDimitry Andric llvm::MD5::MD5Result result; 7550623d748SDimitry Andric md5.update(MDS->getString()); 7560623d748SDimitry Andric md5.final(result); 7570623d748SDimitry Andric uint64_t id = 0; 7580623d748SDimitry Andric for (int i = 0; i < 8; ++i) 7590623d748SDimitry Andric id |= static_cast<uint64_t>(result[i]) << (i * 8); 7600623d748SDimitry Andric return llvm::ConstantInt::get(Int64Ty, id); 7610623d748SDimitry Andric } 7620623d748SDimitry Andric 76359d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D, 76459d1ed5bSDimitry Andric llvm::Function *F) { 76559d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 766f22ef01cSRoman Divacky } 767f22ef01cSRoman Divacky 768f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 769f22ef01cSRoman Divacky const CGFunctionInfo &Info, 770f22ef01cSRoman Divacky llvm::Function *F) { 771f22ef01cSRoman Divacky unsigned CallingConv; 772f22ef01cSRoman Divacky AttributeListType AttributeList; 773139f7f9bSDimitry Andric ConstructAttributeList(Info, D, AttributeList, CallingConv, false); 774139f7f9bSDimitry Andric F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList)); 775f22ef01cSRoman Divacky F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 776f22ef01cSRoman Divacky } 777f22ef01cSRoman Divacky 7786122f3e6SDimitry Andric /// Determines whether the language options require us to model 7796122f3e6SDimitry Andric /// unwind exceptions. We treat -fexceptions as mandating this 7806122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions 7816122f3e6SDimitry Andric /// enabled. This means, for example, that C with -fexceptions 7826122f3e6SDimitry Andric /// enables this. 783dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) { 7846122f3e6SDimitry Andric // If exceptions are completely disabled, obviously this is false. 785dff0c46cSDimitry Andric if (!LangOpts.Exceptions) return false; 7866122f3e6SDimitry Andric 7876122f3e6SDimitry Andric // If C++ exceptions are enabled, this is true. 788dff0c46cSDimitry Andric if (LangOpts.CXXExceptions) return true; 7896122f3e6SDimitry Andric 7906122f3e6SDimitry Andric // If ObjC exceptions are enabled, this depends on the ABI. 791dff0c46cSDimitry Andric if (LangOpts.ObjCExceptions) { 7927ae0e2c9SDimitry Andric return LangOpts.ObjCRuntime.hasUnwindExceptions(); 7936122f3e6SDimitry Andric } 7946122f3e6SDimitry Andric 7956122f3e6SDimitry Andric return true; 7966122f3e6SDimitry Andric } 7976122f3e6SDimitry Andric 798f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 799f22ef01cSRoman Divacky llvm::Function *F) { 800f785676fSDimitry Andric llvm::AttrBuilder B; 801f785676fSDimitry Andric 802bd5abe19SDimitry Andric if (CodeGenOpts.UnwindTables) 803f785676fSDimitry Andric B.addAttribute(llvm::Attribute::UWTable); 804bd5abe19SDimitry Andric 805dff0c46cSDimitry Andric if (!hasUnwindExceptions(LangOpts)) 806f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoUnwind); 807f22ef01cSRoman Divacky 8080623d748SDimitry Andric if (LangOpts.getStackProtector() == LangOptions::SSPOn) 8090623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtect); 8100623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 8110623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 8120623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 8130623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectReq); 8140623d748SDimitry Andric 8150623d748SDimitry Andric if (!D) { 8160623d748SDimitry Andric F->addAttributes(llvm::AttributeSet::FunctionIndex, 8170623d748SDimitry Andric llvm::AttributeSet::get( 8180623d748SDimitry Andric F->getContext(), 8190623d748SDimitry Andric llvm::AttributeSet::FunctionIndex, B)); 8200623d748SDimitry Andric return; 8210623d748SDimitry Andric } 8220623d748SDimitry Andric 8236122f3e6SDimitry Andric if (D->hasAttr<NakedAttr>()) { 8246122f3e6SDimitry Andric // Naked implies noinline: we should not be inlining such functions. 825f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Naked); 826f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 82759d1ed5bSDimitry Andric } else if (D->hasAttr<NoDuplicateAttr>()) { 82859d1ed5bSDimitry Andric B.addAttribute(llvm::Attribute::NoDuplicate); 829f785676fSDimitry Andric } else if (D->hasAttr<NoInlineAttr>()) { 830f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 83159d1ed5bSDimitry Andric } else if (D->hasAttr<AlwaysInlineAttr>() && 832f785676fSDimitry Andric !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex, 833f785676fSDimitry Andric llvm::Attribute::NoInline)) { 834f785676fSDimitry Andric // (noinline wins over always_inline, and we can't specify both in IR) 835f785676fSDimitry Andric B.addAttribute(llvm::Attribute::AlwaysInline); 8366122f3e6SDimitry Andric } 8372754fe60SDimitry Andric 838f785676fSDimitry Andric if (D->hasAttr<ColdAttr>()) { 83939d628a0SDimitry Andric if (!D->hasAttr<OptimizeNoneAttr>()) 840f785676fSDimitry Andric B.addAttribute(llvm::Attribute::OptimizeForSize); 841f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Cold); 842f785676fSDimitry Andric } 8433861d79fSDimitry Andric 8443861d79fSDimitry Andric if (D->hasAttr<MinSizeAttr>()) 845f785676fSDimitry Andric B.addAttribute(llvm::Attribute::MinSize); 846f22ef01cSRoman Divacky 847f785676fSDimitry Andric F->addAttributes(llvm::AttributeSet::FunctionIndex, 848f785676fSDimitry Andric llvm::AttributeSet::get( 849f785676fSDimitry Andric F->getContext(), llvm::AttributeSet::FunctionIndex, B)); 850f785676fSDimitry Andric 85139d628a0SDimitry Andric if (D->hasAttr<OptimizeNoneAttr>()) { 85239d628a0SDimitry Andric // OptimizeNone implies noinline; we should not be inlining such functions. 85339d628a0SDimitry Andric F->addFnAttr(llvm::Attribute::OptimizeNone); 85439d628a0SDimitry Andric F->addFnAttr(llvm::Attribute::NoInline); 85539d628a0SDimitry Andric 85639d628a0SDimitry Andric // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline. 8570623d748SDimitry Andric F->removeFnAttr(llvm::Attribute::OptimizeForSize); 8580623d748SDimitry Andric F->removeFnAttr(llvm::Attribute::MinSize); 85939d628a0SDimitry Andric assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 86039d628a0SDimitry Andric "OptimizeNone and AlwaysInline on same function!"); 86139d628a0SDimitry Andric 86239d628a0SDimitry Andric // Attribute 'inlinehint' has no effect on 'optnone' functions. 86339d628a0SDimitry Andric // Explicitly remove it from the set of function attributes. 86439d628a0SDimitry Andric F->removeFnAttr(llvm::Attribute::InlineHint); 86539d628a0SDimitry Andric } 86639d628a0SDimitry Andric 867f785676fSDimitry Andric if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 868f785676fSDimitry Andric F->setUnnamedAddr(true); 86959d1ed5bSDimitry Andric else if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) 870f785676fSDimitry Andric if (MD->isVirtual()) 871f785676fSDimitry Andric F->setUnnamedAddr(true); 872f785676fSDimitry Andric 873e580952dSDimitry Andric unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 874e580952dSDimitry Andric if (alignment) 875e580952dSDimitry Andric F->setAlignment(alignment); 876e580952dSDimitry Andric 8770623d748SDimitry Andric // Some C++ ABIs require 2-byte alignment for member functions, in order to 8780623d748SDimitry Andric // reserve a bit for differentiating between virtual and non-virtual member 8790623d748SDimitry Andric // functions. If the current target's C++ ABI requires this and this is a 8800623d748SDimitry Andric // member function, set its alignment accordingly. 8810623d748SDimitry Andric if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 882f22ef01cSRoman Divacky if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 883f22ef01cSRoman Divacky F->setAlignment(2); 884f22ef01cSRoman Divacky } 8850623d748SDimitry Andric } 886f22ef01cSRoman Divacky 887f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D, 888f22ef01cSRoman Divacky llvm::GlobalValue *GV) { 8890623d748SDimitry Andric if (const auto *ND = dyn_cast_or_null<NamedDecl>(D)) 8902754fe60SDimitry Andric setGlobalVisibility(GV, ND); 8912754fe60SDimitry Andric else 8922754fe60SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 893f22ef01cSRoman Divacky 8940623d748SDimitry Andric if (D && D->hasAttr<UsedAttr>()) 89559d1ed5bSDimitry Andric addUsedGlobal(GV); 89659d1ed5bSDimitry Andric } 89759d1ed5bSDimitry Andric 89839d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D, 89939d628a0SDimitry Andric llvm::GlobalValue *GV) { 90039d628a0SDimitry Andric SetCommonAttributes(D, GV); 90139d628a0SDimitry Andric 90239d628a0SDimitry Andric // Process the dllexport attribute based on whether the original definition 90339d628a0SDimitry Andric // (not necessarily the aliasee) was exported. 90439d628a0SDimitry Andric if (D->hasAttr<DLLExportAttr>()) 90539d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 90639d628a0SDimitry Andric } 90739d628a0SDimitry Andric 90859d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D, 90959d1ed5bSDimitry Andric llvm::GlobalObject *GO) { 91059d1ed5bSDimitry Andric SetCommonAttributes(D, GO); 911f22ef01cSRoman Divacky 9120623d748SDimitry Andric if (D) 913f22ef01cSRoman Divacky if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 91459d1ed5bSDimitry Andric GO->setSection(SA->getName()); 915f22ef01cSRoman Divacky 91697bc6c73SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 917f22ef01cSRoman Divacky } 918f22ef01cSRoman Divacky 919f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 920f22ef01cSRoman Divacky llvm::Function *F, 921f22ef01cSRoman Divacky const CGFunctionInfo &FI) { 922f22ef01cSRoman Divacky SetLLVMFunctionAttributes(D, FI, F); 923f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, F); 924f22ef01cSRoman Divacky 925f22ef01cSRoman Divacky F->setLinkage(llvm::Function::InternalLinkage); 926f22ef01cSRoman Divacky 92759d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 92859d1ed5bSDimitry Andric } 92959d1ed5bSDimitry Andric 93059d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, 93159d1ed5bSDimitry Andric const NamedDecl *ND) { 93259d1ed5bSDimitry Andric // Set linkage and visibility in case we never see a definition. 93359d1ed5bSDimitry Andric LinkageInfo LV = ND->getLinkageAndVisibility(); 93459d1ed5bSDimitry Andric if (LV.getLinkage() != ExternalLinkage) { 93559d1ed5bSDimitry Andric // Don't set internal linkage on declarations. 93659d1ed5bSDimitry Andric } else { 93759d1ed5bSDimitry Andric if (ND->hasAttr<DLLImportAttr>()) { 93859d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 93959d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 94059d1ed5bSDimitry Andric } else if (ND->hasAttr<DLLExportAttr>()) { 94159d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 94259d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 94359d1ed5bSDimitry Andric } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 94459d1ed5bSDimitry Andric // "extern_weak" is overloaded in LLVM; we probably should have 94559d1ed5bSDimitry Andric // separate linkage types for this. 94659d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 94759d1ed5bSDimitry Andric } 94859d1ed5bSDimitry Andric 94959d1ed5bSDimitry Andric // Set visibility on a declaration only if it's explicit. 95059d1ed5bSDimitry Andric if (LV.isVisibilityExplicit()) 95159d1ed5bSDimitry Andric GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility())); 95259d1ed5bSDimitry Andric } 953f22ef01cSRoman Divacky } 954f22ef01cSRoman Divacky 9550623d748SDimitry Andric void CodeGenModule::CreateFunctionBitSetEntry(const FunctionDecl *FD, 9560623d748SDimitry Andric llvm::Function *F) { 9570623d748SDimitry Andric // Only if we are checking indirect calls. 9580623d748SDimitry Andric if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 9590623d748SDimitry Andric return; 9600623d748SDimitry Andric 9610623d748SDimitry Andric // Non-static class methods are handled via vtable pointer checks elsewhere. 9620623d748SDimitry Andric if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 9630623d748SDimitry Andric return; 9640623d748SDimitry Andric 9650623d748SDimitry Andric // Additionally, if building with cross-DSO support... 9660623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 9670623d748SDimitry Andric // Don't emit entries for function declarations. In cross-DSO mode these are 9680623d748SDimitry Andric // handled with better precision at run time. 9690623d748SDimitry Andric if (!FD->hasBody()) 9700623d748SDimitry Andric return; 9710623d748SDimitry Andric // Skip available_externally functions. They won't be codegen'ed in the 9720623d748SDimitry Andric // current module anyway. 9730623d748SDimitry Andric if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally) 9740623d748SDimitry Andric return; 9750623d748SDimitry Andric } 9760623d748SDimitry Andric 9770623d748SDimitry Andric llvm::NamedMDNode *BitsetsMD = 9780623d748SDimitry Andric getModule().getOrInsertNamedMetadata("llvm.bitsets"); 9790623d748SDimitry Andric 9800623d748SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 9810623d748SDimitry Andric llvm::Metadata *BitsetOps[] = { 9820623d748SDimitry Andric MD, llvm::ConstantAsMetadata::get(F), 9830623d748SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int64Ty, 0))}; 9840623d748SDimitry Andric BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps)); 9850623d748SDimitry Andric 9860623d748SDimitry Andric // Emit a hash-based bit set entry for cross-DSO calls. 9870623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 9880623d748SDimitry Andric if (auto TypeId = CreateCfiIdForTypeMetadata(MD)) { 9890623d748SDimitry Andric llvm::Metadata *BitsetOps2[] = { 9900623d748SDimitry Andric llvm::ConstantAsMetadata::get(TypeId), 9910623d748SDimitry Andric llvm::ConstantAsMetadata::get(F), 9920623d748SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int64Ty, 0))}; 9930623d748SDimitry Andric BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps2)); 9940623d748SDimitry Andric } 9950623d748SDimitry Andric } 9960623d748SDimitry Andric } 9970623d748SDimitry Andric 99839d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 99939d628a0SDimitry Andric bool IsIncompleteFunction, 100039d628a0SDimitry Andric bool IsThunk) { 100133956c43SDimitry Andric if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 10023b0f4066SDimitry Andric // If this is an intrinsic function, set the function's attributes 10033b0f4066SDimitry Andric // to the intrinsic's attributes. 100433956c43SDimitry Andric F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 10053b0f4066SDimitry Andric return; 10063b0f4066SDimitry Andric } 10073b0f4066SDimitry Andric 100859d1ed5bSDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1009f22ef01cSRoman Divacky 1010f22ef01cSRoman Divacky if (!IsIncompleteFunction) 1011dff0c46cSDimitry Andric SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 1012f22ef01cSRoman Divacky 101359d1ed5bSDimitry Andric // Add the Returned attribute for "this", except for iOS 5 and earlier 101459d1ed5bSDimitry Andric // where substantial code, including the libstdc++ dylib, was compiled with 101559d1ed5bSDimitry Andric // GCC and does not actually return "this". 101639d628a0SDimitry Andric if (!IsThunk && getCXXABI().HasThisReturn(GD) && 101759d1ed5bSDimitry Andric !(getTarget().getTriple().isiOS() && 101859d1ed5bSDimitry Andric getTarget().getTriple().isOSVersionLT(6))) { 1019f785676fSDimitry Andric assert(!F->arg_empty() && 1020f785676fSDimitry Andric F->arg_begin()->getType() 1021f785676fSDimitry Andric ->canLosslesslyBitCastTo(F->getReturnType()) && 1022f785676fSDimitry Andric "unexpected this return"); 1023f785676fSDimitry Andric F->addAttribute(1, llvm::Attribute::Returned); 1024f785676fSDimitry Andric } 1025f785676fSDimitry Andric 1026f22ef01cSRoman Divacky // Only a few attributes are set on declarations; these may later be 1027f22ef01cSRoman Divacky // overridden by a definition. 1028f22ef01cSRoman Divacky 102959d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(F, FD); 10302754fe60SDimitry Andric 1031f22ef01cSRoman Divacky if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 1032f22ef01cSRoman Divacky F->setSection(SA->getName()); 1033f785676fSDimitry Andric 1034f785676fSDimitry Andric // A replaceable global allocation function does not act like a builtin by 1035f785676fSDimitry Andric // default, only if it is invoked by a new-expression or delete-expression. 1036f785676fSDimitry Andric if (FD->isReplaceableGlobalAllocationFunction()) 1037f785676fSDimitry Andric F->addAttribute(llvm::AttributeSet::FunctionIndex, 1038f785676fSDimitry Andric llvm::Attribute::NoBuiltin); 10390623d748SDimitry Andric 10400623d748SDimitry Andric CreateFunctionBitSetEntry(FD, F); 1041f22ef01cSRoman Divacky } 1042f22ef01cSRoman Divacky 104359d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 1044f22ef01cSRoman Divacky assert(!GV->isDeclaration() && 1045f22ef01cSRoman Divacky "Only globals with definition can force usage."); 104697bc6c73SDimitry Andric LLVMUsed.emplace_back(GV); 1047f22ef01cSRoman Divacky } 1048f22ef01cSRoman Divacky 104959d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 105059d1ed5bSDimitry Andric assert(!GV->isDeclaration() && 105159d1ed5bSDimitry Andric "Only globals with definition can force usage."); 105297bc6c73SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 105359d1ed5bSDimitry Andric } 105459d1ed5bSDimitry Andric 105559d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name, 105659d1ed5bSDimitry Andric std::vector<llvm::WeakVH> &List) { 1057f22ef01cSRoman Divacky // Don't create llvm.used if there is no need. 105859d1ed5bSDimitry Andric if (List.empty()) 1059f22ef01cSRoman Divacky return; 1060f22ef01cSRoman Divacky 106159d1ed5bSDimitry Andric // Convert List to what ConstantArray needs. 1062dff0c46cSDimitry Andric SmallVector<llvm::Constant*, 8> UsedArray; 106359d1ed5bSDimitry Andric UsedArray.resize(List.size()); 106459d1ed5bSDimitry Andric for (unsigned i = 0, e = List.size(); i != e; ++i) { 1065f22ef01cSRoman Divacky UsedArray[i] = 106644f7b0dcSDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 106744f7b0dcSDimitry Andric cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 1068f22ef01cSRoman Divacky } 1069f22ef01cSRoman Divacky 1070f22ef01cSRoman Divacky if (UsedArray.empty()) 1071f22ef01cSRoman Divacky return; 107259d1ed5bSDimitry Andric llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 1073f22ef01cSRoman Divacky 107459d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 107559d1ed5bSDimitry Andric CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 107659d1ed5bSDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), Name); 1077f22ef01cSRoman Divacky 1078f22ef01cSRoman Divacky GV->setSection("llvm.metadata"); 1079f22ef01cSRoman Divacky } 1080f22ef01cSRoman Divacky 108159d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() { 108259d1ed5bSDimitry Andric emitUsed(*this, "llvm.used", LLVMUsed); 108359d1ed5bSDimitry Andric emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 108459d1ed5bSDimitry Andric } 108559d1ed5bSDimitry Andric 1086f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 108739d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 1088f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1089f785676fSDimitry Andric } 1090f785676fSDimitry Andric 1091f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 1092f785676fSDimitry Andric llvm::SmallString<32> Opt; 1093f785676fSDimitry Andric getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 109439d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1095f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1096f785676fSDimitry Andric } 1097f785676fSDimitry Andric 1098f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) { 1099f785676fSDimitry Andric llvm::SmallString<24> Opt; 1100f785676fSDimitry Andric getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 110139d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1102f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1103f785676fSDimitry Andric } 1104f785676fSDimitry Andric 1105139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules 1106139f7f9bSDimitry Andric /// it depends on, using a postorder walk. 110739d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 110839d628a0SDimitry Andric SmallVectorImpl<llvm::Metadata *> &Metadata, 1109139f7f9bSDimitry Andric llvm::SmallPtrSet<Module *, 16> &Visited) { 1110139f7f9bSDimitry Andric // Import this module's parent. 111139d628a0SDimitry Andric if (Mod->Parent && Visited.insert(Mod->Parent).second) { 1112f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 1113139f7f9bSDimitry Andric } 1114139f7f9bSDimitry Andric 1115139f7f9bSDimitry Andric // Import this module's dependencies. 1116139f7f9bSDimitry Andric for (unsigned I = Mod->Imports.size(); I > 0; --I) { 111739d628a0SDimitry Andric if (Visited.insert(Mod->Imports[I - 1]).second) 1118f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 1119139f7f9bSDimitry Andric } 1120139f7f9bSDimitry Andric 1121139f7f9bSDimitry Andric // Add linker options to link against the libraries/frameworks 1122139f7f9bSDimitry Andric // described by this module. 1123f785676fSDimitry Andric llvm::LLVMContext &Context = CGM.getLLVMContext(); 1124139f7f9bSDimitry Andric for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 1125f785676fSDimitry Andric // Link against a framework. Frameworks are currently Darwin only, so we 1126f785676fSDimitry Andric // don't to ask TargetCodeGenInfo for the spelling of the linker option. 1127139f7f9bSDimitry Andric if (Mod->LinkLibraries[I-1].IsFramework) { 112839d628a0SDimitry Andric llvm::Metadata *Args[2] = { 1129139f7f9bSDimitry Andric llvm::MDString::get(Context, "-framework"), 113039d628a0SDimitry Andric llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 1131139f7f9bSDimitry Andric 1132139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 1133139f7f9bSDimitry Andric continue; 1134139f7f9bSDimitry Andric } 1135139f7f9bSDimitry Andric 1136139f7f9bSDimitry Andric // Link against a library. 1137f785676fSDimitry Andric llvm::SmallString<24> Opt; 1138f785676fSDimitry Andric CGM.getTargetCodeGenInfo().getDependentLibraryOption( 1139f785676fSDimitry Andric Mod->LinkLibraries[I-1].Library, Opt); 114039d628a0SDimitry Andric auto *OptString = llvm::MDString::get(Context, Opt); 1141139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, OptString)); 1142139f7f9bSDimitry Andric } 1143139f7f9bSDimitry Andric } 1144139f7f9bSDimitry Andric 1145139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() { 1146139f7f9bSDimitry Andric // Collect the set of all of the modules we want to visit to emit link 1147139f7f9bSDimitry Andric // options, which is essentially the imported modules and all of their 1148139f7f9bSDimitry Andric // non-explicit child modules. 1149139f7f9bSDimitry Andric llvm::SetVector<clang::Module *> LinkModules; 1150139f7f9bSDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 1151139f7f9bSDimitry Andric SmallVector<clang::Module *, 16> Stack; 1152139f7f9bSDimitry Andric 1153139f7f9bSDimitry Andric // Seed the stack with imported modules. 11548f0fd8f6SDimitry Andric for (Module *M : ImportedModules) 11558f0fd8f6SDimitry Andric if (Visited.insert(M).second) 11568f0fd8f6SDimitry Andric Stack.push_back(M); 1157139f7f9bSDimitry Andric 1158139f7f9bSDimitry Andric // Find all of the modules to import, making a little effort to prune 1159139f7f9bSDimitry Andric // non-leaf modules. 1160139f7f9bSDimitry Andric while (!Stack.empty()) { 1161f785676fSDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 1162139f7f9bSDimitry Andric 1163139f7f9bSDimitry Andric bool AnyChildren = false; 1164139f7f9bSDimitry Andric 1165139f7f9bSDimitry Andric // Visit the submodules of this module. 1166139f7f9bSDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 1167139f7f9bSDimitry Andric SubEnd = Mod->submodule_end(); 1168139f7f9bSDimitry Andric Sub != SubEnd; ++Sub) { 1169139f7f9bSDimitry Andric // Skip explicit children; they need to be explicitly imported to be 1170139f7f9bSDimitry Andric // linked against. 1171139f7f9bSDimitry Andric if ((*Sub)->IsExplicit) 1172139f7f9bSDimitry Andric continue; 1173139f7f9bSDimitry Andric 117439d628a0SDimitry Andric if (Visited.insert(*Sub).second) { 1175139f7f9bSDimitry Andric Stack.push_back(*Sub); 1176139f7f9bSDimitry Andric AnyChildren = true; 1177139f7f9bSDimitry Andric } 1178139f7f9bSDimitry Andric } 1179139f7f9bSDimitry Andric 1180139f7f9bSDimitry Andric // We didn't find any children, so add this module to the list of 1181139f7f9bSDimitry Andric // modules to link against. 1182139f7f9bSDimitry Andric if (!AnyChildren) { 1183139f7f9bSDimitry Andric LinkModules.insert(Mod); 1184139f7f9bSDimitry Andric } 1185139f7f9bSDimitry Andric } 1186139f7f9bSDimitry Andric 1187139f7f9bSDimitry Andric // Add link options for all of the imported modules in reverse topological 1188f785676fSDimitry Andric // order. We don't do anything to try to order import link flags with respect 1189f785676fSDimitry Andric // to linker options inserted by things like #pragma comment(). 119039d628a0SDimitry Andric SmallVector<llvm::Metadata *, 16> MetadataArgs; 1191139f7f9bSDimitry Andric Visited.clear(); 11928f0fd8f6SDimitry Andric for (Module *M : LinkModules) 11938f0fd8f6SDimitry Andric if (Visited.insert(M).second) 11948f0fd8f6SDimitry Andric addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 1195139f7f9bSDimitry Andric std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 1196f785676fSDimitry Andric LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 1197139f7f9bSDimitry Andric 1198139f7f9bSDimitry Andric // Add the linker options metadata flag. 1199139f7f9bSDimitry Andric getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options", 1200f785676fSDimitry Andric llvm::MDNode::get(getLLVMContext(), 1201f785676fSDimitry Andric LinkerOptionsMetadata)); 1202139f7f9bSDimitry Andric } 1203139f7f9bSDimitry Andric 1204f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() { 1205f22ef01cSRoman Divacky // Emit code for any potentially referenced deferred decls. Since a 1206f22ef01cSRoman Divacky // previously unused static decl may become used during the generation of code 1207f22ef01cSRoman Divacky // for a static function, iterate until no changes are made. 1208f22ef01cSRoman Divacky 1209f22ef01cSRoman Divacky if (!DeferredVTables.empty()) { 1210139f7f9bSDimitry Andric EmitDeferredVTables(); 1211139f7f9bSDimitry Andric 1212139f7f9bSDimitry Andric // Emitting a v-table doesn't directly cause more v-tables to 1213139f7f9bSDimitry Andric // become deferred, although it can cause functions to be 1214139f7f9bSDimitry Andric // emitted that then need those v-tables. 1215139f7f9bSDimitry Andric assert(DeferredVTables.empty()); 1216f22ef01cSRoman Divacky } 1217f22ef01cSRoman Divacky 1218139f7f9bSDimitry Andric // Stop if we're out of both deferred v-tables and deferred declarations. 121933956c43SDimitry Andric if (DeferredDeclsToEmit.empty()) 122033956c43SDimitry Andric return; 1221139f7f9bSDimitry Andric 122233956c43SDimitry Andric // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 122333956c43SDimitry Andric // work, it will not interfere with this. 122433956c43SDimitry Andric std::vector<DeferredGlobal> CurDeclsToEmit; 122533956c43SDimitry Andric CurDeclsToEmit.swap(DeferredDeclsToEmit); 122633956c43SDimitry Andric 122733956c43SDimitry Andric for (DeferredGlobal &G : CurDeclsToEmit) { 122859d1ed5bSDimitry Andric GlobalDecl D = G.GD; 122959d1ed5bSDimitry Andric llvm::GlobalValue *GV = G.GV; 123033956c43SDimitry Andric G.GV = nullptr; 1231f22ef01cSRoman Divacky 12320623d748SDimitry Andric // We should call GetAddrOfGlobal with IsForDefinition set to true in order 12330623d748SDimitry Andric // to get GlobalValue with exactly the type we need, not something that 12340623d748SDimitry Andric // might had been created for another decl with the same mangled name but 12350623d748SDimitry Andric // different type. 12360623d748SDimitry Andric // FIXME: Support for variables is not implemented yet. 12370623d748SDimitry Andric if (isa<FunctionDecl>(D.getDecl())) 12380623d748SDimitry Andric GV = cast<llvm::GlobalValue>(GetAddrOfGlobal(D, /*IsForDefinition=*/true)); 12390623d748SDimitry Andric else 124039d628a0SDimitry Andric if (!GV) 124139d628a0SDimitry Andric GV = GetGlobalValue(getMangledName(D)); 124239d628a0SDimitry Andric 1243f22ef01cSRoman Divacky // Check to see if we've already emitted this. This is necessary 1244f22ef01cSRoman Divacky // for a couple of reasons: first, decls can end up in the 1245f22ef01cSRoman Divacky // deferred-decls queue multiple times, and second, decls can end 1246f22ef01cSRoman Divacky // up with definitions in unusual ways (e.g. by an extern inline 1247f22ef01cSRoman Divacky // function acquiring a strong function redefinition). Just 1248f22ef01cSRoman Divacky // ignore these cases. 124939d628a0SDimitry Andric if (GV && !GV->isDeclaration()) 1250f22ef01cSRoman Divacky continue; 1251f22ef01cSRoman Divacky 1252f22ef01cSRoman Divacky // Otherwise, emit the definition and move on to the next one. 125359d1ed5bSDimitry Andric EmitGlobalDefinition(D, GV); 125433956c43SDimitry Andric 125533956c43SDimitry Andric // If we found out that we need to emit more decls, do that recursively. 125633956c43SDimitry Andric // This has the advantage that the decls are emitted in a DFS and related 125733956c43SDimitry Andric // ones are close together, which is convenient for testing. 125833956c43SDimitry Andric if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 125933956c43SDimitry Andric EmitDeferred(); 126033956c43SDimitry Andric assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 126133956c43SDimitry Andric } 1262f22ef01cSRoman Divacky } 1263f22ef01cSRoman Divacky } 1264f22ef01cSRoman Divacky 12656122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() { 12666122f3e6SDimitry Andric if (Annotations.empty()) 12676122f3e6SDimitry Andric return; 12686122f3e6SDimitry Andric 12696122f3e6SDimitry Andric // Create a new global variable for the ConstantStruct in the Module. 12706122f3e6SDimitry Andric llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 12716122f3e6SDimitry Andric Annotations[0]->getType(), Annotations.size()), Annotations); 127259d1ed5bSDimitry Andric auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 127359d1ed5bSDimitry Andric llvm::GlobalValue::AppendingLinkage, 127459d1ed5bSDimitry Andric Array, "llvm.global.annotations"); 12756122f3e6SDimitry Andric gv->setSection(AnnotationSection); 12766122f3e6SDimitry Andric } 12776122f3e6SDimitry Andric 1278139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1279f785676fSDimitry Andric llvm::Constant *&AStr = AnnotationStrings[Str]; 1280f785676fSDimitry Andric if (AStr) 1281f785676fSDimitry Andric return AStr; 12826122f3e6SDimitry Andric 12836122f3e6SDimitry Andric // Not found yet, create a new global. 1284dff0c46cSDimitry Andric llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 128559d1ed5bSDimitry Andric auto *gv = 128659d1ed5bSDimitry Andric new llvm::GlobalVariable(getModule(), s->getType(), true, 128759d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, s, ".str"); 12886122f3e6SDimitry Andric gv->setSection(AnnotationSection); 12896122f3e6SDimitry Andric gv->setUnnamedAddr(true); 1290f785676fSDimitry Andric AStr = gv; 12916122f3e6SDimitry Andric return gv; 12926122f3e6SDimitry Andric } 12936122f3e6SDimitry Andric 12946122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 12956122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 12966122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(Loc); 12976122f3e6SDimitry Andric if (PLoc.isValid()) 12986122f3e6SDimitry Andric return EmitAnnotationString(PLoc.getFilename()); 12996122f3e6SDimitry Andric return EmitAnnotationString(SM.getBufferName(Loc)); 13006122f3e6SDimitry Andric } 13016122f3e6SDimitry Andric 13026122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 13036122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 13046122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(L); 13056122f3e6SDimitry Andric unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 13066122f3e6SDimitry Andric SM.getExpansionLineNumber(L); 13076122f3e6SDimitry Andric return llvm::ConstantInt::get(Int32Ty, LineNo); 13086122f3e6SDimitry Andric } 13096122f3e6SDimitry Andric 1310f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1311f22ef01cSRoman Divacky const AnnotateAttr *AA, 13126122f3e6SDimitry Andric SourceLocation L) { 13136122f3e6SDimitry Andric // Get the globals for file name, annotation, and the line number. 13146122f3e6SDimitry Andric llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 13156122f3e6SDimitry Andric *UnitGV = EmitAnnotationUnit(L), 13166122f3e6SDimitry Andric *LineNoCst = EmitAnnotationLineNo(L); 1317f22ef01cSRoman Divacky 1318f22ef01cSRoman Divacky // Create the ConstantStruct for the global annotation. 1319f22ef01cSRoman Divacky llvm::Constant *Fields[4] = { 13206122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 13216122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 13226122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 13236122f3e6SDimitry Andric LineNoCst 1324f22ef01cSRoman Divacky }; 132517a519f9SDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 1326f22ef01cSRoman Divacky } 1327f22ef01cSRoman Divacky 13286122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 13296122f3e6SDimitry Andric llvm::GlobalValue *GV) { 13306122f3e6SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 13316122f3e6SDimitry Andric // Get the struct elements for these annotations. 133259d1ed5bSDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 133359d1ed5bSDimitry Andric Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 13346122f3e6SDimitry Andric } 13356122f3e6SDimitry Andric 133639d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn, 133739d628a0SDimitry Andric SourceLocation Loc) const { 133839d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 133939d628a0SDimitry Andric // Blacklist by function name. 134039d628a0SDimitry Andric if (SanitizerBL.isBlacklistedFunction(Fn->getName())) 134139d628a0SDimitry Andric return true; 134239d628a0SDimitry Andric // Blacklist by location. 13430623d748SDimitry Andric if (Loc.isValid()) 134439d628a0SDimitry Andric return SanitizerBL.isBlacklistedLocation(Loc); 134539d628a0SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 134639d628a0SDimitry Andric // it's located in the main file. 134739d628a0SDimitry Andric auto &SM = Context.getSourceManager(); 134839d628a0SDimitry Andric if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 134939d628a0SDimitry Andric return SanitizerBL.isBlacklistedFile(MainFile->getName()); 135039d628a0SDimitry Andric } 135139d628a0SDimitry Andric return false; 135239d628a0SDimitry Andric } 135339d628a0SDimitry Andric 135439d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 135539d628a0SDimitry Andric SourceLocation Loc, QualType Ty, 135639d628a0SDimitry Andric StringRef Category) const { 13578f0fd8f6SDimitry Andric // For now globals can be blacklisted only in ASan and KASan. 13588f0fd8f6SDimitry Andric if (!LangOpts.Sanitize.hasOneOf( 13598f0fd8f6SDimitry Andric SanitizerKind::Address | SanitizerKind::KernelAddress)) 136039d628a0SDimitry Andric return false; 136139d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 136239d628a0SDimitry Andric if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category)) 136339d628a0SDimitry Andric return true; 136439d628a0SDimitry Andric if (SanitizerBL.isBlacklistedLocation(Loc, Category)) 136539d628a0SDimitry Andric return true; 136639d628a0SDimitry Andric // Check global type. 136739d628a0SDimitry Andric if (!Ty.isNull()) { 136839d628a0SDimitry Andric // Drill down the array types: if global variable of a fixed type is 136939d628a0SDimitry Andric // blacklisted, we also don't instrument arrays of them. 137039d628a0SDimitry Andric while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 137139d628a0SDimitry Andric Ty = AT->getElementType(); 137239d628a0SDimitry Andric Ty = Ty.getCanonicalType().getUnqualifiedType(); 137339d628a0SDimitry Andric // We allow to blacklist only record types (classes, structs etc.) 137439d628a0SDimitry Andric if (Ty->isRecordType()) { 137539d628a0SDimitry Andric std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 137639d628a0SDimitry Andric if (SanitizerBL.isBlacklistedType(TypeStr, Category)) 137739d628a0SDimitry Andric return true; 137839d628a0SDimitry Andric } 137939d628a0SDimitry Andric } 138039d628a0SDimitry Andric return false; 138139d628a0SDimitry Andric } 138239d628a0SDimitry Andric 138339d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 1384e580952dSDimitry Andric // Never defer when EmitAllDecls is specified. 1385dff0c46cSDimitry Andric if (LangOpts.EmitAllDecls) 138639d628a0SDimitry Andric return true; 138739d628a0SDimitry Andric 138839d628a0SDimitry Andric return getContext().DeclMustBeEmitted(Global); 138939d628a0SDimitry Andric } 139039d628a0SDimitry Andric 139139d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 139239d628a0SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) 139339d628a0SDimitry Andric if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 139439d628a0SDimitry Andric // Implicit template instantiations may change linkage if they are later 139539d628a0SDimitry Andric // explicitly instantiated, so they should not be emitted eagerly. 1396f22ef01cSRoman Divacky return false; 1397875ed548SDimitry Andric // If OpenMP is enabled and threadprivates must be generated like TLS, delay 1398875ed548SDimitry Andric // codegen for global variables, because they may be marked as threadprivate. 1399875ed548SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 1400875ed548SDimitry Andric getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global)) 1401875ed548SDimitry Andric return false; 1402f22ef01cSRoman Divacky 140339d628a0SDimitry Andric return true; 1404f22ef01cSRoman Divacky } 1405f22ef01cSRoman Divacky 14060623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor( 14073861d79fSDimitry Andric const CXXUuidofExpr* E) { 14083861d79fSDimitry Andric // Sema has verified that IIDSource has a __declspec(uuid()), and that its 14093861d79fSDimitry Andric // well-formed. 1410f785676fSDimitry Andric StringRef Uuid = E->getUuidAsStringRef(Context); 1411f785676fSDimitry Andric std::string Name = "_GUID_" + Uuid.lower(); 1412f785676fSDimitry Andric std::replace(Name.begin(), Name.end(), '-', '_'); 14133861d79fSDimitry Andric 14140623d748SDimitry Andric // Contains a 32-bit field. 14150623d748SDimitry Andric CharUnits Alignment = CharUnits::fromQuantity(4); 14160623d748SDimitry Andric 14173861d79fSDimitry Andric // Look for an existing global. 14183861d79fSDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 14190623d748SDimitry Andric return ConstantAddress(GV, Alignment); 14203861d79fSDimitry Andric 142139d628a0SDimitry Andric llvm::Constant *Init = EmitUuidofInitializer(Uuid); 14223861d79fSDimitry Andric assert(Init && "failed to initialize as constant"); 14233861d79fSDimitry Andric 142459d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 1425f785676fSDimitry Andric getModule(), Init->getType(), 1426f785676fSDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 142733956c43SDimitry Andric if (supportsCOMDAT()) 142833956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 14290623d748SDimitry Andric return ConstantAddress(GV, Alignment); 14303861d79fSDimitry Andric } 14313861d79fSDimitry Andric 14320623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1433f22ef01cSRoman Divacky const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1434f22ef01cSRoman Divacky assert(AA && "No alias?"); 1435f22ef01cSRoman Divacky 14360623d748SDimitry Andric CharUnits Alignment = getContext().getDeclAlign(VD); 14376122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1438f22ef01cSRoman Divacky 1439f22ef01cSRoman Divacky // See if there is already something with the target's name in the module. 1440f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 14413861d79fSDimitry Andric if (Entry) { 14423861d79fSDimitry Andric unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 14430623d748SDimitry Andric auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 14440623d748SDimitry Andric return ConstantAddress(Ptr, Alignment); 14453861d79fSDimitry Andric } 1446f22ef01cSRoman Divacky 1447f22ef01cSRoman Divacky llvm::Constant *Aliasee; 1448f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 14493861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 14503861d79fSDimitry Andric GlobalDecl(cast<FunctionDecl>(VD)), 14512754fe60SDimitry Andric /*ForVTable=*/false); 1452f22ef01cSRoman Divacky else 1453f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 145459d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 145559d1ed5bSDimitry Andric nullptr); 14563861d79fSDimitry Andric 145759d1ed5bSDimitry Andric auto *F = cast<llvm::GlobalValue>(Aliasee); 1458f22ef01cSRoman Divacky F->setLinkage(llvm::Function::ExternalWeakLinkage); 1459f22ef01cSRoman Divacky WeakRefReferences.insert(F); 1460f22ef01cSRoman Divacky 14610623d748SDimitry Andric return ConstantAddress(Aliasee, Alignment); 1462f22ef01cSRoman Divacky } 1463f22ef01cSRoman Divacky 1464f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) { 146559d1ed5bSDimitry Andric const auto *Global = cast<ValueDecl>(GD.getDecl()); 1466f22ef01cSRoman Divacky 1467f22ef01cSRoman Divacky // Weak references don't produce any output by themselves. 1468f22ef01cSRoman Divacky if (Global->hasAttr<WeakRefAttr>()) 1469f22ef01cSRoman Divacky return; 1470f22ef01cSRoman Divacky 1471f22ef01cSRoman Divacky // If this is an alias definition (which otherwise looks like a declaration) 1472f22ef01cSRoman Divacky // emit it now. 1473f22ef01cSRoman Divacky if (Global->hasAttr<AliasAttr>()) 1474f22ef01cSRoman Divacky return EmitAliasDefinition(GD); 1475f22ef01cSRoman Divacky 14766122f3e6SDimitry Andric // If this is CUDA, be selective about which declarations we emit. 1477dff0c46cSDimitry Andric if (LangOpts.CUDA) { 147833956c43SDimitry Andric if (LangOpts.CUDAIsDevice) { 14796122f3e6SDimitry Andric if (!Global->hasAttr<CUDADeviceAttr>() && 14806122f3e6SDimitry Andric !Global->hasAttr<CUDAGlobalAttr>() && 14816122f3e6SDimitry Andric !Global->hasAttr<CUDAConstantAttr>() && 14826122f3e6SDimitry Andric !Global->hasAttr<CUDASharedAttr>()) 14836122f3e6SDimitry Andric return; 14846122f3e6SDimitry Andric } else { 14856122f3e6SDimitry Andric if (!Global->hasAttr<CUDAHostAttr>() && ( 14866122f3e6SDimitry Andric Global->hasAttr<CUDADeviceAttr>() || 14876122f3e6SDimitry Andric Global->hasAttr<CUDAConstantAttr>() || 14886122f3e6SDimitry Andric Global->hasAttr<CUDASharedAttr>())) 14896122f3e6SDimitry Andric return; 1490e580952dSDimitry Andric } 1491e580952dSDimitry Andric } 1492e580952dSDimitry Andric 14936122f3e6SDimitry Andric // Ignore declarations, they will be emitted on their first use. 149459d1ed5bSDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 1495f22ef01cSRoman Divacky // Forward declarations are emitted lazily on first use. 14966122f3e6SDimitry Andric if (!FD->doesThisDeclarationHaveABody()) { 14976122f3e6SDimitry Andric if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1498f22ef01cSRoman Divacky return; 14996122f3e6SDimitry Andric 15006122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 150159d1ed5bSDimitry Andric 150259d1ed5bSDimitry Andric // Compute the function info and LLVM type. 150359d1ed5bSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 150459d1ed5bSDimitry Andric llvm::Type *Ty = getTypes().GetFunctionType(FI); 150559d1ed5bSDimitry Andric 150659d1ed5bSDimitry Andric GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 150759d1ed5bSDimitry Andric /*DontDefer=*/false); 15086122f3e6SDimitry Andric return; 15096122f3e6SDimitry Andric } 1510f22ef01cSRoman Divacky } else { 151159d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(Global); 1512f22ef01cSRoman Divacky assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1513f22ef01cSRoman Divacky 151459d1ed5bSDimitry Andric if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 151559d1ed5bSDimitry Andric !Context.isMSStaticDataMemberInlineDefinition(VD)) 1516f22ef01cSRoman Divacky return; 1517f22ef01cSRoman Divacky } 1518f22ef01cSRoman Divacky 151939d628a0SDimitry Andric // Defer code generation to first use when possible, e.g. if this is an inline 152039d628a0SDimitry Andric // function. If the global must always be emitted, do it eagerly if possible 152139d628a0SDimitry Andric // to benefit from cache locality. 152239d628a0SDimitry Andric if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 1523f22ef01cSRoman Divacky // Emit the definition if it can't be deferred. 1524f22ef01cSRoman Divacky EmitGlobalDefinition(GD); 1525f22ef01cSRoman Divacky return; 1526f22ef01cSRoman Divacky } 1527f22ef01cSRoman Divacky 1528e580952dSDimitry Andric // If we're deferring emission of a C++ variable with an 1529e580952dSDimitry Andric // initializer, remember the order in which it appeared in the file. 1530dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1531e580952dSDimitry Andric cast<VarDecl>(Global)->hasInit()) { 1532e580952dSDimitry Andric DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 153359d1ed5bSDimitry Andric CXXGlobalInits.push_back(nullptr); 1534e580952dSDimitry Andric } 1535e580952dSDimitry Andric 15366122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 153739d628a0SDimitry Andric if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) { 153839d628a0SDimitry Andric // The value has already been used and should therefore be emitted. 153959d1ed5bSDimitry Andric addDeferredDeclToEmit(GV, GD); 154039d628a0SDimitry Andric } else if (MustBeEmitted(Global)) { 154139d628a0SDimitry Andric // The value must be emitted, but cannot be emitted eagerly. 154239d628a0SDimitry Andric assert(!MayBeEmittedEagerly(Global)); 154339d628a0SDimitry Andric addDeferredDeclToEmit(/*GV=*/nullptr, GD); 154439d628a0SDimitry Andric } else { 1545f22ef01cSRoman Divacky // Otherwise, remember that we saw a deferred decl with this name. The 1546f22ef01cSRoman Divacky // first use of the mangled name will cause it to move into 1547f22ef01cSRoman Divacky // DeferredDeclsToEmit. 1548f22ef01cSRoman Divacky DeferredDecls[MangledName] = GD; 1549f22ef01cSRoman Divacky } 1550f22ef01cSRoman Divacky } 1551f22ef01cSRoman Divacky 1552f8254f43SDimitry Andric namespace { 1553f8254f43SDimitry Andric struct FunctionIsDirectlyRecursive : 1554f8254f43SDimitry Andric public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1555f8254f43SDimitry Andric const StringRef Name; 1556dff0c46cSDimitry Andric const Builtin::Context &BI; 1557f8254f43SDimitry Andric bool Result; 1558dff0c46cSDimitry Andric FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1559dff0c46cSDimitry Andric Name(N), BI(C), Result(false) { 1560f8254f43SDimitry Andric } 1561f8254f43SDimitry Andric typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1562f8254f43SDimitry Andric 1563f8254f43SDimitry Andric bool TraverseCallExpr(CallExpr *E) { 1564dff0c46cSDimitry Andric const FunctionDecl *FD = E->getDirectCallee(); 1565dff0c46cSDimitry Andric if (!FD) 1566f8254f43SDimitry Andric return true; 1567dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1568dff0c46cSDimitry Andric if (Attr && Name == Attr->getLabel()) { 1569dff0c46cSDimitry Andric Result = true; 1570dff0c46cSDimitry Andric return false; 1571dff0c46cSDimitry Andric } 1572dff0c46cSDimitry Andric unsigned BuiltinID = FD->getBuiltinID(); 15733dac3a9bSDimitry Andric if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 1574f8254f43SDimitry Andric return true; 15750623d748SDimitry Andric StringRef BuiltinName = BI.getName(BuiltinID); 1576dff0c46cSDimitry Andric if (BuiltinName.startswith("__builtin_") && 1577dff0c46cSDimitry Andric Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1578f8254f43SDimitry Andric Result = true; 1579f8254f43SDimitry Andric return false; 1580f8254f43SDimitry Andric } 1581f8254f43SDimitry Andric return true; 1582f8254f43SDimitry Andric } 1583f8254f43SDimitry Andric }; 15840623d748SDimitry Andric 15850623d748SDimitry Andric struct DLLImportFunctionVisitor 15860623d748SDimitry Andric : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 15870623d748SDimitry Andric bool SafeToInline = true; 15880623d748SDimitry Andric 15890623d748SDimitry Andric bool VisitVarDecl(VarDecl *VD) { 15900623d748SDimitry Andric // A thread-local variable cannot be imported. 15910623d748SDimitry Andric SafeToInline = !VD->getTLSKind(); 15920623d748SDimitry Andric return SafeToInline; 15930623d748SDimitry Andric } 15940623d748SDimitry Andric 15950623d748SDimitry Andric // Make sure we're not referencing non-imported vars or functions. 15960623d748SDimitry Andric bool VisitDeclRefExpr(DeclRefExpr *E) { 15970623d748SDimitry Andric ValueDecl *VD = E->getDecl(); 15980623d748SDimitry Andric if (isa<FunctionDecl>(VD)) 15990623d748SDimitry Andric SafeToInline = VD->hasAttr<DLLImportAttr>(); 16000623d748SDimitry Andric else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 16010623d748SDimitry Andric SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 16020623d748SDimitry Andric return SafeToInline; 16030623d748SDimitry Andric } 16040623d748SDimitry Andric bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 16050623d748SDimitry Andric SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 16060623d748SDimitry Andric return SafeToInline; 16070623d748SDimitry Andric } 16080623d748SDimitry Andric bool VisitCXXNewExpr(CXXNewExpr *E) { 16090623d748SDimitry Andric SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 16100623d748SDimitry Andric return SafeToInline; 16110623d748SDimitry Andric } 16120623d748SDimitry Andric }; 1613f8254f43SDimitry Andric } 1614f8254f43SDimitry Andric 1615dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another 1616dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin, 1617dff0c46cSDimitry Andric // ends up pointing to itself. 1618f8254f43SDimitry Andric bool 1619dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1620dff0c46cSDimitry Andric StringRef Name; 1621dff0c46cSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1622dff0c46cSDimitry Andric // asm labels are a special kind of mangling we have to support. 1623dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1624dff0c46cSDimitry Andric if (!Attr) 1625f8254f43SDimitry Andric return false; 1626dff0c46cSDimitry Andric Name = Attr->getLabel(); 1627dff0c46cSDimitry Andric } else { 1628dff0c46cSDimitry Andric Name = FD->getName(); 1629dff0c46cSDimitry Andric } 1630f8254f43SDimitry Andric 1631dff0c46cSDimitry Andric FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1632dff0c46cSDimitry Andric Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1633f8254f43SDimitry Andric return Walker.Result; 1634f8254f43SDimitry Andric } 1635f8254f43SDimitry Andric 1636f8254f43SDimitry Andric bool 1637f785676fSDimitry Andric CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1638f785676fSDimitry Andric if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1639f8254f43SDimitry Andric return true; 164059d1ed5bSDimitry Andric const auto *F = cast<FunctionDecl>(GD.getDecl()); 164159d1ed5bSDimitry Andric if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1642f8254f43SDimitry Andric return false; 16430623d748SDimitry Andric 16440623d748SDimitry Andric if (F->hasAttr<DLLImportAttr>()) { 16450623d748SDimitry Andric // Check whether it would be safe to inline this dllimport function. 16460623d748SDimitry Andric DLLImportFunctionVisitor Visitor; 16470623d748SDimitry Andric Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 16480623d748SDimitry Andric if (!Visitor.SafeToInline) 16490623d748SDimitry Andric return false; 16500623d748SDimitry Andric } 16510623d748SDimitry Andric 1652f8254f43SDimitry Andric // PR9614. Avoid cases where the source code is lying to us. An available 1653f8254f43SDimitry Andric // externally function should have an equivalent function somewhere else, 1654f8254f43SDimitry Andric // but a function that calls itself is clearly not equivalent to the real 1655f8254f43SDimitry Andric // implementation. 1656f8254f43SDimitry Andric // This happens in glibc's btowc and in some configure checks. 1657dff0c46cSDimitry Andric return !isTriviallyRecursive(F); 1658f8254f43SDimitry Andric } 1659f8254f43SDimitry Andric 1660f785676fSDimitry Andric /// If the type for the method's class was generated by 1661f785676fSDimitry Andric /// CGDebugInfo::createContextChain(), the cache contains only a 1662f785676fSDimitry Andric /// limited DIType without any declarations. Since EmitFunctionStart() 1663f785676fSDimitry Andric /// needs to find the canonical declaration for each method, we need 1664f785676fSDimitry Andric /// to construct the complete type prior to emitting the method. 1665f785676fSDimitry Andric void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) { 1666f785676fSDimitry Andric if (!D->isInstance()) 1667f785676fSDimitry Andric return; 1668f785676fSDimitry Andric 1669f785676fSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 1670f785676fSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) { 167159d1ed5bSDimitry Andric const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext())); 1672f785676fSDimitry Andric DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation()); 1673f785676fSDimitry Andric } 1674f785676fSDimitry Andric } 1675f785676fSDimitry Andric 167659d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 167759d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 1678f22ef01cSRoman Divacky 1679f22ef01cSRoman Divacky PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1680f22ef01cSRoman Divacky Context.getSourceManager(), 1681f22ef01cSRoman Divacky "Generating code for declaration"); 1682f22ef01cSRoman Divacky 1683f785676fSDimitry Andric if (isa<FunctionDecl>(D)) { 1684ffd1746dSEd Schouten // At -O0, don't generate IR for functions with available_externally 1685ffd1746dSEd Schouten // linkage. 1686f785676fSDimitry Andric if (!shouldEmitFunction(GD)) 1687ffd1746dSEd Schouten return; 1688ffd1746dSEd Schouten 168959d1ed5bSDimitry Andric if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 1690f785676fSDimitry Andric CompleteDIClassType(Method); 1691bd5abe19SDimitry Andric // Make sure to emit the definition(s) before we emit the thunks. 1692bd5abe19SDimitry Andric // This is necessary for the generation of certain thunks. 169359d1ed5bSDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 169439d628a0SDimitry Andric ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); 169559d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 169639d628a0SDimitry Andric ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); 1697bd5abe19SDimitry Andric else 169859d1ed5bSDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 1699bd5abe19SDimitry Andric 1700f22ef01cSRoman Divacky if (Method->isVirtual()) 1701f22ef01cSRoman Divacky getVTables().EmitThunks(GD); 1702f22ef01cSRoman Divacky 1703bd5abe19SDimitry Andric return; 1704ffd1746dSEd Schouten } 1705f22ef01cSRoman Divacky 170659d1ed5bSDimitry Andric return EmitGlobalFunctionDefinition(GD, GV); 1707ffd1746dSEd Schouten } 1708f22ef01cSRoman Divacky 170959d1ed5bSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 1710f22ef01cSRoman Divacky return EmitGlobalVarDefinition(VD); 1711f22ef01cSRoman Divacky 17126122f3e6SDimitry Andric llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1713f22ef01cSRoman Divacky } 1714f22ef01cSRoman Divacky 17150623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 17160623d748SDimitry Andric llvm::Function *NewFn); 17170623d748SDimitry Andric 1718f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1719f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there 1720f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 1721f22ef01cSRoman Divacky /// bitcasted to the right type. 1722f22ef01cSRoman Divacky /// 1723f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 1724f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created. 1725f22ef01cSRoman Divacky llvm::Constant * 17266122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 17276122f3e6SDimitry Andric llvm::Type *Ty, 1728f785676fSDimitry Andric GlobalDecl GD, bool ForVTable, 172939d628a0SDimitry Andric bool DontDefer, bool IsThunk, 17300623d748SDimitry Andric llvm::AttributeSet ExtraAttrs, 17310623d748SDimitry Andric bool IsForDefinition) { 1732f785676fSDimitry Andric const Decl *D = GD.getDecl(); 1733f785676fSDimitry Andric 1734f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 1735f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1736f22ef01cSRoman Divacky if (Entry) { 17373861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 1738f785676fSDimitry Andric const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 1739f22ef01cSRoman Divacky if (FD && !FD->hasAttr<WeakAttr>()) 1740f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 1741f22ef01cSRoman Divacky } 1742f22ef01cSRoman Divacky 174339d628a0SDimitry Andric // Handle dropped DLL attributes. 174439d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 174539d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 174639d628a0SDimitry Andric 17470623d748SDimitry Andric // If there are two attempts to define the same mangled name, issue an 17480623d748SDimitry Andric // error. 17490623d748SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 17500623d748SDimitry Andric GlobalDecl OtherGD; 17510623d748SDimitry Andric // Check that GD is not yet in ExplicitDefinitions is required to make 17520623d748SDimitry Andric // sure that we issue an error only once. 17530623d748SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 17540623d748SDimitry Andric (GD.getCanonicalDecl().getDecl() != 17550623d748SDimitry Andric OtherGD.getCanonicalDecl().getDecl()) && 17560623d748SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 17570623d748SDimitry Andric getDiags().Report(D->getLocation(), 17580623d748SDimitry Andric diag::err_duplicate_mangled_name); 17590623d748SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 17600623d748SDimitry Andric diag::note_previous_definition); 17610623d748SDimitry Andric } 17620623d748SDimitry Andric } 17630623d748SDimitry Andric 17640623d748SDimitry Andric if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 17650623d748SDimitry Andric (Entry->getType()->getElementType() == Ty)) { 1766f22ef01cSRoman Divacky return Entry; 17670623d748SDimitry Andric } 1768f22ef01cSRoman Divacky 1769f22ef01cSRoman Divacky // Make sure the result is of the correct type. 17700623d748SDimitry Andric // (If function is requested for a definition, we always need to create a new 17710623d748SDimitry Andric // function, not just return a bitcast.) 17720623d748SDimitry Andric if (!IsForDefinition) 177317a519f9SDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1774f22ef01cSRoman Divacky } 1775f22ef01cSRoman Divacky 1776f22ef01cSRoman Divacky // This function doesn't have a complete type (for example, the return 1777f22ef01cSRoman Divacky // type is an incomplete struct). Use a fake type instead, and make 1778f22ef01cSRoman Divacky // sure not to try to set attributes. 1779f22ef01cSRoman Divacky bool IsIncompleteFunction = false; 1780f22ef01cSRoman Divacky 17816122f3e6SDimitry Andric llvm::FunctionType *FTy; 1782f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(Ty)) { 1783f22ef01cSRoman Divacky FTy = cast<llvm::FunctionType>(Ty); 1784f22ef01cSRoman Divacky } else { 1785bd5abe19SDimitry Andric FTy = llvm::FunctionType::get(VoidTy, false); 1786f22ef01cSRoman Divacky IsIncompleteFunction = true; 1787f22ef01cSRoman Divacky } 1788ffd1746dSEd Schouten 17890623d748SDimitry Andric llvm::Function *F = 17900623d748SDimitry Andric llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 17910623d748SDimitry Andric Entry ? StringRef() : MangledName, &getModule()); 17920623d748SDimitry Andric 17930623d748SDimitry Andric // If we already created a function with the same mangled name (but different 17940623d748SDimitry Andric // type) before, take its name and add it to the list of functions to be 17950623d748SDimitry Andric // replaced with F at the end of CodeGen. 17960623d748SDimitry Andric // 17970623d748SDimitry Andric // This happens if there is a prototype for a function (e.g. "int f()") and 17980623d748SDimitry Andric // then a definition of a different type (e.g. "int f(int x)"). 17990623d748SDimitry Andric if (Entry) { 18000623d748SDimitry Andric F->takeName(Entry); 18010623d748SDimitry Andric 18020623d748SDimitry Andric // This might be an implementation of a function without a prototype, in 18030623d748SDimitry Andric // which case, try to do special replacement of calls which match the new 18040623d748SDimitry Andric // prototype. The really key thing here is that we also potentially drop 18050623d748SDimitry Andric // arguments from the call site so as to make a direct call, which makes the 18060623d748SDimitry Andric // inliner happier and suppresses a number of optimizer warnings (!) about 18070623d748SDimitry Andric // dropping arguments. 18080623d748SDimitry Andric if (!Entry->use_empty()) { 18090623d748SDimitry Andric ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 18100623d748SDimitry Andric Entry->removeDeadConstantUsers(); 18110623d748SDimitry Andric } 18120623d748SDimitry Andric 18130623d748SDimitry Andric llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 18140623d748SDimitry Andric F, Entry->getType()->getElementType()->getPointerTo()); 18150623d748SDimitry Andric addGlobalValReplacement(Entry, BC); 18160623d748SDimitry Andric } 18170623d748SDimitry Andric 1818f22ef01cSRoman Divacky assert(F->getName() == MangledName && "name was uniqued!"); 1819f785676fSDimitry Andric if (D) 182039d628a0SDimitry Andric SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 1821139f7f9bSDimitry Andric if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) { 1822139f7f9bSDimitry Andric llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex); 1823139f7f9bSDimitry Andric F->addAttributes(llvm::AttributeSet::FunctionIndex, 1824139f7f9bSDimitry Andric llvm::AttributeSet::get(VMContext, 1825139f7f9bSDimitry Andric llvm::AttributeSet::FunctionIndex, 1826139f7f9bSDimitry Andric B)); 1827139f7f9bSDimitry Andric } 1828f22ef01cSRoman Divacky 182959d1ed5bSDimitry Andric if (!DontDefer) { 183059d1ed5bSDimitry Andric // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 183159d1ed5bSDimitry Andric // each other bottoming out with the base dtor. Therefore we emit non-base 183259d1ed5bSDimitry Andric // dtors on usage, even if there is no dtor definition in the TU. 183359d1ed5bSDimitry Andric if (D && isa<CXXDestructorDecl>(D) && 183459d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 183559d1ed5bSDimitry Andric GD.getDtorType())) 183659d1ed5bSDimitry Andric addDeferredDeclToEmit(F, GD); 183759d1ed5bSDimitry Andric 1838f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 1839f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 1840f22ef01cSRoman Divacky // of the file. 184159d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 1842f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 184359d1ed5bSDimitry Andric // Move the potentially referenced deferred decl to the 184459d1ed5bSDimitry Andric // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 184559d1ed5bSDimitry Andric // don't need it anymore). 184659d1ed5bSDimitry Andric addDeferredDeclToEmit(F, DDI->second); 1847f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 18482754fe60SDimitry Andric 18492754fe60SDimitry Andric // Otherwise, there are cases we have to worry about where we're 18502754fe60SDimitry Andric // using a declaration for which we must emit a definition but where 18512754fe60SDimitry Andric // we might not find a top-level definition: 18522754fe60SDimitry Andric // - member functions defined inline in their classes 18532754fe60SDimitry Andric // - friend functions defined inline in some class 18542754fe60SDimitry Andric // - special member functions with implicit definitions 18552754fe60SDimitry Andric // If we ever change our AST traversal to walk into class methods, 18562754fe60SDimitry Andric // this will be unnecessary. 18572754fe60SDimitry Andric // 185859d1ed5bSDimitry Andric // We also don't emit a definition for a function if it's going to be an 185939d628a0SDimitry Andric // entry in a vtable, unless it's already marked as used. 1860f785676fSDimitry Andric } else if (getLangOpts().CPlusPlus && D) { 18612754fe60SDimitry Andric // Look for a declaration that's lexically in a record. 186239d628a0SDimitry Andric for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 186339d628a0SDimitry Andric FD = FD->getPreviousDecl()) { 18642754fe60SDimitry Andric if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 186539d628a0SDimitry Andric if (FD->doesThisDeclarationHaveABody()) { 186659d1ed5bSDimitry Andric addDeferredDeclToEmit(F, GD.getWithDecl(FD)); 18672754fe60SDimitry Andric break; 1868f22ef01cSRoman Divacky } 1869f22ef01cSRoman Divacky } 187039d628a0SDimitry Andric } 1871f22ef01cSRoman Divacky } 187259d1ed5bSDimitry Andric } 1873f22ef01cSRoman Divacky 1874f22ef01cSRoman Divacky // Make sure the result is of the requested type. 1875f22ef01cSRoman Divacky if (!IsIncompleteFunction) { 1876f22ef01cSRoman Divacky assert(F->getType()->getElementType() == Ty); 1877f22ef01cSRoman Divacky return F; 1878f22ef01cSRoman Divacky } 1879f22ef01cSRoman Divacky 188017a519f9SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1881f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(F, PTy); 1882f22ef01cSRoman Divacky } 1883f22ef01cSRoman Divacky 1884f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function. If Ty is 1885f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to 1886f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function). 1887f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 18886122f3e6SDimitry Andric llvm::Type *Ty, 188959d1ed5bSDimitry Andric bool ForVTable, 18900623d748SDimitry Andric bool DontDefer, 18910623d748SDimitry Andric bool IsForDefinition) { 1892f22ef01cSRoman Divacky // If there was no specific requested type, just convert it now. 18930623d748SDimitry Andric if (!Ty) { 18940623d748SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 18950623d748SDimitry Andric auto CanonTy = Context.getCanonicalType(FD->getType()); 18960623d748SDimitry Andric Ty = getTypes().ConvertFunctionType(CanonTy, FD); 18970623d748SDimitry Andric } 1898ffd1746dSEd Schouten 18996122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 19000623d748SDimitry Andric return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 19010623d748SDimitry Andric /*IsThunk=*/false, llvm::AttributeSet(), 19020623d748SDimitry Andric IsForDefinition); 1903f22ef01cSRoman Divacky } 1904f22ef01cSRoman Divacky 1905f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified 1906f22ef01cSRoman Divacky /// type and name. 1907f22ef01cSRoman Divacky llvm::Constant * 19086122f3e6SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 19096122f3e6SDimitry Andric StringRef Name, 1910139f7f9bSDimitry Andric llvm::AttributeSet ExtraAttrs) { 191159d1ed5bSDimitry Andric llvm::Constant *C = 191259d1ed5bSDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 191339d628a0SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 191459d1ed5bSDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) 1915139f7f9bSDimitry Andric if (F->empty()) 1916139f7f9bSDimitry Andric F->setCallingConv(getRuntimeCC()); 1917139f7f9bSDimitry Andric return C; 1918f22ef01cSRoman Divacky } 1919f22ef01cSRoman Divacky 192039d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified 192139d628a0SDimitry Andric /// type and name. 192239d628a0SDimitry Andric llvm::Constant * 192339d628a0SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, 192439d628a0SDimitry Andric StringRef Name, 192539d628a0SDimitry Andric llvm::AttributeSet ExtraAttrs) { 192639d628a0SDimitry Andric llvm::Constant *C = 192739d628a0SDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 192839d628a0SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 192939d628a0SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) 193039d628a0SDimitry Andric if (F->empty()) 193139d628a0SDimitry Andric F->setCallingConv(getBuiltinCC()); 193239d628a0SDimitry Andric return C; 193339d628a0SDimitry Andric } 193439d628a0SDimitry Andric 1935dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted 1936dff0c46cSDimitry Andric /// as a constant. 1937dff0c46cSDimitry Andric /// 1938dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs 1939dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is 1940dff0c46cSDimitry Andric /// not written to during its construction. 1941dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 1942dff0c46cSDimitry Andric if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 1943f22ef01cSRoman Divacky return false; 1944bd5abe19SDimitry Andric 1945dff0c46cSDimitry Andric if (Context.getLangOpts().CPlusPlus) { 1946dff0c46cSDimitry Andric if (const CXXRecordDecl *Record 1947dff0c46cSDimitry Andric = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 1948dff0c46cSDimitry Andric return ExcludeCtor && !Record->hasMutableFields() && 1949dff0c46cSDimitry Andric Record->hasTrivialDestructor(); 1950f22ef01cSRoman Divacky } 1951bd5abe19SDimitry Andric 1952f22ef01cSRoman Divacky return true; 1953f22ef01cSRoman Divacky } 1954f22ef01cSRoman Divacky 1955f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 1956f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type. If there 1957f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 1958f22ef01cSRoman Divacky /// bitcasted to the right type. 1959f22ef01cSRoman Divacky /// 1960f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 1961f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created. 1962f22ef01cSRoman Divacky llvm::Constant * 19636122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 19646122f3e6SDimitry Andric llvm::PointerType *Ty, 196559d1ed5bSDimitry Andric const VarDecl *D) { 1966f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 1967f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1968f22ef01cSRoman Divacky if (Entry) { 19693861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 1970f22ef01cSRoman Divacky if (D && !D->hasAttr<WeakAttr>()) 1971f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 1972f22ef01cSRoman Divacky } 1973f22ef01cSRoman Divacky 197439d628a0SDimitry Andric // Handle dropped DLL attributes. 197539d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 197639d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 197739d628a0SDimitry Andric 1978f22ef01cSRoman Divacky if (Entry->getType() == Ty) 1979f22ef01cSRoman Divacky return Entry; 1980f22ef01cSRoman Divacky 1981f22ef01cSRoman Divacky // Make sure the result is of the correct type. 1982f785676fSDimitry Andric if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 1983f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 1984f785676fSDimitry Andric 1985f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(Entry, Ty); 1986f22ef01cSRoman Divacky } 1987f22ef01cSRoman Divacky 198859d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 198959d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 199059d1ed5bSDimitry Andric getModule(), Ty->getElementType(), false, 199159d1ed5bSDimitry Andric llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 199259d1ed5bSDimitry Andric llvm::GlobalVariable::NotThreadLocal, AddrSpace); 199359d1ed5bSDimitry Andric 1994f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 1995f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 1996f22ef01cSRoman Divacky // of the file. 199759d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 1998f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 1999f22ef01cSRoman Divacky // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 2000f22ef01cSRoman Divacky // list, and remove it from DeferredDecls (since we don't need it anymore). 200159d1ed5bSDimitry Andric addDeferredDeclToEmit(GV, DDI->second); 2002f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 2003f22ef01cSRoman Divacky } 2004f22ef01cSRoman Divacky 2005f22ef01cSRoman Divacky // Handle things which are present even on external declarations. 2006f22ef01cSRoman Divacky if (D) { 2007f22ef01cSRoman Divacky // FIXME: This code is overly simple and should be merged with other global 2008f22ef01cSRoman Divacky // handling. 2009dff0c46cSDimitry Andric GV->setConstant(isTypeConstant(D->getType(), false)); 2010f22ef01cSRoman Divacky 201133956c43SDimitry Andric GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 201233956c43SDimitry Andric 201359d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(GV, D); 20142754fe60SDimitry Andric 2015284c1978SDimitry Andric if (D->getTLSKind()) { 2016284c1978SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 20170623d748SDimitry Andric CXXThreadLocals.push_back(D); 20187ae0e2c9SDimitry Andric setTLSMode(GV, *D); 2019f22ef01cSRoman Divacky } 2020f785676fSDimitry Andric 2021f785676fSDimitry Andric // If required by the ABI, treat declarations of static data members with 2022f785676fSDimitry Andric // inline initializers as definitions. 202359d1ed5bSDimitry Andric if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 2024f785676fSDimitry Andric EmitGlobalVarDefinition(D); 2025284c1978SDimitry Andric } 2026f22ef01cSRoman Divacky 202759d1ed5bSDimitry Andric // Handle XCore specific ABI requirements. 202859d1ed5bSDimitry Andric if (getTarget().getTriple().getArch() == llvm::Triple::xcore && 202959d1ed5bSDimitry Andric D->getLanguageLinkage() == CLanguageLinkage && 203059d1ed5bSDimitry Andric D->getType().isConstant(Context) && 203159d1ed5bSDimitry Andric isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 203259d1ed5bSDimitry Andric GV->setSection(".cp.rodata"); 203359d1ed5bSDimitry Andric } 203459d1ed5bSDimitry Andric 20357ae0e2c9SDimitry Andric if (AddrSpace != Ty->getAddressSpace()) 2036f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty); 2037f785676fSDimitry Andric 2038f22ef01cSRoman Divacky return GV; 2039f22ef01cSRoman Divacky } 2040f22ef01cSRoman Divacky 20410623d748SDimitry Andric llvm::Constant * 20420623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, 20430623d748SDimitry Andric bool IsForDefinition) { 20440623d748SDimitry Andric if (isa<CXXConstructorDecl>(GD.getDecl())) 20450623d748SDimitry Andric return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()), 20460623d748SDimitry Andric getFromCtorType(GD.getCtorType()), 20470623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 20480623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 20490623d748SDimitry Andric else if (isa<CXXDestructorDecl>(GD.getDecl())) 20500623d748SDimitry Andric return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()), 20510623d748SDimitry Andric getFromDtorType(GD.getDtorType()), 20520623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 20530623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 20540623d748SDimitry Andric else if (isa<CXXMethodDecl>(GD.getDecl())) { 20550623d748SDimitry Andric auto FInfo = &getTypes().arrangeCXXMethodDeclaration( 20560623d748SDimitry Andric cast<CXXMethodDecl>(GD.getDecl())); 20570623d748SDimitry Andric auto Ty = getTypes().GetFunctionType(*FInfo); 20580623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 20590623d748SDimitry Andric IsForDefinition); 20600623d748SDimitry Andric } else if (isa<FunctionDecl>(GD.getDecl())) { 20610623d748SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 20620623d748SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 20630623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 20640623d748SDimitry Andric IsForDefinition); 20650623d748SDimitry Andric } else 20660623d748SDimitry Andric return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl())); 20670623d748SDimitry Andric } 2068f22ef01cSRoman Divacky 20692754fe60SDimitry Andric llvm::GlobalVariable * 20706122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 20716122f3e6SDimitry Andric llvm::Type *Ty, 20722754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage) { 20732754fe60SDimitry Andric llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 207459d1ed5bSDimitry Andric llvm::GlobalVariable *OldGV = nullptr; 20752754fe60SDimitry Andric 20762754fe60SDimitry Andric if (GV) { 20772754fe60SDimitry Andric // Check if the variable has the right type. 20782754fe60SDimitry Andric if (GV->getType()->getElementType() == Ty) 20792754fe60SDimitry Andric return GV; 20802754fe60SDimitry Andric 20812754fe60SDimitry Andric // Because C++ name mangling, the only way we can end up with an already 20822754fe60SDimitry Andric // existing global with the same name is if it has been declared extern "C". 20832754fe60SDimitry Andric assert(GV->isDeclaration() && "Declaration has wrong type!"); 20842754fe60SDimitry Andric OldGV = GV; 20852754fe60SDimitry Andric } 20862754fe60SDimitry Andric 20872754fe60SDimitry Andric // Create a new variable. 20882754fe60SDimitry Andric GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 208959d1ed5bSDimitry Andric Linkage, nullptr, Name); 20902754fe60SDimitry Andric 20912754fe60SDimitry Andric if (OldGV) { 20922754fe60SDimitry Andric // Replace occurrences of the old variable if needed. 20932754fe60SDimitry Andric GV->takeName(OldGV); 20942754fe60SDimitry Andric 20952754fe60SDimitry Andric if (!OldGV->use_empty()) { 20962754fe60SDimitry Andric llvm::Constant *NewPtrForOldDecl = 20972754fe60SDimitry Andric llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 20982754fe60SDimitry Andric OldGV->replaceAllUsesWith(NewPtrForOldDecl); 20992754fe60SDimitry Andric } 21002754fe60SDimitry Andric 21012754fe60SDimitry Andric OldGV->eraseFromParent(); 21022754fe60SDimitry Andric } 21032754fe60SDimitry Andric 210433956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker() && 210533956c43SDimitry Andric !GV->hasAvailableExternallyLinkage()) 210633956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 210733956c43SDimitry Andric 21082754fe60SDimitry Andric return GV; 21092754fe60SDimitry Andric } 21102754fe60SDimitry Andric 2111f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 2112f22ef01cSRoman Divacky /// given global variable. If Ty is non-null and if the global doesn't exist, 2113cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the 2114f22ef01cSRoman Divacky /// normal requested type would be. 2115f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 21166122f3e6SDimitry Andric llvm::Type *Ty) { 2117f22ef01cSRoman Divacky assert(D->hasGlobalStorage() && "Not a global variable"); 2118f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 211959d1ed5bSDimitry Andric if (!Ty) 2120f22ef01cSRoman Divacky Ty = getTypes().ConvertTypeForMem(ASTTy); 2121f22ef01cSRoman Divacky 21226122f3e6SDimitry Andric llvm::PointerType *PTy = 21233b0f4066SDimitry Andric llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 2124f22ef01cSRoman Divacky 21256122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2126f22ef01cSRoman Divacky return GetOrCreateLLVMGlobal(MangledName, PTy, D); 2127f22ef01cSRoman Divacky } 2128f22ef01cSRoman Divacky 2129f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the 2130f22ef01cSRoman Divacky /// specified type and name. 2131f22ef01cSRoman Divacky llvm::Constant * 21326122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 21336122f3e6SDimitry Andric StringRef Name) { 213459d1ed5bSDimitry Andric return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr); 2135f22ef01cSRoman Divacky } 2136f22ef01cSRoman Divacky 2137f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 2138f22ef01cSRoman Divacky assert(!D->getInit() && "Cannot emit definite definitions here!"); 2139f22ef01cSRoman Divacky 214039d628a0SDimitry Andric if (!MustBeEmitted(D)) { 2141f22ef01cSRoman Divacky // If we have not seen a reference to this variable yet, place it 2142f22ef01cSRoman Divacky // into the deferred declarations table to be emitted if needed 2143f22ef01cSRoman Divacky // later. 21446122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2145f22ef01cSRoman Divacky if (!GetGlobalValue(MangledName)) { 2146f22ef01cSRoman Divacky DeferredDecls[MangledName] = D; 2147f22ef01cSRoman Divacky return; 2148f22ef01cSRoman Divacky } 2149f22ef01cSRoman Divacky } 2150f22ef01cSRoman Divacky 2151f22ef01cSRoman Divacky // The tentative definition is the only definition. 2152f22ef01cSRoman Divacky EmitGlobalVarDefinition(D); 2153f22ef01cSRoman Divacky } 2154f22ef01cSRoman Divacky 21556122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 21562754fe60SDimitry Andric return Context.toCharUnitsFromBits( 21570623d748SDimitry Andric getDataLayout().getTypeStoreSizeInBits(Ty)); 2158f22ef01cSRoman Divacky } 2159f22ef01cSRoman Divacky 21607ae0e2c9SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 21617ae0e2c9SDimitry Andric unsigned AddrSpace) { 216233956c43SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 21637ae0e2c9SDimitry Andric if (D->hasAttr<CUDAConstantAttr>()) 21647ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 21657ae0e2c9SDimitry Andric else if (D->hasAttr<CUDASharedAttr>()) 21667ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 21677ae0e2c9SDimitry Andric else 21687ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 21697ae0e2c9SDimitry Andric } 21707ae0e2c9SDimitry Andric 21717ae0e2c9SDimitry Andric return AddrSpace; 21727ae0e2c9SDimitry Andric } 21737ae0e2c9SDimitry Andric 2174284c1978SDimitry Andric template<typename SomeDecl> 2175284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 2176284c1978SDimitry Andric llvm::GlobalValue *GV) { 2177284c1978SDimitry Andric if (!getLangOpts().CPlusPlus) 2178284c1978SDimitry Andric return; 2179284c1978SDimitry Andric 2180284c1978SDimitry Andric // Must have 'used' attribute, or else inline assembly can't rely on 2181284c1978SDimitry Andric // the name existing. 2182284c1978SDimitry Andric if (!D->template hasAttr<UsedAttr>()) 2183284c1978SDimitry Andric return; 2184284c1978SDimitry Andric 2185284c1978SDimitry Andric // Must have internal linkage and an ordinary name. 2186f785676fSDimitry Andric if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 2187284c1978SDimitry Andric return; 2188284c1978SDimitry Andric 2189284c1978SDimitry Andric // Must be in an extern "C" context. Entities declared directly within 2190284c1978SDimitry Andric // a record are not extern "C" even if the record is in such a context. 2191f785676fSDimitry Andric const SomeDecl *First = D->getFirstDecl(); 2192284c1978SDimitry Andric if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 2193284c1978SDimitry Andric return; 2194284c1978SDimitry Andric 2195284c1978SDimitry Andric // OK, this is an internal linkage entity inside an extern "C" linkage 2196284c1978SDimitry Andric // specification. Make a note of that so we can give it the "expected" 2197284c1978SDimitry Andric // mangled name if nothing else is using that name. 2198284c1978SDimitry Andric std::pair<StaticExternCMap::iterator, bool> R = 2199284c1978SDimitry Andric StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 2200284c1978SDimitry Andric 2201284c1978SDimitry Andric // If we have multiple internal linkage entities with the same name 2202284c1978SDimitry Andric // in extern "C" regions, none of them gets that name. 2203284c1978SDimitry Andric if (!R.second) 220459d1ed5bSDimitry Andric R.first->second = nullptr; 2205284c1978SDimitry Andric } 2206284c1978SDimitry Andric 220733956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 220833956c43SDimitry Andric if (!CGM.supportsCOMDAT()) 220933956c43SDimitry Andric return false; 221033956c43SDimitry Andric 221133956c43SDimitry Andric if (D.hasAttr<SelectAnyAttr>()) 221233956c43SDimitry Andric return true; 221333956c43SDimitry Andric 221433956c43SDimitry Andric GVALinkage Linkage; 221533956c43SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(&D)) 221633956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 221733956c43SDimitry Andric else 221833956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 221933956c43SDimitry Andric 222033956c43SDimitry Andric switch (Linkage) { 222133956c43SDimitry Andric case GVA_Internal: 222233956c43SDimitry Andric case GVA_AvailableExternally: 222333956c43SDimitry Andric case GVA_StrongExternal: 222433956c43SDimitry Andric return false; 222533956c43SDimitry Andric case GVA_DiscardableODR: 222633956c43SDimitry Andric case GVA_StrongODR: 222733956c43SDimitry Andric return true; 222833956c43SDimitry Andric } 222933956c43SDimitry Andric llvm_unreachable("No such linkage"); 223033956c43SDimitry Andric } 223133956c43SDimitry Andric 223233956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 223333956c43SDimitry Andric llvm::GlobalObject &GO) { 223433956c43SDimitry Andric if (!shouldBeInCOMDAT(*this, D)) 223533956c43SDimitry Andric return; 223633956c43SDimitry Andric GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 223733956c43SDimitry Andric } 223833956c43SDimitry Andric 2239f22ef01cSRoman Divacky void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 224059d1ed5bSDimitry Andric llvm::Constant *Init = nullptr; 2241f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 2242dff0c46cSDimitry Andric CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2243dff0c46cSDimitry Andric bool NeedsGlobalCtor = false; 2244dff0c46cSDimitry Andric bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 2245f22ef01cSRoman Divacky 2246dff0c46cSDimitry Andric const VarDecl *InitDecl; 2247dff0c46cSDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 2248f22ef01cSRoman Divacky 22490623d748SDimitry Andric // CUDA E.2.4.1 "__shared__ variables cannot have an initialization as part 22500623d748SDimitry Andric // of their declaration." 22510623d748SDimitry Andric if (getLangOpts().CPlusPlus && getLangOpts().CUDAIsDevice 22520623d748SDimitry Andric && D->hasAttr<CUDASharedAttr>()) { 22530623d748SDimitry Andric if (InitExpr) { 22540623d748SDimitry Andric const auto *C = dyn_cast<CXXConstructExpr>(InitExpr); 22550623d748SDimitry Andric if (C == nullptr || !C->getConstructor()->hasTrivialBody()) 22560623d748SDimitry Andric Error(D->getLocation(), 22570623d748SDimitry Andric "__shared__ variable cannot have an initialization."); 22580623d748SDimitry Andric } 22590623d748SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 22600623d748SDimitry Andric } else if (!InitExpr) { 2261f22ef01cSRoman Divacky // This is a tentative definition; tentative definitions are 2262f22ef01cSRoman Divacky // implicitly initialized with { 0 }. 2263f22ef01cSRoman Divacky // 2264f22ef01cSRoman Divacky // Note that tentative definitions are only emitted at the end of 2265f22ef01cSRoman Divacky // a translation unit, so they should never have incomplete 2266f22ef01cSRoman Divacky // type. In addition, EmitTentativeDefinition makes sure that we 2267f22ef01cSRoman Divacky // never attempt to emit a tentative definition if a real one 2268f22ef01cSRoman Divacky // exists. A use may still exists, however, so we still may need 2269f22ef01cSRoman Divacky // to do a RAUW. 2270f22ef01cSRoman Divacky assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 2271f22ef01cSRoman Divacky Init = EmitNullConstant(D->getType()); 2272f22ef01cSRoman Divacky } else { 22737ae0e2c9SDimitry Andric initializedGlobalDecl = GlobalDecl(D); 2274dff0c46cSDimitry Andric Init = EmitConstantInit(*InitDecl); 2275f785676fSDimitry Andric 2276f22ef01cSRoman Divacky if (!Init) { 2277f22ef01cSRoman Divacky QualType T = InitExpr->getType(); 2278f22ef01cSRoman Divacky if (D->getType()->isReferenceType()) 2279f22ef01cSRoman Divacky T = D->getType(); 2280f22ef01cSRoman Divacky 2281dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus) { 2282f22ef01cSRoman Divacky Init = EmitNullConstant(T); 2283dff0c46cSDimitry Andric NeedsGlobalCtor = true; 2284f22ef01cSRoman Divacky } else { 2285f22ef01cSRoman Divacky ErrorUnsupported(D, "static initializer"); 2286f22ef01cSRoman Divacky Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 2287f22ef01cSRoman Divacky } 2288e580952dSDimitry Andric } else { 2289e580952dSDimitry Andric // We don't need an initializer, so remove the entry for the delayed 2290dff0c46cSDimitry Andric // initializer position (just in case this entry was delayed) if we 2291dff0c46cSDimitry Andric // also don't need to register a destructor. 2292dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 2293e580952dSDimitry Andric DelayedCXXInitPosition.erase(D); 2294f22ef01cSRoman Divacky } 2295f22ef01cSRoman Divacky } 2296f22ef01cSRoman Divacky 22976122f3e6SDimitry Andric llvm::Type* InitType = Init->getType(); 2298f22ef01cSRoman Divacky llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 2299f22ef01cSRoman Divacky 2300f22ef01cSRoman Divacky // Strip off a bitcast if we got one back. 230159d1ed5bSDimitry Andric if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2302f22ef01cSRoman Divacky assert(CE->getOpcode() == llvm::Instruction::BitCast || 2303f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 2304f785676fSDimitry Andric // All zero index gep. 2305f22ef01cSRoman Divacky CE->getOpcode() == llvm::Instruction::GetElementPtr); 2306f22ef01cSRoman Divacky Entry = CE->getOperand(0); 2307f22ef01cSRoman Divacky } 2308f22ef01cSRoman Divacky 2309f22ef01cSRoman Divacky // Entry is now either a Function or GlobalVariable. 231059d1ed5bSDimitry Andric auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 2311f22ef01cSRoman Divacky 2312f22ef01cSRoman Divacky // We have a definition after a declaration with the wrong type. 2313f22ef01cSRoman Divacky // We must make a new GlobalVariable* and update everything that used OldGV 2314f22ef01cSRoman Divacky // (a declaration or tentative definition) with the new GlobalVariable* 2315f22ef01cSRoman Divacky // (which will be a definition). 2316f22ef01cSRoman Divacky // 2317f22ef01cSRoman Divacky // This happens if there is a prototype for a global (e.g. 2318f22ef01cSRoman Divacky // "extern int x[];") and then a definition of a different type (e.g. 2319f22ef01cSRoman Divacky // "int x[10];"). This also happens when an initializer has a different type 2320f22ef01cSRoman Divacky // from the type of the global (this happens with unions). 232159d1ed5bSDimitry Andric if (!GV || 2322f22ef01cSRoman Divacky GV->getType()->getElementType() != InitType || 23233b0f4066SDimitry Andric GV->getType()->getAddressSpace() != 23247ae0e2c9SDimitry Andric GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 2325f22ef01cSRoman Divacky 2326f22ef01cSRoman Divacky // Move the old entry aside so that we'll create a new one. 23276122f3e6SDimitry Andric Entry->setName(StringRef()); 2328f22ef01cSRoman Divacky 2329f22ef01cSRoman Divacky // Make a new global with the correct type, this is now guaranteed to work. 2330f22ef01cSRoman Divacky GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 2331f22ef01cSRoman Divacky 2332f22ef01cSRoman Divacky // Replace all uses of the old global with the new global 2333f22ef01cSRoman Divacky llvm::Constant *NewPtrForOldDecl = 2334f22ef01cSRoman Divacky llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2335f22ef01cSRoman Divacky Entry->replaceAllUsesWith(NewPtrForOldDecl); 2336f22ef01cSRoman Divacky 2337f22ef01cSRoman Divacky // Erase the old global, since it is no longer used. 2338f22ef01cSRoman Divacky cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 2339f22ef01cSRoman Divacky } 2340f22ef01cSRoman Divacky 2341284c1978SDimitry Andric MaybeHandleStaticInExternC(D, GV); 2342284c1978SDimitry Andric 23436122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 23446122f3e6SDimitry Andric AddGlobalAnnotations(D, GV); 2345f22ef01cSRoman Divacky 23460623d748SDimitry Andric // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 23470623d748SDimitry Andric // the device. [...]" 23480623d748SDimitry Andric // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 23490623d748SDimitry Andric // __device__, declares a variable that: [...] 23500623d748SDimitry Andric // Is accessible from all the threads within the grid and from the host 23510623d748SDimitry Andric // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 23520623d748SDimitry Andric // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 23530623d748SDimitry Andric if (GV && LangOpts.CUDA && LangOpts.CUDAIsDevice && 23540623d748SDimitry Andric (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>())) { 23550623d748SDimitry Andric GV->setExternallyInitialized(true); 23560623d748SDimitry Andric } 2357f22ef01cSRoman Divacky GV->setInitializer(Init); 2358f22ef01cSRoman Divacky 2359f22ef01cSRoman Divacky // If it is safe to mark the global 'constant', do so now. 2360dff0c46cSDimitry Andric GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 2361dff0c46cSDimitry Andric isTypeConstant(D->getType(), true)); 2362f22ef01cSRoman Divacky 236339d628a0SDimitry Andric // If it is in a read-only section, mark it 'constant'. 236439d628a0SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 236539d628a0SDimitry Andric const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 236639d628a0SDimitry Andric if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 236739d628a0SDimitry Andric GV->setConstant(true); 236839d628a0SDimitry Andric } 236939d628a0SDimitry Andric 2370f22ef01cSRoman Divacky GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 2371f22ef01cSRoman Divacky 2372f22ef01cSRoman Divacky // Set the llvm linkage type as appropriate. 23732754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 237459d1ed5bSDimitry Andric getLLVMLinkageVarDefinition(D, GV->isConstant()); 2375f785676fSDimitry Andric 23760623d748SDimitry Andric // On Darwin, if the normal linkage of a C++ thread_local variable is 23770623d748SDimitry Andric // LinkOnce or Weak, we keep the normal linkage to prevent multiple 23780623d748SDimitry Andric // copies within a linkage unit; otherwise, the backing variable has 23790623d748SDimitry Andric // internal linkage and all accesses should just be calls to the 238059d1ed5bSDimitry Andric // Itanium-specified entry point, which has the normal linkage of the 23810623d748SDimitry Andric // variable. This is to preserve the ability to change the implementation 23820623d748SDimitry Andric // behind the scenes. 238339d628a0SDimitry Andric if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic && 23840623d748SDimitry Andric Context.getTargetInfo().getTriple().isOSDarwin() && 23850623d748SDimitry Andric !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) && 23860623d748SDimitry Andric !llvm::GlobalVariable::isWeakLinkage(Linkage)) 238759d1ed5bSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 238859d1ed5bSDimitry Andric 238959d1ed5bSDimitry Andric GV->setLinkage(Linkage); 239059d1ed5bSDimitry Andric if (D->hasAttr<DLLImportAttr>()) 239159d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 239259d1ed5bSDimitry Andric else if (D->hasAttr<DLLExportAttr>()) 239359d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 239439d628a0SDimitry Andric else 239539d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 2396f785676fSDimitry Andric 23972754fe60SDimitry Andric if (Linkage == llvm::GlobalVariable::CommonLinkage) 2398f22ef01cSRoman Divacky // common vars aren't constant even if declared const. 2399f22ef01cSRoman Divacky GV->setConstant(false); 2400f22ef01cSRoman Divacky 240159d1ed5bSDimitry Andric setNonAliasAttributes(D, GV); 2402f22ef01cSRoman Divacky 240339d628a0SDimitry Andric if (D->getTLSKind() && !GV->isThreadLocal()) { 240439d628a0SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 24050623d748SDimitry Andric CXXThreadLocals.push_back(D); 240639d628a0SDimitry Andric setTLSMode(GV, *D); 240739d628a0SDimitry Andric } 240839d628a0SDimitry Andric 240933956c43SDimitry Andric maybeSetTrivialComdat(*D, *GV); 241033956c43SDimitry Andric 24112754fe60SDimitry Andric // Emit the initializer function if necessary. 2412dff0c46cSDimitry Andric if (NeedsGlobalCtor || NeedsGlobalDtor) 2413dff0c46cSDimitry Andric EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 24142754fe60SDimitry Andric 241539d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 24163861d79fSDimitry Andric 2417f22ef01cSRoman Divacky // Emit global variable debug information. 24186122f3e6SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 24193861d79fSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 2420f22ef01cSRoman Divacky DI->EmitGlobalVariable(GV, D); 2421f22ef01cSRoman Divacky } 2422f22ef01cSRoman Divacky 242339d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context, 242433956c43SDimitry Andric CodeGenModule &CGM, const VarDecl *D, 242533956c43SDimitry Andric bool NoCommon) { 242659d1ed5bSDimitry Andric // Don't give variables common linkage if -fno-common was specified unless it 242759d1ed5bSDimitry Andric // was overridden by a NoCommon attribute. 242859d1ed5bSDimitry Andric if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 242959d1ed5bSDimitry Andric return true; 243059d1ed5bSDimitry Andric 243159d1ed5bSDimitry Andric // C11 6.9.2/2: 243259d1ed5bSDimitry Andric // A declaration of an identifier for an object that has file scope without 243359d1ed5bSDimitry Andric // an initializer, and without a storage-class specifier or with the 243459d1ed5bSDimitry Andric // storage-class specifier static, constitutes a tentative definition. 243559d1ed5bSDimitry Andric if (D->getInit() || D->hasExternalStorage()) 243659d1ed5bSDimitry Andric return true; 243759d1ed5bSDimitry Andric 243859d1ed5bSDimitry Andric // A variable cannot be both common and exist in a section. 243959d1ed5bSDimitry Andric if (D->hasAttr<SectionAttr>()) 244059d1ed5bSDimitry Andric return true; 244159d1ed5bSDimitry Andric 244259d1ed5bSDimitry Andric // Thread local vars aren't considered common linkage. 244359d1ed5bSDimitry Andric if (D->getTLSKind()) 244459d1ed5bSDimitry Andric return true; 244559d1ed5bSDimitry Andric 244659d1ed5bSDimitry Andric // Tentative definitions marked with WeakImportAttr are true definitions. 244759d1ed5bSDimitry Andric if (D->hasAttr<WeakImportAttr>()) 244859d1ed5bSDimitry Andric return true; 244959d1ed5bSDimitry Andric 245033956c43SDimitry Andric // A variable cannot be both common and exist in a comdat. 245133956c43SDimitry Andric if (shouldBeInCOMDAT(CGM, *D)) 245233956c43SDimitry Andric return true; 245333956c43SDimitry Andric 245439d628a0SDimitry Andric // Declarations with a required alignment do not have common linakge in MSVC 245539d628a0SDimitry Andric // mode. 24560623d748SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 245733956c43SDimitry Andric if (D->hasAttr<AlignedAttr>()) 245839d628a0SDimitry Andric return true; 245933956c43SDimitry Andric QualType VarType = D->getType(); 246033956c43SDimitry Andric if (Context.isAlignmentRequired(VarType)) 246133956c43SDimitry Andric return true; 246233956c43SDimitry Andric 246333956c43SDimitry Andric if (const auto *RT = VarType->getAs<RecordType>()) { 246433956c43SDimitry Andric const RecordDecl *RD = RT->getDecl(); 246533956c43SDimitry Andric for (const FieldDecl *FD : RD->fields()) { 246633956c43SDimitry Andric if (FD->isBitField()) 246733956c43SDimitry Andric continue; 246833956c43SDimitry Andric if (FD->hasAttr<AlignedAttr>()) 246933956c43SDimitry Andric return true; 247033956c43SDimitry Andric if (Context.isAlignmentRequired(FD->getType())) 247133956c43SDimitry Andric return true; 247233956c43SDimitry Andric } 247333956c43SDimitry Andric } 247433956c43SDimitry Andric } 247539d628a0SDimitry Andric 247659d1ed5bSDimitry Andric return false; 247759d1ed5bSDimitry Andric } 247859d1ed5bSDimitry Andric 247959d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 248059d1ed5bSDimitry Andric const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 24812754fe60SDimitry Andric if (Linkage == GVA_Internal) 24822754fe60SDimitry Andric return llvm::Function::InternalLinkage; 248359d1ed5bSDimitry Andric 248459d1ed5bSDimitry Andric if (D->hasAttr<WeakAttr>()) { 248559d1ed5bSDimitry Andric if (IsConstantVariable) 248659d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 248759d1ed5bSDimitry Andric else 248859d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakAnyLinkage; 248959d1ed5bSDimitry Andric } 249059d1ed5bSDimitry Andric 249159d1ed5bSDimitry Andric // We are guaranteed to have a strong definition somewhere else, 249259d1ed5bSDimitry Andric // so we can use available_externally linkage. 249359d1ed5bSDimitry Andric if (Linkage == GVA_AvailableExternally) 249459d1ed5bSDimitry Andric return llvm::Function::AvailableExternallyLinkage; 249559d1ed5bSDimitry Andric 249659d1ed5bSDimitry Andric // Note that Apple's kernel linker doesn't support symbol 249759d1ed5bSDimitry Andric // coalescing, so we need to avoid linkonce and weak linkages there. 249859d1ed5bSDimitry Andric // Normally, this means we just map to internal, but for explicit 249959d1ed5bSDimitry Andric // instantiations we'll map to external. 250059d1ed5bSDimitry Andric 250159d1ed5bSDimitry Andric // In C++, the compiler has to emit a definition in every translation unit 250259d1ed5bSDimitry Andric // that references the function. We should use linkonce_odr because 250359d1ed5bSDimitry Andric // a) if all references in this translation unit are optimized away, we 250459d1ed5bSDimitry Andric // don't need to codegen it. b) if the function persists, it needs to be 250559d1ed5bSDimitry Andric // merged with other definitions. c) C++ has the ODR, so we know the 250659d1ed5bSDimitry Andric // definition is dependable. 250759d1ed5bSDimitry Andric if (Linkage == GVA_DiscardableODR) 250859d1ed5bSDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 250959d1ed5bSDimitry Andric : llvm::Function::InternalLinkage; 251059d1ed5bSDimitry Andric 251159d1ed5bSDimitry Andric // An explicit instantiation of a template has weak linkage, since 251259d1ed5bSDimitry Andric // explicit instantiations can occur in multiple translation units 251359d1ed5bSDimitry Andric // and must all be equivalent. However, we are not allowed to 251459d1ed5bSDimitry Andric // throw away these explicit instantiations. 251559d1ed5bSDimitry Andric if (Linkage == GVA_StrongODR) 251659d1ed5bSDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage 251759d1ed5bSDimitry Andric : llvm::Function::ExternalLinkage; 251859d1ed5bSDimitry Andric 251959d1ed5bSDimitry Andric // C++ doesn't have tentative definitions and thus cannot have common 252059d1ed5bSDimitry Andric // linkage. 252159d1ed5bSDimitry Andric if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 252233956c43SDimitry Andric !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 252339d628a0SDimitry Andric CodeGenOpts.NoCommon)) 252459d1ed5bSDimitry Andric return llvm::GlobalVariable::CommonLinkage; 252559d1ed5bSDimitry Andric 2526f785676fSDimitry Andric // selectany symbols are externally visible, so use weak instead of 2527f785676fSDimitry Andric // linkonce. MSVC optimizes away references to const selectany globals, so 2528f785676fSDimitry Andric // all definitions should be the same and ODR linkage should be used. 2529f785676fSDimitry Andric // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 253059d1ed5bSDimitry Andric if (D->hasAttr<SelectAnyAttr>()) 2531f785676fSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 253259d1ed5bSDimitry Andric 253359d1ed5bSDimitry Andric // Otherwise, we have strong external linkage. 253459d1ed5bSDimitry Andric assert(Linkage == GVA_StrongExternal); 25352754fe60SDimitry Andric return llvm::GlobalVariable::ExternalLinkage; 25362754fe60SDimitry Andric } 25372754fe60SDimitry Andric 253859d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 253959d1ed5bSDimitry Andric const VarDecl *VD, bool IsConstant) { 254059d1ed5bSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 254159d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 254259d1ed5bSDimitry Andric } 254359d1ed5bSDimitry Andric 2544139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type. 2545139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites 2546139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 2547139f7f9bSDimitry Andric llvm::Function *newFn) { 2548139f7f9bSDimitry Andric // Fast path. 2549139f7f9bSDimitry Andric if (old->use_empty()) return; 2550139f7f9bSDimitry Andric 2551139f7f9bSDimitry Andric llvm::Type *newRetTy = newFn->getReturnType(); 2552139f7f9bSDimitry Andric SmallVector<llvm::Value*, 4> newArgs; 25530623d748SDimitry Andric SmallVector<llvm::OperandBundleDef, 1> newBundles; 2554139f7f9bSDimitry Andric 2555139f7f9bSDimitry Andric for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 2556139f7f9bSDimitry Andric ui != ue; ) { 2557139f7f9bSDimitry Andric llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 255859d1ed5bSDimitry Andric llvm::User *user = use->getUser(); 2559139f7f9bSDimitry Andric 2560139f7f9bSDimitry Andric // Recognize and replace uses of bitcasts. Most calls to 2561139f7f9bSDimitry Andric // unprototyped functions will use bitcasts. 256259d1ed5bSDimitry Andric if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 2563139f7f9bSDimitry Andric if (bitcast->getOpcode() == llvm::Instruction::BitCast) 2564139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(bitcast, newFn); 2565139f7f9bSDimitry Andric continue; 2566139f7f9bSDimitry Andric } 2567139f7f9bSDimitry Andric 2568139f7f9bSDimitry Andric // Recognize calls to the function. 2569139f7f9bSDimitry Andric llvm::CallSite callSite(user); 2570139f7f9bSDimitry Andric if (!callSite) continue; 257159d1ed5bSDimitry Andric if (!callSite.isCallee(&*use)) continue; 2572139f7f9bSDimitry Andric 2573139f7f9bSDimitry Andric // If the return types don't match exactly, then we can't 2574139f7f9bSDimitry Andric // transform this call unless it's dead. 2575139f7f9bSDimitry Andric if (callSite->getType() != newRetTy && !callSite->use_empty()) 2576139f7f9bSDimitry Andric continue; 2577139f7f9bSDimitry Andric 2578139f7f9bSDimitry Andric // Get the call site's attribute list. 2579139f7f9bSDimitry Andric SmallVector<llvm::AttributeSet, 8> newAttrs; 2580139f7f9bSDimitry Andric llvm::AttributeSet oldAttrs = callSite.getAttributes(); 2581139f7f9bSDimitry Andric 2582139f7f9bSDimitry Andric // Collect any return attributes from the call. 2583139f7f9bSDimitry Andric if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex)) 2584139f7f9bSDimitry Andric newAttrs.push_back( 2585139f7f9bSDimitry Andric llvm::AttributeSet::get(newFn->getContext(), 2586139f7f9bSDimitry Andric oldAttrs.getRetAttributes())); 2587139f7f9bSDimitry Andric 2588139f7f9bSDimitry Andric // If the function was passed too few arguments, don't transform. 2589139f7f9bSDimitry Andric unsigned newNumArgs = newFn->arg_size(); 2590139f7f9bSDimitry Andric if (callSite.arg_size() < newNumArgs) continue; 2591139f7f9bSDimitry Andric 2592139f7f9bSDimitry Andric // If extra arguments were passed, we silently drop them. 2593139f7f9bSDimitry Andric // If any of the types mismatch, we don't transform. 2594139f7f9bSDimitry Andric unsigned argNo = 0; 2595139f7f9bSDimitry Andric bool dontTransform = false; 2596139f7f9bSDimitry Andric for (llvm::Function::arg_iterator ai = newFn->arg_begin(), 2597139f7f9bSDimitry Andric ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) { 2598139f7f9bSDimitry Andric if (callSite.getArgument(argNo)->getType() != ai->getType()) { 2599139f7f9bSDimitry Andric dontTransform = true; 2600139f7f9bSDimitry Andric break; 2601139f7f9bSDimitry Andric } 2602139f7f9bSDimitry Andric 2603139f7f9bSDimitry Andric // Add any parameter attributes. 2604139f7f9bSDimitry Andric if (oldAttrs.hasAttributes(argNo + 1)) 2605139f7f9bSDimitry Andric newAttrs. 2606139f7f9bSDimitry Andric push_back(llvm:: 2607139f7f9bSDimitry Andric AttributeSet::get(newFn->getContext(), 2608139f7f9bSDimitry Andric oldAttrs.getParamAttributes(argNo + 1))); 2609139f7f9bSDimitry Andric } 2610139f7f9bSDimitry Andric if (dontTransform) 2611139f7f9bSDimitry Andric continue; 2612139f7f9bSDimitry Andric 2613139f7f9bSDimitry Andric if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) 2614139f7f9bSDimitry Andric newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(), 2615139f7f9bSDimitry Andric oldAttrs.getFnAttributes())); 2616139f7f9bSDimitry Andric 2617139f7f9bSDimitry Andric // Okay, we can transform this. Create the new call instruction and copy 2618139f7f9bSDimitry Andric // over the required information. 2619139f7f9bSDimitry Andric newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 2620139f7f9bSDimitry Andric 26210623d748SDimitry Andric // Copy over any operand bundles. 26220623d748SDimitry Andric callSite.getOperandBundlesAsDefs(newBundles); 26230623d748SDimitry Andric 2624139f7f9bSDimitry Andric llvm::CallSite newCall; 2625139f7f9bSDimitry Andric if (callSite.isCall()) { 26260623d748SDimitry Andric newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "", 2627139f7f9bSDimitry Andric callSite.getInstruction()); 2628139f7f9bSDimitry Andric } else { 262959d1ed5bSDimitry Andric auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction()); 2630139f7f9bSDimitry Andric newCall = llvm::InvokeInst::Create(newFn, 2631139f7f9bSDimitry Andric oldInvoke->getNormalDest(), 2632139f7f9bSDimitry Andric oldInvoke->getUnwindDest(), 26330623d748SDimitry Andric newArgs, newBundles, "", 2634139f7f9bSDimitry Andric callSite.getInstruction()); 2635139f7f9bSDimitry Andric } 2636139f7f9bSDimitry Andric newArgs.clear(); // for the next iteration 2637139f7f9bSDimitry Andric 2638139f7f9bSDimitry Andric if (!newCall->getType()->isVoidTy()) 2639139f7f9bSDimitry Andric newCall->takeName(callSite.getInstruction()); 2640139f7f9bSDimitry Andric newCall.setAttributes( 2641139f7f9bSDimitry Andric llvm::AttributeSet::get(newFn->getContext(), newAttrs)); 2642139f7f9bSDimitry Andric newCall.setCallingConv(callSite.getCallingConv()); 2643139f7f9bSDimitry Andric 2644139f7f9bSDimitry Andric // Finally, remove the old call, replacing any uses with the new one. 2645139f7f9bSDimitry Andric if (!callSite->use_empty()) 2646139f7f9bSDimitry Andric callSite->replaceAllUsesWith(newCall.getInstruction()); 2647139f7f9bSDimitry Andric 2648139f7f9bSDimitry Andric // Copy debug location attached to CI. 264933956c43SDimitry Andric if (callSite->getDebugLoc()) 2650139f7f9bSDimitry Andric newCall->setDebugLoc(callSite->getDebugLoc()); 26510623d748SDimitry Andric 2652139f7f9bSDimitry Andric callSite->eraseFromParent(); 2653139f7f9bSDimitry Andric } 2654139f7f9bSDimitry Andric } 2655139f7f9bSDimitry Andric 2656f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 2657f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}". If there are 2658f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to 2659f22ef01cSRoman Divacky /// call the new function directly. 2660f22ef01cSRoman Divacky /// 2661f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to 2662f22ef01cSRoman Divacky /// functions to be able to inline them. If there is a bitcast in the way, it 2663f22ef01cSRoman Divacky /// won't inline them. Instcombine normally deletes these calls, but it isn't 2664f22ef01cSRoman Divacky /// run at -O0. 2665f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2666f22ef01cSRoman Divacky llvm::Function *NewFn) { 2667f22ef01cSRoman Divacky // If we're redefining a global as a function, don't transform it. 2668139f7f9bSDimitry Andric if (!isa<llvm::Function>(Old)) return; 2669f22ef01cSRoman Divacky 2670139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(Old, NewFn); 2671f22ef01cSRoman Divacky } 2672f22ef01cSRoman Divacky 2673dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 2674dff0c46cSDimitry Andric TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 2675dff0c46cSDimitry Andric // If we have a definition, this might be a deferred decl. If the 2676dff0c46cSDimitry Andric // instantiation is explicit, make sure we emit it at the end. 2677dff0c46cSDimitry Andric if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 2678dff0c46cSDimitry Andric GetAddrOfGlobalVar(VD); 2679139f7f9bSDimitry Andric 2680139f7f9bSDimitry Andric EmitTopLevelDecl(VD); 2681dff0c46cSDimitry Andric } 2682f22ef01cSRoman Divacky 268359d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 268459d1ed5bSDimitry Andric llvm::GlobalValue *GV) { 268559d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 26863b0f4066SDimitry Andric 26873b0f4066SDimitry Andric // Compute the function info and LLVM type. 2688dff0c46cSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2689dff0c46cSDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 26903b0f4066SDimitry Andric 2691f22ef01cSRoman Divacky // Get or create the prototype for the function. 26920623d748SDimitry Andric if (!GV || (GV->getType()->getElementType() != Ty)) 26930623d748SDimitry Andric GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 26940623d748SDimitry Andric /*DontDefer=*/true, 26950623d748SDimitry Andric /*IsForDefinition=*/true)); 2696f22ef01cSRoman Divacky 26970623d748SDimitry Andric // Already emitted. 26980623d748SDimitry Andric if (!GV->isDeclaration()) 2699f785676fSDimitry Andric return; 2700f22ef01cSRoman Divacky 27012754fe60SDimitry Andric // We need to set linkage and visibility on the function before 27022754fe60SDimitry Andric // generating code for it because various parts of IR generation 27032754fe60SDimitry Andric // want to propagate this information down (e.g. to local static 27042754fe60SDimitry Andric // declarations). 270559d1ed5bSDimitry Andric auto *Fn = cast<llvm::Function>(GV); 2706f785676fSDimitry Andric setFunctionLinkage(GD, Fn); 270797bc6c73SDimitry Andric setFunctionDLLStorageClass(GD, Fn); 2708f22ef01cSRoman Divacky 270959d1ed5bSDimitry Andric // FIXME: this is redundant with part of setFunctionDefinitionAttributes 27102754fe60SDimitry Andric setGlobalVisibility(Fn, D); 27112754fe60SDimitry Andric 2712284c1978SDimitry Andric MaybeHandleStaticInExternC(D, Fn); 2713284c1978SDimitry Andric 271433956c43SDimitry Andric maybeSetTrivialComdat(*D, *Fn); 271533956c43SDimitry Andric 27163b0f4066SDimitry Andric CodeGenFunction(*this).GenerateCode(D, Fn, FI); 2717f22ef01cSRoman Divacky 271859d1ed5bSDimitry Andric setFunctionDefinitionAttributes(D, Fn); 2719f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, Fn); 2720f22ef01cSRoman Divacky 2721f22ef01cSRoman Divacky if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 2722f22ef01cSRoman Divacky AddGlobalCtor(Fn, CA->getPriority()); 2723f22ef01cSRoman Divacky if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 2724f22ef01cSRoman Divacky AddGlobalDtor(Fn, DA->getPriority()); 27256122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 27266122f3e6SDimitry Andric AddGlobalAnnotations(D, Fn); 2727f22ef01cSRoman Divacky } 2728f22ef01cSRoman Divacky 2729f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 273059d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 2731f22ef01cSRoman Divacky const AliasAttr *AA = D->getAttr<AliasAttr>(); 2732f22ef01cSRoman Divacky assert(AA && "Not an alias?"); 2733f22ef01cSRoman Divacky 27346122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 2735f22ef01cSRoman Divacky 27369a4b3118SDimitry Andric if (AA->getAliasee() == MangledName) { 27379a4b3118SDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 27389a4b3118SDimitry Andric return; 27399a4b3118SDimitry Andric } 27409a4b3118SDimitry Andric 2741f22ef01cSRoman Divacky // If there is a definition in the module, then it wins over the alias. 2742f22ef01cSRoman Divacky // This is dubious, but allow it to be safe. Just ignore the alias. 2743f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2744f22ef01cSRoman Divacky if (Entry && !Entry->isDeclaration()) 2745f22ef01cSRoman Divacky return; 2746f22ef01cSRoman Divacky 2747f785676fSDimitry Andric Aliases.push_back(GD); 2748f785676fSDimitry Andric 27496122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 2750f22ef01cSRoman Divacky 2751f22ef01cSRoman Divacky // Create a reference to the named value. This ensures that it is emitted 2752f22ef01cSRoman Divacky // if a deferred decl. 2753f22ef01cSRoman Divacky llvm::Constant *Aliasee; 2754f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 27553861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 27562754fe60SDimitry Andric /*ForVTable=*/false); 2757f22ef01cSRoman Divacky else 2758f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 275959d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 276039d628a0SDimitry Andric /*D=*/nullptr); 2761f22ef01cSRoman Divacky 2762f22ef01cSRoman Divacky // Create the new alias itself, but don't set a name yet. 276359d1ed5bSDimitry Andric auto *GA = llvm::GlobalAlias::create( 27640623d748SDimitry Andric DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule()); 2765f22ef01cSRoman Divacky 2766f22ef01cSRoman Divacky if (Entry) { 276759d1ed5bSDimitry Andric if (GA->getAliasee() == Entry) { 276859d1ed5bSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 276959d1ed5bSDimitry Andric return; 277059d1ed5bSDimitry Andric } 277159d1ed5bSDimitry Andric 2772f22ef01cSRoman Divacky assert(Entry->isDeclaration()); 2773f22ef01cSRoman Divacky 2774f22ef01cSRoman Divacky // If there is a declaration in the module, then we had an extern followed 2775f22ef01cSRoman Divacky // by the alias, as in: 2776f22ef01cSRoman Divacky // extern int test6(); 2777f22ef01cSRoman Divacky // ... 2778f22ef01cSRoman Divacky // int test6() __attribute__((alias("test7"))); 2779f22ef01cSRoman Divacky // 2780f22ef01cSRoman Divacky // Remove it and replace uses of it with the alias. 2781f22ef01cSRoman Divacky GA->takeName(Entry); 2782f22ef01cSRoman Divacky 2783f22ef01cSRoman Divacky Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 2784f22ef01cSRoman Divacky Entry->getType())); 2785f22ef01cSRoman Divacky Entry->eraseFromParent(); 2786f22ef01cSRoman Divacky } else { 2787ffd1746dSEd Schouten GA->setName(MangledName); 2788f22ef01cSRoman Divacky } 2789f22ef01cSRoman Divacky 2790f22ef01cSRoman Divacky // Set attributes which are particular to an alias; this is a 2791f22ef01cSRoman Divacky // specialization of the attributes which may be set on a global 2792f22ef01cSRoman Divacky // variable/function. 279339d628a0SDimitry Andric if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 27943b0f4066SDimitry Andric D->isWeakImported()) { 2795f22ef01cSRoman Divacky GA->setLinkage(llvm::Function::WeakAnyLinkage); 2796f22ef01cSRoman Divacky } 2797f22ef01cSRoman Divacky 279839d628a0SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 279939d628a0SDimitry Andric if (VD->getTLSKind()) 280039d628a0SDimitry Andric setTLSMode(GA, *VD); 280139d628a0SDimitry Andric 280239d628a0SDimitry Andric setAliasAttributes(D, GA); 2803f22ef01cSRoman Divacky } 2804f22ef01cSRoman Divacky 280517a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 28066122f3e6SDimitry Andric ArrayRef<llvm::Type*> Tys) { 280717a519f9SDimitry Andric return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 280817a519f9SDimitry Andric Tys); 2809f22ef01cSRoman Divacky } 2810f22ef01cSRoman Divacky 281133956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 281233956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 281333956c43SDimitry Andric const StringLiteral *Literal, bool TargetIsLSB, 281433956c43SDimitry Andric bool &IsUTF16, unsigned &StringLength) { 28156122f3e6SDimitry Andric StringRef String = Literal->getString(); 2816e580952dSDimitry Andric unsigned NumBytes = String.size(); 2817f22ef01cSRoman Divacky 2818f22ef01cSRoman Divacky // Check for simple case. 2819f22ef01cSRoman Divacky if (!Literal->containsNonAsciiOrNull()) { 2820f22ef01cSRoman Divacky StringLength = NumBytes; 282139d628a0SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 2822f22ef01cSRoman Divacky } 2823f22ef01cSRoman Divacky 2824dff0c46cSDimitry Andric // Otherwise, convert the UTF8 literals into a string of shorts. 2825dff0c46cSDimitry Andric IsUTF16 = true; 2826dff0c46cSDimitry Andric 2827dff0c46cSDimitry Andric SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 28283861d79fSDimitry Andric const UTF8 *FromPtr = (const UTF8 *)String.data(); 2829f22ef01cSRoman Divacky UTF16 *ToPtr = &ToBuf[0]; 2830f22ef01cSRoman Divacky 28312754fe60SDimitry Andric (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 2832f22ef01cSRoman Divacky &ToPtr, ToPtr + NumBytes, 2833f22ef01cSRoman Divacky strictConversion); 2834f22ef01cSRoman Divacky 2835f22ef01cSRoman Divacky // ConvertUTF8toUTF16 returns the length in ToPtr. 2836f22ef01cSRoman Divacky StringLength = ToPtr - &ToBuf[0]; 2837f22ef01cSRoman Divacky 2838dff0c46cSDimitry Andric // Add an explicit null. 2839dff0c46cSDimitry Andric *ToPtr = 0; 284039d628a0SDimitry Andric return *Map.insert(std::make_pair( 284139d628a0SDimitry Andric StringRef(reinterpret_cast<const char *>(ToBuf.data()), 284239d628a0SDimitry Andric (StringLength + 1) * 2), 284339d628a0SDimitry Andric nullptr)).first; 2844f22ef01cSRoman Divacky } 2845f22ef01cSRoman Divacky 284633956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 284733956c43SDimitry Andric GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 284833956c43SDimitry Andric const StringLiteral *Literal, unsigned &StringLength) { 28496122f3e6SDimitry Andric StringRef String = Literal->getString(); 2850bd5abe19SDimitry Andric StringLength = String.size(); 285139d628a0SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 2852bd5abe19SDimitry Andric } 2853bd5abe19SDimitry Andric 28540623d748SDimitry Andric ConstantAddress 2855f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 2856f22ef01cSRoman Divacky unsigned StringLength = 0; 2857f22ef01cSRoman Divacky bool isUTF16 = false; 285833956c43SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2859f22ef01cSRoman Divacky GetConstantCFStringEntry(CFConstantStringMap, Literal, 286033956c43SDimitry Andric getDataLayout().isLittleEndian(), isUTF16, 286133956c43SDimitry Andric StringLength); 2862f22ef01cSRoman Divacky 286339d628a0SDimitry Andric if (auto *C = Entry.second) 28640623d748SDimitry Andric return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 2865f22ef01cSRoman Divacky 2866dff0c46cSDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2867f22ef01cSRoman Divacky llvm::Constant *Zeros[] = { Zero, Zero }; 2868284c1978SDimitry Andric llvm::Value *V; 2869f22ef01cSRoman Divacky 2870f22ef01cSRoman Divacky // If we don't already have it, get __CFConstantStringClassReference. 2871f22ef01cSRoman Divacky if (!CFConstantStringClassRef) { 28726122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2873f22ef01cSRoman Divacky Ty = llvm::ArrayType::get(Ty, 0); 2874f22ef01cSRoman Divacky llvm::Constant *GV = CreateRuntimeVariable(Ty, 2875f22ef01cSRoman Divacky "__CFConstantStringClassReference"); 2876f22ef01cSRoman Divacky // Decay array -> ptr 287733956c43SDimitry Andric V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros); 2878284c1978SDimitry Andric CFConstantStringClassRef = V; 2879f22ef01cSRoman Divacky } 2880284c1978SDimitry Andric else 2881284c1978SDimitry Andric V = CFConstantStringClassRef; 2882f22ef01cSRoman Divacky 2883f22ef01cSRoman Divacky QualType CFTy = getContext().getCFConstantStringType(); 2884f22ef01cSRoman Divacky 288559d1ed5bSDimitry Andric auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 2886f22ef01cSRoman Divacky 2887dff0c46cSDimitry Andric llvm::Constant *Fields[4]; 2888f22ef01cSRoman Divacky 2889f22ef01cSRoman Divacky // Class pointer. 2890284c1978SDimitry Andric Fields[0] = cast<llvm::ConstantExpr>(V); 2891f22ef01cSRoman Divacky 2892f22ef01cSRoman Divacky // Flags. 28936122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2894f22ef01cSRoman Divacky Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 2895f22ef01cSRoman Divacky llvm::ConstantInt::get(Ty, 0x07C8); 2896f22ef01cSRoman Divacky 2897f22ef01cSRoman Divacky // String pointer. 289859d1ed5bSDimitry Andric llvm::Constant *C = nullptr; 2899dff0c46cSDimitry Andric if (isUTF16) { 29000623d748SDimitry Andric auto Arr = llvm::makeArrayRef( 290139d628a0SDimitry Andric reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 290239d628a0SDimitry Andric Entry.first().size() / 2); 2903dff0c46cSDimitry Andric C = llvm::ConstantDataArray::get(VMContext, Arr); 2904dff0c46cSDimitry Andric } else { 290539d628a0SDimitry Andric C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 2906dff0c46cSDimitry Andric } 2907f22ef01cSRoman Divacky 2908dff0c46cSDimitry Andric // Note: -fwritable-strings doesn't make the backing store strings of 2909dff0c46cSDimitry Andric // CFStrings writable. (See <rdar://problem/10657500>) 291059d1ed5bSDimitry Andric auto *GV = 2911dff0c46cSDimitry Andric new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 291259d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, C, ".str"); 29132754fe60SDimitry Andric GV->setUnnamedAddr(true); 2914284c1978SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 2915284c1978SDimitry Andric // of the string is via this class initializer. 291659d1ed5bSDimitry Andric // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without 291759d1ed5bSDimitry Andric // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing 291859d1ed5bSDimitry Andric // that changes the section it ends in, which surprises ld64. 2919f22ef01cSRoman Divacky if (isUTF16) { 2920f22ef01cSRoman Divacky CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 2921f22ef01cSRoman Divacky GV->setAlignment(Align.getQuantity()); 292259d1ed5bSDimitry Andric GV->setSection("__TEXT,__ustring"); 29233b0f4066SDimitry Andric } else { 29243b0f4066SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 29253b0f4066SDimitry Andric GV->setAlignment(Align.getQuantity()); 292659d1ed5bSDimitry Andric GV->setSection("__TEXT,__cstring,cstring_literals"); 2927f22ef01cSRoman Divacky } 2928dff0c46cSDimitry Andric 2929dff0c46cSDimitry Andric // String. 293033956c43SDimitry Andric Fields[2] = 293133956c43SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 2932f22ef01cSRoman Divacky 2933dff0c46cSDimitry Andric if (isUTF16) 2934dff0c46cSDimitry Andric // Cast the UTF16 string to the correct type. 2935dff0c46cSDimitry Andric Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 2936dff0c46cSDimitry Andric 2937f22ef01cSRoman Divacky // String length. 2938f22ef01cSRoman Divacky Ty = getTypes().ConvertType(getContext().LongTy); 2939f22ef01cSRoman Divacky Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 2940f22ef01cSRoman Divacky 29410623d748SDimitry Andric CharUnits Alignment = getPointerAlign(); 29420623d748SDimitry Andric 2943f22ef01cSRoman Divacky // The struct. 2944f22ef01cSRoman Divacky C = llvm::ConstantStruct::get(STy, Fields); 2945f22ef01cSRoman Divacky GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2946f22ef01cSRoman Divacky llvm::GlobalVariable::PrivateLinkage, C, 2947f22ef01cSRoman Divacky "_unnamed_cfstring_"); 294859d1ed5bSDimitry Andric GV->setSection("__DATA,__cfstring"); 29490623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 295039d628a0SDimitry Andric Entry.second = GV; 2951f22ef01cSRoman Divacky 29520623d748SDimitry Andric return ConstantAddress(GV, Alignment); 2953f22ef01cSRoman Divacky } 2954f22ef01cSRoman Divacky 29550623d748SDimitry Andric ConstantAddress 29562754fe60SDimitry Andric CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 2957f22ef01cSRoman Divacky unsigned StringLength = 0; 295833956c43SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2959bd5abe19SDimitry Andric GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 2960f22ef01cSRoman Divacky 296139d628a0SDimitry Andric if (auto *C = Entry.second) 29620623d748SDimitry Andric return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 2963f22ef01cSRoman Divacky 2964dff0c46cSDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2965f22ef01cSRoman Divacky llvm::Constant *Zeros[] = { Zero, Zero }; 2966284c1978SDimitry Andric llvm::Value *V; 2967f22ef01cSRoman Divacky // If we don't already have it, get _NSConstantStringClassReference. 29682754fe60SDimitry Andric if (!ConstantStringClassRef) { 2969dff0c46cSDimitry Andric std::string StringClass(getLangOpts().ObjCConstantStringClass); 29706122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 29712754fe60SDimitry Andric llvm::Constant *GV; 29727ae0e2c9SDimitry Andric if (LangOpts.ObjCRuntime.isNonFragile()) { 2973bd5abe19SDimitry Andric std::string str = 2974bd5abe19SDimitry Andric StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 2975bd5abe19SDimitry Andric : "OBJC_CLASS_$_" + StringClass; 2976bd5abe19SDimitry Andric GV = getObjCRuntime().GetClassGlobal(str); 2977bd5abe19SDimitry Andric // Make sure the result is of the correct type. 29786122f3e6SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2979284c1978SDimitry Andric V = llvm::ConstantExpr::getBitCast(GV, PTy); 2980284c1978SDimitry Andric ConstantStringClassRef = V; 2981bd5abe19SDimitry Andric } else { 2982bd5abe19SDimitry Andric std::string str = 2983bd5abe19SDimitry Andric StringClass.empty() ? "_NSConstantStringClassReference" 2984bd5abe19SDimitry Andric : "_" + StringClass + "ClassReference"; 29856122f3e6SDimitry Andric llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 2986bd5abe19SDimitry Andric GV = CreateRuntimeVariable(PTy, str); 2987f22ef01cSRoman Divacky // Decay array -> ptr 298833956c43SDimitry Andric V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros); 2989284c1978SDimitry Andric ConstantStringClassRef = V; 2990f22ef01cSRoman Divacky } 299133956c43SDimitry Andric } else 2992284c1978SDimitry Andric V = ConstantStringClassRef; 2993f22ef01cSRoman Divacky 29946122f3e6SDimitry Andric if (!NSConstantStringType) { 29956122f3e6SDimitry Andric // Construct the type for a constant NSString. 299659d1ed5bSDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString"); 29976122f3e6SDimitry Andric D->startDefinition(); 2998f22ef01cSRoman Divacky 29996122f3e6SDimitry Andric QualType FieldTypes[3]; 30006122f3e6SDimitry Andric 30016122f3e6SDimitry Andric // const int *isa; 30026122f3e6SDimitry Andric FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 30036122f3e6SDimitry Andric // const char *str; 30046122f3e6SDimitry Andric FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 30056122f3e6SDimitry Andric // unsigned int length; 30066122f3e6SDimitry Andric FieldTypes[2] = Context.UnsignedIntTy; 30076122f3e6SDimitry Andric 30086122f3e6SDimitry Andric // Create fields 30096122f3e6SDimitry Andric for (unsigned i = 0; i < 3; ++i) { 30106122f3e6SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, D, 30116122f3e6SDimitry Andric SourceLocation(), 301259d1ed5bSDimitry Andric SourceLocation(), nullptr, 301359d1ed5bSDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 301459d1ed5bSDimitry Andric /*BitWidth=*/nullptr, 30156122f3e6SDimitry Andric /*Mutable=*/false, 30167ae0e2c9SDimitry Andric ICIS_NoInit); 30176122f3e6SDimitry Andric Field->setAccess(AS_public); 30186122f3e6SDimitry Andric D->addDecl(Field); 30196122f3e6SDimitry Andric } 30206122f3e6SDimitry Andric 30216122f3e6SDimitry Andric D->completeDefinition(); 30226122f3e6SDimitry Andric QualType NSTy = Context.getTagDeclType(D); 30236122f3e6SDimitry Andric NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 30246122f3e6SDimitry Andric } 3025f22ef01cSRoman Divacky 3026dff0c46cSDimitry Andric llvm::Constant *Fields[3]; 3027f22ef01cSRoman Divacky 3028f22ef01cSRoman Divacky // Class pointer. 3029284c1978SDimitry Andric Fields[0] = cast<llvm::ConstantExpr>(V); 3030f22ef01cSRoman Divacky 3031f22ef01cSRoman Divacky // String pointer. 3032dff0c46cSDimitry Andric llvm::Constant *C = 303339d628a0SDimitry Andric llvm::ConstantDataArray::getString(VMContext, Entry.first()); 3034f22ef01cSRoman Divacky 3035f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes Linkage; 3036f22ef01cSRoman Divacky bool isConstant; 3037f22ef01cSRoman Divacky Linkage = llvm::GlobalValue::PrivateLinkage; 3038dff0c46cSDimitry Andric isConstant = !LangOpts.WritableStrings; 3039f22ef01cSRoman Divacky 304059d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant, 304159d1ed5bSDimitry Andric Linkage, C, ".str"); 30422754fe60SDimitry Andric GV->setUnnamedAddr(true); 3043284c1978SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 3044284c1978SDimitry Andric // of the string is via this class initializer. 30453b0f4066SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 30463b0f4066SDimitry Andric GV->setAlignment(Align.getQuantity()); 304733956c43SDimitry Andric Fields[1] = 304833956c43SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 3049f22ef01cSRoman Divacky 3050f22ef01cSRoman Divacky // String length. 30516122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 3052f22ef01cSRoman Divacky Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 3053f22ef01cSRoman Divacky 3054f22ef01cSRoman Divacky // The struct. 30550623d748SDimitry Andric CharUnits Alignment = getPointerAlign(); 30566122f3e6SDimitry Andric C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 3057f22ef01cSRoman Divacky GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 3058f22ef01cSRoman Divacky llvm::GlobalVariable::PrivateLinkage, C, 3059f22ef01cSRoman Divacky "_unnamed_nsstring_"); 30600623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 306159d1ed5bSDimitry Andric const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip"; 306259d1ed5bSDimitry Andric const char *NSStringNonFragileABISection = 306359d1ed5bSDimitry Andric "__DATA,__objc_stringobj,regular,no_dead_strip"; 3064f22ef01cSRoman Divacky // FIXME. Fix section. 306559d1ed5bSDimitry Andric GV->setSection(LangOpts.ObjCRuntime.isNonFragile() 306659d1ed5bSDimitry Andric ? NSStringNonFragileABISection 306759d1ed5bSDimitry Andric : NSStringSection); 306839d628a0SDimitry Andric Entry.second = GV; 3069f22ef01cSRoman Divacky 30700623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3071f22ef01cSRoman Divacky } 3072f22ef01cSRoman Divacky 30736122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() { 30746122f3e6SDimitry Andric if (ObjCFastEnumerationStateType.isNull()) { 307559d1ed5bSDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 30766122f3e6SDimitry Andric D->startDefinition(); 30776122f3e6SDimitry Andric 30786122f3e6SDimitry Andric QualType FieldTypes[] = { 30796122f3e6SDimitry Andric Context.UnsignedLongTy, 30806122f3e6SDimitry Andric Context.getPointerType(Context.getObjCIdType()), 30816122f3e6SDimitry Andric Context.getPointerType(Context.UnsignedLongTy), 30826122f3e6SDimitry Andric Context.getConstantArrayType(Context.UnsignedLongTy, 30836122f3e6SDimitry Andric llvm::APInt(32, 5), ArrayType::Normal, 0) 30846122f3e6SDimitry Andric }; 30856122f3e6SDimitry Andric 30866122f3e6SDimitry Andric for (size_t i = 0; i < 4; ++i) { 30876122f3e6SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, 30886122f3e6SDimitry Andric D, 30896122f3e6SDimitry Andric SourceLocation(), 309059d1ed5bSDimitry Andric SourceLocation(), nullptr, 309159d1ed5bSDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 309259d1ed5bSDimitry Andric /*BitWidth=*/nullptr, 30936122f3e6SDimitry Andric /*Mutable=*/false, 30947ae0e2c9SDimitry Andric ICIS_NoInit); 30956122f3e6SDimitry Andric Field->setAccess(AS_public); 30966122f3e6SDimitry Andric D->addDecl(Field); 30976122f3e6SDimitry Andric } 30986122f3e6SDimitry Andric 30996122f3e6SDimitry Andric D->completeDefinition(); 31006122f3e6SDimitry Andric ObjCFastEnumerationStateType = Context.getTagDeclType(D); 31016122f3e6SDimitry Andric } 31026122f3e6SDimitry Andric 31036122f3e6SDimitry Andric return ObjCFastEnumerationStateType; 31046122f3e6SDimitry Andric } 31056122f3e6SDimitry Andric 3106dff0c46cSDimitry Andric llvm::Constant * 3107dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 3108dff0c46cSDimitry Andric assert(!E->getType()->isPointerType() && "Strings are always arrays"); 3109f22ef01cSRoman Divacky 3110dff0c46cSDimitry Andric // Don't emit it as the address of the string, emit the string data itself 3111dff0c46cSDimitry Andric // as an inline array. 3112dff0c46cSDimitry Andric if (E->getCharByteWidth() == 1) { 3113dff0c46cSDimitry Andric SmallString<64> Str(E->getString()); 3114f22ef01cSRoman Divacky 3115dff0c46cSDimitry Andric // Resize the string to the right size, which is indicated by its type. 3116dff0c46cSDimitry Andric const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 3117dff0c46cSDimitry Andric Str.resize(CAT->getSize().getZExtValue()); 3118dff0c46cSDimitry Andric return llvm::ConstantDataArray::getString(VMContext, Str, false); 31196122f3e6SDimitry Andric } 3120f22ef01cSRoman Divacky 312159d1ed5bSDimitry Andric auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 3122dff0c46cSDimitry Andric llvm::Type *ElemTy = AType->getElementType(); 3123dff0c46cSDimitry Andric unsigned NumElements = AType->getNumElements(); 3124f22ef01cSRoman Divacky 3125dff0c46cSDimitry Andric // Wide strings have either 2-byte or 4-byte elements. 3126dff0c46cSDimitry Andric if (ElemTy->getPrimitiveSizeInBits() == 16) { 3127dff0c46cSDimitry Andric SmallVector<uint16_t, 32> Elements; 3128dff0c46cSDimitry Andric Elements.reserve(NumElements); 3129dff0c46cSDimitry Andric 3130dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3131dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 3132dff0c46cSDimitry Andric Elements.resize(NumElements); 3133dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 3134dff0c46cSDimitry Andric } 3135dff0c46cSDimitry Andric 3136dff0c46cSDimitry Andric assert(ElemTy->getPrimitiveSizeInBits() == 32); 3137dff0c46cSDimitry Andric SmallVector<uint32_t, 32> Elements; 3138dff0c46cSDimitry Andric Elements.reserve(NumElements); 3139dff0c46cSDimitry Andric 3140dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3141dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 3142dff0c46cSDimitry Andric Elements.resize(NumElements); 3143dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 3144f22ef01cSRoman Divacky } 3145f22ef01cSRoman Divacky 314659d1ed5bSDimitry Andric static llvm::GlobalVariable * 314759d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 314859d1ed5bSDimitry Andric CodeGenModule &CGM, StringRef GlobalName, 31490623d748SDimitry Andric CharUnits Alignment) { 315059d1ed5bSDimitry Andric // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 315159d1ed5bSDimitry Andric unsigned AddrSpace = 0; 315259d1ed5bSDimitry Andric if (CGM.getLangOpts().OpenCL) 315359d1ed5bSDimitry Andric AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 3154dff0c46cSDimitry Andric 315533956c43SDimitry Andric llvm::Module &M = CGM.getModule(); 315659d1ed5bSDimitry Andric // Create a global variable for this string 315759d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 315833956c43SDimitry Andric M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 315933956c43SDimitry Andric nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 31600623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 316159d1ed5bSDimitry Andric GV->setUnnamedAddr(true); 316233956c43SDimitry Andric if (GV->isWeakForLinker()) { 316333956c43SDimitry Andric assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 316433956c43SDimitry Andric GV->setComdat(M.getOrInsertComdat(GV->getName())); 316533956c43SDimitry Andric } 316633956c43SDimitry Andric 316759d1ed5bSDimitry Andric return GV; 3168f22ef01cSRoman Divacky } 3169dff0c46cSDimitry Andric 317059d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 317159d1ed5bSDimitry Andric /// constant array for the given string literal. 31720623d748SDimitry Andric ConstantAddress 317339d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 317439d628a0SDimitry Andric StringRef Name) { 31750623d748SDimitry Andric CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 3176dff0c46cSDimitry Andric 317759d1ed5bSDimitry Andric llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 317859d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 317959d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 318059d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 318159d1ed5bSDimitry Andric if (auto GV = *Entry) { 31820623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 31830623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 31840623d748SDimitry Andric return ConstantAddress(GV, Alignment); 318559d1ed5bSDimitry Andric } 318659d1ed5bSDimitry Andric } 318759d1ed5bSDimitry Andric 318859d1ed5bSDimitry Andric SmallString<256> MangledNameBuffer; 318959d1ed5bSDimitry Andric StringRef GlobalVariableName; 319059d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes LT; 319159d1ed5bSDimitry Andric 319259d1ed5bSDimitry Andric // Mangle the string literal if the ABI allows for it. However, we cannot 319359d1ed5bSDimitry Andric // do this if we are compiling with ASan or -fwritable-strings because they 319459d1ed5bSDimitry Andric // rely on strings having normal linkage. 319539d628a0SDimitry Andric if (!LangOpts.WritableStrings && 319639d628a0SDimitry Andric !LangOpts.Sanitize.has(SanitizerKind::Address) && 319759d1ed5bSDimitry Andric getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { 319859d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(MangledNameBuffer); 319959d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 320059d1ed5bSDimitry Andric 320159d1ed5bSDimitry Andric LT = llvm::GlobalValue::LinkOnceODRLinkage; 320259d1ed5bSDimitry Andric GlobalVariableName = MangledNameBuffer; 320359d1ed5bSDimitry Andric } else { 320459d1ed5bSDimitry Andric LT = llvm::GlobalValue::PrivateLinkage; 320539d628a0SDimitry Andric GlobalVariableName = Name; 320659d1ed5bSDimitry Andric } 320759d1ed5bSDimitry Andric 320859d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 320959d1ed5bSDimitry Andric if (Entry) 321059d1ed5bSDimitry Andric *Entry = GV; 321159d1ed5bSDimitry Andric 321239d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 321339d628a0SDimitry Andric QualType()); 32140623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3215f22ef01cSRoman Divacky } 3216f22ef01cSRoman Divacky 3217f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 3218f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node. 32190623d748SDimitry Andric ConstantAddress 3220f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 3221f22ef01cSRoman Divacky std::string Str; 3222f22ef01cSRoman Divacky getContext().getObjCEncodingForType(E->getEncodedType(), Str); 3223f22ef01cSRoman Divacky 3224f22ef01cSRoman Divacky return GetAddrOfConstantCString(Str); 3225f22ef01cSRoman Divacky } 3226f22ef01cSRoman Divacky 322759d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing 322859d1ed5bSDimitry Andric /// the literal and a terminating '\0' character. 322959d1ed5bSDimitry Andric /// The result has pointer to array type. 32300623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString( 32310623d748SDimitry Andric const std::string &Str, const char *GlobalName) { 323259d1ed5bSDimitry Andric StringRef StrWithNull(Str.c_str(), Str.size() + 1); 32330623d748SDimitry Andric CharUnits Alignment = 32340623d748SDimitry Andric getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 3235f22ef01cSRoman Divacky 323659d1ed5bSDimitry Andric llvm::Constant *C = 323759d1ed5bSDimitry Andric llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 323859d1ed5bSDimitry Andric 323959d1ed5bSDimitry Andric // Don't share any string literals if strings aren't constant. 324059d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 324159d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 324259d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 324359d1ed5bSDimitry Andric if (auto GV = *Entry) { 32440623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 32450623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 32460623d748SDimitry Andric return ConstantAddress(GV, Alignment); 324759d1ed5bSDimitry Andric } 324859d1ed5bSDimitry Andric } 324959d1ed5bSDimitry Andric 3250f22ef01cSRoman Divacky // Get the default prefix if a name wasn't specified. 3251f22ef01cSRoman Divacky if (!GlobalName) 3252f22ef01cSRoman Divacky GlobalName = ".str"; 3253f22ef01cSRoman Divacky // Create a global variable for this. 325459d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 325559d1ed5bSDimitry Andric GlobalName, Alignment); 325659d1ed5bSDimitry Andric if (Entry) 325759d1ed5bSDimitry Andric *Entry = GV; 32580623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3259f22ef01cSRoman Divacky } 3260f22ef01cSRoman Divacky 32610623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 3262f785676fSDimitry Andric const MaterializeTemporaryExpr *E, const Expr *Init) { 3263f785676fSDimitry Andric assert((E->getStorageDuration() == SD_Static || 3264f785676fSDimitry Andric E->getStorageDuration() == SD_Thread) && "not a global temporary"); 326559d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 3266f785676fSDimitry Andric 3267f785676fSDimitry Andric // If we're not materializing a subobject of the temporary, keep the 3268f785676fSDimitry Andric // cv-qualifiers from the type of the MaterializeTemporaryExpr. 3269f785676fSDimitry Andric QualType MaterializedType = Init->getType(); 3270f785676fSDimitry Andric if (Init == E->GetTemporaryExpr()) 3271f785676fSDimitry Andric MaterializedType = E->getType(); 3272f785676fSDimitry Andric 32730623d748SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 32740623d748SDimitry Andric 32750623d748SDimitry Andric if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E]) 32760623d748SDimitry Andric return ConstantAddress(Slot, Align); 3277f785676fSDimitry Andric 3278f785676fSDimitry Andric // FIXME: If an externally-visible declaration extends multiple temporaries, 3279f785676fSDimitry Andric // we need to give each temporary the same name in every translation unit (and 3280f785676fSDimitry Andric // we also need to make the temporaries externally-visible). 3281f785676fSDimitry Andric SmallString<256> Name; 3282f785676fSDimitry Andric llvm::raw_svector_ostream Out(Name); 328359d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleReferenceTemporary( 328459d1ed5bSDimitry Andric VD, E->getManglingNumber(), Out); 3285f785676fSDimitry Andric 328659d1ed5bSDimitry Andric APValue *Value = nullptr; 3287f785676fSDimitry Andric if (E->getStorageDuration() == SD_Static) { 3288f785676fSDimitry Andric // We might have a cached constant initializer for this temporary. Note 3289f785676fSDimitry Andric // that this might have a different value from the value computed by 3290f785676fSDimitry Andric // evaluating the initializer if the surrounding constant expression 3291f785676fSDimitry Andric // modifies the temporary. 3292f785676fSDimitry Andric Value = getContext().getMaterializedTemporaryValue(E, false); 3293f785676fSDimitry Andric if (Value && Value->isUninit()) 329459d1ed5bSDimitry Andric Value = nullptr; 3295f785676fSDimitry Andric } 3296f785676fSDimitry Andric 3297f785676fSDimitry Andric // Try evaluating it now, it might have a constant initializer. 3298f785676fSDimitry Andric Expr::EvalResult EvalResult; 3299f785676fSDimitry Andric if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 3300f785676fSDimitry Andric !EvalResult.hasSideEffects()) 3301f785676fSDimitry Andric Value = &EvalResult.Val; 3302f785676fSDimitry Andric 330359d1ed5bSDimitry Andric llvm::Constant *InitialValue = nullptr; 3304f785676fSDimitry Andric bool Constant = false; 3305f785676fSDimitry Andric llvm::Type *Type; 3306f785676fSDimitry Andric if (Value) { 3307f785676fSDimitry Andric // The temporary has a constant initializer, use it. 330859d1ed5bSDimitry Andric InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr); 3309f785676fSDimitry Andric Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 3310f785676fSDimitry Andric Type = InitialValue->getType(); 3311f785676fSDimitry Andric } else { 3312f785676fSDimitry Andric // No initializer, the initialization will be provided when we 3313f785676fSDimitry Andric // initialize the declaration which performed lifetime extension. 3314f785676fSDimitry Andric Type = getTypes().ConvertTypeForMem(MaterializedType); 3315f785676fSDimitry Andric } 3316f785676fSDimitry Andric 3317f785676fSDimitry Andric // Create a global variable for this lifetime-extended temporary. 331859d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 331959d1ed5bSDimitry Andric getLLVMLinkageVarDefinition(VD, Constant); 332033956c43SDimitry Andric if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 332133956c43SDimitry Andric const VarDecl *InitVD; 332233956c43SDimitry Andric if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 332333956c43SDimitry Andric isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 332433956c43SDimitry Andric // Temporaries defined inside a class get linkonce_odr linkage because the 332533956c43SDimitry Andric // class can be defined in multipe translation units. 332633956c43SDimitry Andric Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 332733956c43SDimitry Andric } else { 332833956c43SDimitry Andric // There is no need for this temporary to have external linkage if the 332933956c43SDimitry Andric // VarDecl has external linkage. 333033956c43SDimitry Andric Linkage = llvm::GlobalVariable::InternalLinkage; 333133956c43SDimitry Andric } 333233956c43SDimitry Andric } 333359d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace( 333459d1ed5bSDimitry Andric VD, getContext().getTargetAddressSpace(MaterializedType)); 333559d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 333659d1ed5bSDimitry Andric getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 333759d1ed5bSDimitry Andric /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, 333859d1ed5bSDimitry Andric AddrSpace); 333959d1ed5bSDimitry Andric setGlobalVisibility(GV, VD); 33400623d748SDimitry Andric GV->setAlignment(Align.getQuantity()); 334133956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker()) 334233956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3343f785676fSDimitry Andric if (VD->getTLSKind()) 3344f785676fSDimitry Andric setTLSMode(GV, *VD); 33450623d748SDimitry Andric MaterializedGlobalTemporaryMap[E] = GV; 33460623d748SDimitry Andric return ConstantAddress(GV, Align); 3347f785676fSDimitry Andric } 3348f785676fSDimitry Andric 3349f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized 3350f22ef01cSRoman Divacky /// properties for an implementation. 3351f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const 3352f22ef01cSRoman Divacky ObjCImplementationDecl *D) { 335359d1ed5bSDimitry Andric for (const auto *PID : D->property_impls()) { 3354f22ef01cSRoman Divacky // Dynamic is just for type-checking. 3355f22ef01cSRoman Divacky if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 3356f22ef01cSRoman Divacky ObjCPropertyDecl *PD = PID->getPropertyDecl(); 3357f22ef01cSRoman Divacky 3358f22ef01cSRoman Divacky // Determine which methods need to be implemented, some may have 33593861d79fSDimitry Andric // been overridden. Note that ::isPropertyAccessor is not the method 3360f22ef01cSRoman Divacky // we want, that just indicates if the decl came from a 3361f22ef01cSRoman Divacky // property. What we want to know is if the method is defined in 3362f22ef01cSRoman Divacky // this implementation. 3363f22ef01cSRoman Divacky if (!D->getInstanceMethod(PD->getGetterName())) 3364f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCGetter( 3365f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3366f22ef01cSRoman Divacky if (!PD->isReadOnly() && 3367f22ef01cSRoman Divacky !D->getInstanceMethod(PD->getSetterName())) 3368f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCSetter( 3369f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3370f22ef01cSRoman Divacky } 3371f22ef01cSRoman Divacky } 3372f22ef01cSRoman Divacky } 3373f22ef01cSRoman Divacky 33743b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) { 33756122f3e6SDimitry Andric const ObjCInterfaceDecl *iface = impl->getClassInterface(); 33766122f3e6SDimitry Andric for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 33773b0f4066SDimitry Andric ivar; ivar = ivar->getNextIvar()) 33783b0f4066SDimitry Andric if (ivar->getType().isDestructedType()) 33793b0f4066SDimitry Andric return true; 33803b0f4066SDimitry Andric 33813b0f4066SDimitry Andric return false; 33823b0f4066SDimitry Andric } 33833b0f4066SDimitry Andric 338439d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM, 338539d628a0SDimitry Andric ObjCImplementationDecl *D) { 338639d628a0SDimitry Andric CodeGenFunction CGF(CGM); 338739d628a0SDimitry Andric for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 338839d628a0SDimitry Andric E = D->init_end(); B != E; ++B) { 338939d628a0SDimitry Andric CXXCtorInitializer *CtorInitExp = *B; 339039d628a0SDimitry Andric Expr *Init = CtorInitExp->getInit(); 339139d628a0SDimitry Andric if (!CGF.isTrivialInitializer(Init)) 339239d628a0SDimitry Andric return false; 339339d628a0SDimitry Andric } 339439d628a0SDimitry Andric return true; 339539d628a0SDimitry Andric } 339639d628a0SDimitry Andric 3397f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization 3398f22ef01cSRoman Divacky /// for an implementation. 3399f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 34003b0f4066SDimitry Andric // We might need a .cxx_destruct even if we don't have any ivar initializers. 34013b0f4066SDimitry Andric if (needsDestructMethod(D)) { 3402f22ef01cSRoman Divacky IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 3403f22ef01cSRoman Divacky Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 34043b0f4066SDimitry Andric ObjCMethodDecl *DTORMethod = 34053b0f4066SDimitry Andric ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 340659d1ed5bSDimitry Andric cxxSelector, getContext().VoidTy, nullptr, D, 34076122f3e6SDimitry Andric /*isInstance=*/true, /*isVariadic=*/false, 34083861d79fSDimitry Andric /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 34096122f3e6SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 3410f22ef01cSRoman Divacky D->addInstanceMethod(DTORMethod); 3411f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 34123861d79fSDimitry Andric D->setHasDestructors(true); 34133b0f4066SDimitry Andric } 3414f22ef01cSRoman Divacky 34153b0f4066SDimitry Andric // If the implementation doesn't have any ivar initializers, we don't need 34163b0f4066SDimitry Andric // a .cxx_construct. 341739d628a0SDimitry Andric if (D->getNumIvarInitializers() == 0 || 341839d628a0SDimitry Andric AllTrivialInitializers(*this, D)) 34193b0f4066SDimitry Andric return; 34203b0f4066SDimitry Andric 34213b0f4066SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 34223b0f4066SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 3423f22ef01cSRoman Divacky // The constructor returns 'self'. 3424f22ef01cSRoman Divacky ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 3425f22ef01cSRoman Divacky D->getLocation(), 34266122f3e6SDimitry Andric D->getLocation(), 34276122f3e6SDimitry Andric cxxSelector, 342859d1ed5bSDimitry Andric getContext().getObjCIdType(), 342959d1ed5bSDimitry Andric nullptr, D, /*isInstance=*/true, 34306122f3e6SDimitry Andric /*isVariadic=*/false, 34313861d79fSDimitry Andric /*isPropertyAccessor=*/true, 34326122f3e6SDimitry Andric /*isImplicitlyDeclared=*/true, 34336122f3e6SDimitry Andric /*isDefined=*/false, 3434f22ef01cSRoman Divacky ObjCMethodDecl::Required); 3435f22ef01cSRoman Divacky D->addInstanceMethod(CTORMethod); 3436f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 34373861d79fSDimitry Andric D->setHasNonZeroConstructors(true); 3438f22ef01cSRoman Divacky } 3439f22ef01cSRoman Divacky 3440f22ef01cSRoman Divacky /// EmitNamespace - Emit all declarations in a namespace. 3441f22ef01cSRoman Divacky void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 344259d1ed5bSDimitry Andric for (auto *I : ND->decls()) { 344359d1ed5bSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(I)) 3444f785676fSDimitry Andric if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 3445f785676fSDimitry Andric VD->getTemplateSpecializationKind() != TSK_Undeclared) 3446f785676fSDimitry Andric continue; 344759d1ed5bSDimitry Andric EmitTopLevelDecl(I); 3448f22ef01cSRoman Divacky } 3449f785676fSDimitry Andric } 3450f22ef01cSRoman Divacky 3451f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec. 3452f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 3453f22ef01cSRoman Divacky if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 3454f22ef01cSRoman Divacky LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 3455f22ef01cSRoman Divacky ErrorUnsupported(LSD, "linkage spec"); 3456f22ef01cSRoman Divacky return; 3457f22ef01cSRoman Divacky } 3458f22ef01cSRoman Divacky 345959d1ed5bSDimitry Andric for (auto *I : LSD->decls()) { 34603861d79fSDimitry Andric // Meta-data for ObjC class includes references to implemented methods. 34613861d79fSDimitry Andric // Generate class's method definitions first. 346259d1ed5bSDimitry Andric if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 346359d1ed5bSDimitry Andric for (auto *M : OID->methods()) 346459d1ed5bSDimitry Andric EmitTopLevelDecl(M); 34653861d79fSDimitry Andric } 346659d1ed5bSDimitry Andric EmitTopLevelDecl(I); 3467f22ef01cSRoman Divacky } 34683861d79fSDimitry Andric } 3469f22ef01cSRoman Divacky 3470f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration. 3471f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) { 3472f22ef01cSRoman Divacky // Ignore dependent declarations. 3473f22ef01cSRoman Divacky if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 3474f22ef01cSRoman Divacky return; 3475f22ef01cSRoman Divacky 3476f22ef01cSRoman Divacky switch (D->getKind()) { 3477f22ef01cSRoman Divacky case Decl::CXXConversion: 3478f22ef01cSRoman Divacky case Decl::CXXMethod: 3479f22ef01cSRoman Divacky case Decl::Function: 3480f22ef01cSRoman Divacky // Skip function templates 34813b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 34823b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3483f22ef01cSRoman Divacky return; 3484f22ef01cSRoman Divacky 3485f22ef01cSRoman Divacky EmitGlobal(cast<FunctionDecl>(D)); 348639d628a0SDimitry Andric // Always provide some coverage mapping 348739d628a0SDimitry Andric // even for the functions that aren't emitted. 348839d628a0SDimitry Andric AddDeferredUnusedCoverageMapping(D); 3489f22ef01cSRoman Divacky break; 3490f22ef01cSRoman Divacky 3491f22ef01cSRoman Divacky case Decl::Var: 3492f785676fSDimitry Andric // Skip variable templates 3493f785676fSDimitry Andric if (cast<VarDecl>(D)->getDescribedVarTemplate()) 3494f785676fSDimitry Andric return; 3495f785676fSDimitry Andric case Decl::VarTemplateSpecialization: 3496f22ef01cSRoman Divacky EmitGlobal(cast<VarDecl>(D)); 3497f22ef01cSRoman Divacky break; 3498f22ef01cSRoman Divacky 34993b0f4066SDimitry Andric // Indirect fields from global anonymous structs and unions can be 35003b0f4066SDimitry Andric // ignored; only the actual variable requires IR gen support. 35013b0f4066SDimitry Andric case Decl::IndirectField: 35023b0f4066SDimitry Andric break; 35033b0f4066SDimitry Andric 3504f22ef01cSRoman Divacky // C++ Decls 3505f22ef01cSRoman Divacky case Decl::Namespace: 3506f22ef01cSRoman Divacky EmitNamespace(cast<NamespaceDecl>(D)); 3507f22ef01cSRoman Divacky break; 3508f22ef01cSRoman Divacky // No code generation needed. 3509f22ef01cSRoman Divacky case Decl::UsingShadow: 3510f22ef01cSRoman Divacky case Decl::ClassTemplate: 3511f785676fSDimitry Andric case Decl::VarTemplate: 3512f785676fSDimitry Andric case Decl::VarTemplatePartialSpecialization: 3513f22ef01cSRoman Divacky case Decl::FunctionTemplate: 3514bd5abe19SDimitry Andric case Decl::TypeAliasTemplate: 3515bd5abe19SDimitry Andric case Decl::Block: 3516139f7f9bSDimitry Andric case Decl::Empty: 3517f22ef01cSRoman Divacky break; 351859d1ed5bSDimitry Andric case Decl::Using: // using X; [C++] 351959d1ed5bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 352059d1ed5bSDimitry Andric DI->EmitUsingDecl(cast<UsingDecl>(*D)); 352159d1ed5bSDimitry Andric return; 3522f785676fSDimitry Andric case Decl::NamespaceAlias: 3523f785676fSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3524f785676fSDimitry Andric DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 3525f785676fSDimitry Andric return; 3526284c1978SDimitry Andric case Decl::UsingDirective: // using namespace X; [C++] 3527284c1978SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3528284c1978SDimitry Andric DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 3529284c1978SDimitry Andric return; 3530f22ef01cSRoman Divacky case Decl::CXXConstructor: 3531f22ef01cSRoman Divacky // Skip function templates 35323b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 35333b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3534f22ef01cSRoman Divacky return; 3535f22ef01cSRoman Divacky 3536f785676fSDimitry Andric getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 3537f22ef01cSRoman Divacky break; 3538f22ef01cSRoman Divacky case Decl::CXXDestructor: 35393b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 35403b0f4066SDimitry Andric return; 3541f785676fSDimitry Andric getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 3542f22ef01cSRoman Divacky break; 3543f22ef01cSRoman Divacky 3544f22ef01cSRoman Divacky case Decl::StaticAssert: 3545f22ef01cSRoman Divacky // Nothing to do. 3546f22ef01cSRoman Divacky break; 3547f22ef01cSRoman Divacky 3548f22ef01cSRoman Divacky // Objective-C Decls 3549f22ef01cSRoman Divacky 3550f22ef01cSRoman Divacky // Forward declarations, no (immediate) code generation. 3551f22ef01cSRoman Divacky case Decl::ObjCInterface: 35527ae0e2c9SDimitry Andric case Decl::ObjCCategory: 3553f22ef01cSRoman Divacky break; 3554f22ef01cSRoman Divacky 3555dff0c46cSDimitry Andric case Decl::ObjCProtocol: { 355659d1ed5bSDimitry Andric auto *Proto = cast<ObjCProtocolDecl>(D); 3557dff0c46cSDimitry Andric if (Proto->isThisDeclarationADefinition()) 3558dff0c46cSDimitry Andric ObjCRuntime->GenerateProtocol(Proto); 3559f22ef01cSRoman Divacky break; 3560dff0c46cSDimitry Andric } 3561f22ef01cSRoman Divacky 3562f22ef01cSRoman Divacky case Decl::ObjCCategoryImpl: 3563f22ef01cSRoman Divacky // Categories have properties but don't support synthesize so we 3564f22ef01cSRoman Divacky // can ignore them here. 35656122f3e6SDimitry Andric ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 3566f22ef01cSRoman Divacky break; 3567f22ef01cSRoman Divacky 3568f22ef01cSRoman Divacky case Decl::ObjCImplementation: { 356959d1ed5bSDimitry Andric auto *OMD = cast<ObjCImplementationDecl>(D); 3570f22ef01cSRoman Divacky EmitObjCPropertyImplementations(OMD); 3571f22ef01cSRoman Divacky EmitObjCIvarInitializations(OMD); 35726122f3e6SDimitry Andric ObjCRuntime->GenerateClass(OMD); 3573dff0c46cSDimitry Andric // Emit global variable debug information. 3574dff0c46cSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3575139f7f9bSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 3576139f7f9bSDimitry Andric DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 3577139f7f9bSDimitry Andric OMD->getClassInterface()), OMD->getLocation()); 3578f22ef01cSRoman Divacky break; 3579f22ef01cSRoman Divacky } 3580f22ef01cSRoman Divacky case Decl::ObjCMethod: { 358159d1ed5bSDimitry Andric auto *OMD = cast<ObjCMethodDecl>(D); 3582f22ef01cSRoman Divacky // If this is not a prototype, emit the body. 3583f22ef01cSRoman Divacky if (OMD->getBody()) 3584f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCMethod(OMD); 3585f22ef01cSRoman Divacky break; 3586f22ef01cSRoman Divacky } 3587f22ef01cSRoman Divacky case Decl::ObjCCompatibleAlias: 3588dff0c46cSDimitry Andric ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 3589f22ef01cSRoman Divacky break; 3590f22ef01cSRoman Divacky 3591f22ef01cSRoman Divacky case Decl::LinkageSpec: 3592f22ef01cSRoman Divacky EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 3593f22ef01cSRoman Divacky break; 3594f22ef01cSRoman Divacky 3595f22ef01cSRoman Divacky case Decl::FileScopeAsm: { 359633956c43SDimitry Andric // File-scope asm is ignored during device-side CUDA compilation. 359733956c43SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 359833956c43SDimitry Andric break; 359959d1ed5bSDimitry Andric auto *AD = cast<FileScopeAsmDecl>(D); 360033956c43SDimitry Andric getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 3601f22ef01cSRoman Divacky break; 3602f22ef01cSRoman Divacky } 3603f22ef01cSRoman Divacky 3604139f7f9bSDimitry Andric case Decl::Import: { 360559d1ed5bSDimitry Andric auto *Import = cast<ImportDecl>(D); 3606139f7f9bSDimitry Andric 3607139f7f9bSDimitry Andric // Ignore import declarations that come from imported modules. 36080623d748SDimitry Andric if (Import->getImportedOwningModule()) 3609139f7f9bSDimitry Andric break; 36103dac3a9bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 36113dac3a9bSDimitry Andric DI->EmitImportDecl(*Import); 3612139f7f9bSDimitry Andric 3613139f7f9bSDimitry Andric ImportedModules.insert(Import->getImportedModule()); 3614139f7f9bSDimitry Andric break; 3615139f7f9bSDimitry Andric } 3616139f7f9bSDimitry Andric 361739d628a0SDimitry Andric case Decl::OMPThreadPrivate: 361839d628a0SDimitry Andric EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 361939d628a0SDimitry Andric break; 362039d628a0SDimitry Andric 362159d1ed5bSDimitry Andric case Decl::ClassTemplateSpecialization: { 362259d1ed5bSDimitry Andric const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 362359d1ed5bSDimitry Andric if (DebugInfo && 362439d628a0SDimitry Andric Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition && 362539d628a0SDimitry Andric Spec->hasDefinition()) 362659d1ed5bSDimitry Andric DebugInfo->completeTemplateDefinition(*Spec); 362739d628a0SDimitry Andric break; 362859d1ed5bSDimitry Andric } 362959d1ed5bSDimitry Andric 3630f22ef01cSRoman Divacky default: 3631f22ef01cSRoman Divacky // Make sure we handled everything we should, every other kind is a 3632f22ef01cSRoman Divacky // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 3633f22ef01cSRoman Divacky // function. Need to recode Decl::Kind to do that easily. 3634f22ef01cSRoman Divacky assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 363539d628a0SDimitry Andric break; 363639d628a0SDimitry Andric } 363739d628a0SDimitry Andric } 363839d628a0SDimitry Andric 363939d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 364039d628a0SDimitry Andric // Do we need to generate coverage mapping? 364139d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 364239d628a0SDimitry Andric return; 364339d628a0SDimitry Andric switch (D->getKind()) { 364439d628a0SDimitry Andric case Decl::CXXConversion: 364539d628a0SDimitry Andric case Decl::CXXMethod: 364639d628a0SDimitry Andric case Decl::Function: 364739d628a0SDimitry Andric case Decl::ObjCMethod: 364839d628a0SDimitry Andric case Decl::CXXConstructor: 364939d628a0SDimitry Andric case Decl::CXXDestructor: { 36500623d748SDimitry Andric if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 365139d628a0SDimitry Andric return; 365239d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 365339d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 365439d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = true; 365539d628a0SDimitry Andric break; 365639d628a0SDimitry Andric } 365739d628a0SDimitry Andric default: 365839d628a0SDimitry Andric break; 365939d628a0SDimitry Andric }; 366039d628a0SDimitry Andric } 366139d628a0SDimitry Andric 366239d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 366339d628a0SDimitry Andric // Do we need to generate coverage mapping? 366439d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 366539d628a0SDimitry Andric return; 366639d628a0SDimitry Andric if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 366739d628a0SDimitry Andric if (Fn->isTemplateInstantiation()) 366839d628a0SDimitry Andric ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 366939d628a0SDimitry Andric } 367039d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 367139d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 367239d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = false; 367339d628a0SDimitry Andric else 367439d628a0SDimitry Andric I->second = false; 367539d628a0SDimitry Andric } 367639d628a0SDimitry Andric 367739d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 367839d628a0SDimitry Andric std::vector<const Decl *> DeferredDecls; 367933956c43SDimitry Andric for (const auto &I : DeferredEmptyCoverageMappingDecls) { 368039d628a0SDimitry Andric if (!I.second) 368139d628a0SDimitry Andric continue; 368239d628a0SDimitry Andric DeferredDecls.push_back(I.first); 368339d628a0SDimitry Andric } 368439d628a0SDimitry Andric // Sort the declarations by their location to make sure that the tests get a 368539d628a0SDimitry Andric // predictable order for the coverage mapping for the unused declarations. 368639d628a0SDimitry Andric if (CodeGenOpts.DumpCoverageMapping) 368739d628a0SDimitry Andric std::sort(DeferredDecls.begin(), DeferredDecls.end(), 368839d628a0SDimitry Andric [] (const Decl *LHS, const Decl *RHS) { 368939d628a0SDimitry Andric return LHS->getLocStart() < RHS->getLocStart(); 369039d628a0SDimitry Andric }); 369139d628a0SDimitry Andric for (const auto *D : DeferredDecls) { 369239d628a0SDimitry Andric switch (D->getKind()) { 369339d628a0SDimitry Andric case Decl::CXXConversion: 369439d628a0SDimitry Andric case Decl::CXXMethod: 369539d628a0SDimitry Andric case Decl::Function: 369639d628a0SDimitry Andric case Decl::ObjCMethod: { 369739d628a0SDimitry Andric CodeGenPGO PGO(*this); 369839d628a0SDimitry Andric GlobalDecl GD(cast<FunctionDecl>(D)); 369939d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 370039d628a0SDimitry Andric getFunctionLinkage(GD)); 370139d628a0SDimitry Andric break; 370239d628a0SDimitry Andric } 370339d628a0SDimitry Andric case Decl::CXXConstructor: { 370439d628a0SDimitry Andric CodeGenPGO PGO(*this); 370539d628a0SDimitry Andric GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 370639d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 370739d628a0SDimitry Andric getFunctionLinkage(GD)); 370839d628a0SDimitry Andric break; 370939d628a0SDimitry Andric } 371039d628a0SDimitry Andric case Decl::CXXDestructor: { 371139d628a0SDimitry Andric CodeGenPGO PGO(*this); 371239d628a0SDimitry Andric GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 371339d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 371439d628a0SDimitry Andric getFunctionLinkage(GD)); 371539d628a0SDimitry Andric break; 371639d628a0SDimitry Andric } 371739d628a0SDimitry Andric default: 371839d628a0SDimitry Andric break; 371939d628a0SDimitry Andric }; 3720f22ef01cSRoman Divacky } 3721f22ef01cSRoman Divacky } 3722ffd1746dSEd Schouten 3723ffd1746dSEd Schouten /// Turns the given pointer into a constant. 3724ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 3725ffd1746dSEd Schouten const void *Ptr) { 3726ffd1746dSEd Schouten uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 37276122f3e6SDimitry Andric llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 3728ffd1746dSEd Schouten return llvm::ConstantInt::get(i64, PtrInt); 3729ffd1746dSEd Schouten } 3730ffd1746dSEd Schouten 3731ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 3732ffd1746dSEd Schouten llvm::NamedMDNode *&GlobalMetadata, 3733ffd1746dSEd Schouten GlobalDecl D, 3734ffd1746dSEd Schouten llvm::GlobalValue *Addr) { 3735ffd1746dSEd Schouten if (!GlobalMetadata) 3736ffd1746dSEd Schouten GlobalMetadata = 3737ffd1746dSEd Schouten CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 3738ffd1746dSEd Schouten 3739ffd1746dSEd Schouten // TODO: should we report variant information for ctors/dtors? 374039d628a0SDimitry Andric llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 374139d628a0SDimitry Andric llvm::ConstantAsMetadata::get(GetPointerConstant( 374239d628a0SDimitry Andric CGM.getLLVMContext(), D.getDecl()))}; 37433b0f4066SDimitry Andric GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 3744ffd1746dSEd Schouten } 3745ffd1746dSEd Schouten 3746284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked 3747284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled 3748284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer 3749284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the 3750284c1978SDimitry Andric /// same translation unit. 3751284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() { 37528f0fd8f6SDimitry Andric for (auto &I : StaticExternCValues) { 37538f0fd8f6SDimitry Andric IdentifierInfo *Name = I.first; 37548f0fd8f6SDimitry Andric llvm::GlobalValue *Val = I.second; 3755284c1978SDimitry Andric if (Val && !getModule().getNamedValue(Name->getName())) 375659d1ed5bSDimitry Andric addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 3757284c1978SDimitry Andric } 3758284c1978SDimitry Andric } 3759284c1978SDimitry Andric 376059d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 376159d1ed5bSDimitry Andric GlobalDecl &Result) const { 376259d1ed5bSDimitry Andric auto Res = Manglings.find(MangledName); 376359d1ed5bSDimitry Andric if (Res == Manglings.end()) 376459d1ed5bSDimitry Andric return false; 376559d1ed5bSDimitry Andric Result = Res->getValue(); 376659d1ed5bSDimitry Andric return true; 376759d1ed5bSDimitry Andric } 376859d1ed5bSDimitry Andric 3769ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the 3770ffd1746dSEd Schouten /// current module with the Decls they came from. This is useful for 3771ffd1746dSEd Schouten /// projects using IR gen as a subroutine. 3772ffd1746dSEd Schouten /// 3773ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly 3774ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata 3775ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'. 3776ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() { 377759d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 3778ffd1746dSEd Schouten 377959d1ed5bSDimitry Andric for (auto &I : MangledDeclNames) { 378059d1ed5bSDimitry Andric llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 37810623d748SDimitry Andric // Some mangled names don't necessarily have an associated GlobalValue 37820623d748SDimitry Andric // in this module, e.g. if we mangled it for DebugInfo. 37830623d748SDimitry Andric if (Addr) 378459d1ed5bSDimitry Andric EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 3785ffd1746dSEd Schouten } 3786ffd1746dSEd Schouten } 3787ffd1746dSEd Schouten 3788ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current 3789ffd1746dSEd Schouten /// function. 3790ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() { 3791ffd1746dSEd Schouten if (LocalDeclMap.empty()) return; 3792ffd1746dSEd Schouten 3793ffd1746dSEd Schouten llvm::LLVMContext &Context = getLLVMContext(); 3794ffd1746dSEd Schouten 3795ffd1746dSEd Schouten // Find the unique metadata ID for this name. 3796ffd1746dSEd Schouten unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 3797ffd1746dSEd Schouten 379859d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 3799ffd1746dSEd Schouten 380059d1ed5bSDimitry Andric for (auto &I : LocalDeclMap) { 380159d1ed5bSDimitry Andric const Decl *D = I.first; 38020623d748SDimitry Andric llvm::Value *Addr = I.second.getPointer(); 380359d1ed5bSDimitry Andric if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 3804ffd1746dSEd Schouten llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 380539d628a0SDimitry Andric Alloca->setMetadata( 380639d628a0SDimitry Andric DeclPtrKind, llvm::MDNode::get( 380739d628a0SDimitry Andric Context, llvm::ValueAsMetadata::getConstant(DAddr))); 380859d1ed5bSDimitry Andric } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 3809ffd1746dSEd Schouten GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 3810ffd1746dSEd Schouten EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 3811ffd1746dSEd Schouten } 3812ffd1746dSEd Schouten } 3813ffd1746dSEd Schouten } 3814e580952dSDimitry Andric 3815f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() { 3816f785676fSDimitry Andric llvm::NamedMDNode *IdentMetadata = 3817f785676fSDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.ident"); 3818f785676fSDimitry Andric std::string Version = getClangFullVersion(); 3819f785676fSDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 3820f785676fSDimitry Andric 382139d628a0SDimitry Andric llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 3822f785676fSDimitry Andric IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 3823f785676fSDimitry Andric } 3824f785676fSDimitry Andric 382559d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() { 382639d628a0SDimitry Andric // Warning, new MangledDeclNames may be appended within this loop. 382739d628a0SDimitry Andric // We rely on MapVector insertions adding new elements to the end 382839d628a0SDimitry Andric // of the container. 382939d628a0SDimitry Andric // FIXME: Move this loop into the one target that needs it, and only 383039d628a0SDimitry Andric // loop over those declarations for which we couldn't emit the target 383139d628a0SDimitry Andric // metadata when we emitted the declaration. 383239d628a0SDimitry Andric for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 383339d628a0SDimitry Andric auto Val = *(MangledDeclNames.begin() + I); 383439d628a0SDimitry Andric const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 383539d628a0SDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(Val.second); 383659d1ed5bSDimitry Andric getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 383759d1ed5bSDimitry Andric } 383859d1ed5bSDimitry Andric } 383959d1ed5bSDimitry Andric 3840bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() { 3841bd5abe19SDimitry Andric if (!getCodeGenOpts().CoverageFile.empty()) { 3842bd5abe19SDimitry Andric if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 3843bd5abe19SDimitry Andric llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 3844bd5abe19SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 3845bd5abe19SDimitry Andric llvm::MDString *CoverageFile = 3846bd5abe19SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 3847bd5abe19SDimitry Andric for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 3848bd5abe19SDimitry Andric llvm::MDNode *CU = CUNode->getOperand(i); 384939d628a0SDimitry Andric llvm::Metadata *Elts[] = {CoverageFile, CU}; 385039d628a0SDimitry Andric GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 3851bd5abe19SDimitry Andric } 3852bd5abe19SDimitry Andric } 3853bd5abe19SDimitry Andric } 3854bd5abe19SDimitry Andric } 38553861d79fSDimitry Andric 385639d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { 38573861d79fSDimitry Andric // Sema has checked that all uuid strings are of the form 38583861d79fSDimitry Andric // "12345678-1234-1234-1234-1234567890ab". 38593861d79fSDimitry Andric assert(Uuid.size() == 36); 3860f785676fSDimitry Andric for (unsigned i = 0; i < 36; ++i) { 3861f785676fSDimitry Andric if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 3862f785676fSDimitry Andric else assert(isHexDigit(Uuid[i])); 38633861d79fSDimitry Andric } 38643861d79fSDimitry Andric 386539d628a0SDimitry Andric // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". 3866f785676fSDimitry Andric const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 38673861d79fSDimitry Andric 3868f785676fSDimitry Andric llvm::Constant *Field3[8]; 3869f785676fSDimitry Andric for (unsigned Idx = 0; Idx < 8; ++Idx) 3870f785676fSDimitry Andric Field3[Idx] = llvm::ConstantInt::get( 3871f785676fSDimitry Andric Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 38723861d79fSDimitry Andric 3873f785676fSDimitry Andric llvm::Constant *Fields[4] = { 3874f785676fSDimitry Andric llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 3875f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 3876f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 3877f785676fSDimitry Andric llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 3878f785676fSDimitry Andric }; 3879f785676fSDimitry Andric 3880f785676fSDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 38813861d79fSDimitry Andric } 388259d1ed5bSDimitry Andric 388359d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 388459d1ed5bSDimitry Andric bool ForEH) { 388559d1ed5bSDimitry Andric // Return a bogus pointer if RTTI is disabled, unless it's for EH. 388659d1ed5bSDimitry Andric // FIXME: should we even be calling this method if RTTI is disabled 388759d1ed5bSDimitry Andric // and it's not for EH? 388859d1ed5bSDimitry Andric if (!ForEH && !getLangOpts().RTTI) 388959d1ed5bSDimitry Andric return llvm::Constant::getNullValue(Int8PtrTy); 389059d1ed5bSDimitry Andric 389159d1ed5bSDimitry Andric if (ForEH && Ty->isObjCObjectPointerType() && 389259d1ed5bSDimitry Andric LangOpts.ObjCRuntime.isGNUFamily()) 389359d1ed5bSDimitry Andric return ObjCRuntime->GetEHType(Ty); 389459d1ed5bSDimitry Andric 389559d1ed5bSDimitry Andric return getCXXABI().getAddrOfRTTIDescriptor(Ty); 389659d1ed5bSDimitry Andric } 389759d1ed5bSDimitry Andric 389839d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 389939d628a0SDimitry Andric for (auto RefExpr : D->varlists()) { 390039d628a0SDimitry Andric auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 390139d628a0SDimitry Andric bool PerformInit = 390239d628a0SDimitry Andric VD->getAnyInitializer() && 390339d628a0SDimitry Andric !VD->getAnyInitializer()->isConstantInitializer(getContext(), 390439d628a0SDimitry Andric /*ForRef=*/false); 39050623d748SDimitry Andric 39060623d748SDimitry Andric Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 390733956c43SDimitry Andric if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 39080623d748SDimitry Andric VD, Addr, RefExpr->getLocStart(), PerformInit)) 390939d628a0SDimitry Andric CXXGlobalInits.push_back(InitFunction); 391039d628a0SDimitry Andric } 391139d628a0SDimitry Andric } 39128f0fd8f6SDimitry Andric 39130623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 39140623d748SDimitry Andric llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()]; 39150623d748SDimitry Andric if (InternalId) 39160623d748SDimitry Andric return InternalId; 39170623d748SDimitry Andric 39180623d748SDimitry Andric if (isExternallyVisible(T->getLinkage())) { 39198f0fd8f6SDimitry Andric std::string OutName; 39208f0fd8f6SDimitry Andric llvm::raw_string_ostream Out(OutName); 39210623d748SDimitry Andric getCXXABI().getMangleContext().mangleTypeName(T, Out); 39228f0fd8f6SDimitry Andric 39230623d748SDimitry Andric InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 39240623d748SDimitry Andric } else { 39250623d748SDimitry Andric InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 39260623d748SDimitry Andric llvm::ArrayRef<llvm::Metadata *>()); 39270623d748SDimitry Andric } 39280623d748SDimitry Andric 39290623d748SDimitry Andric return InternalId; 39300623d748SDimitry Andric } 39310623d748SDimitry Andric 39320623d748SDimitry Andric void CodeGenModule::CreateVTableBitSetEntry(llvm::NamedMDNode *BitsetsMD, 39330623d748SDimitry Andric llvm::GlobalVariable *VTable, 39340623d748SDimitry Andric CharUnits Offset, 39350623d748SDimitry Andric const CXXRecordDecl *RD) { 39360623d748SDimitry Andric llvm::Metadata *MD = 39370623d748SDimitry Andric CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 39388f0fd8f6SDimitry Andric llvm::Metadata *BitsetOps[] = { 39390623d748SDimitry Andric MD, llvm::ConstantAsMetadata::get(VTable), 39400623d748SDimitry Andric llvm::ConstantAsMetadata::get( 39410623d748SDimitry Andric llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))}; 39420623d748SDimitry Andric BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps)); 39430623d748SDimitry Andric 39440623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 39450623d748SDimitry Andric if (auto TypeId = CreateCfiIdForTypeMetadata(MD)) { 39460623d748SDimitry Andric llvm::Metadata *BitsetOps2[] = { 39470623d748SDimitry Andric llvm::ConstantAsMetadata::get(TypeId), 39488f0fd8f6SDimitry Andric llvm::ConstantAsMetadata::get(VTable), 39498f0fd8f6SDimitry Andric llvm::ConstantAsMetadata::get( 39508f0fd8f6SDimitry Andric llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))}; 39510623d748SDimitry Andric BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps2)); 39520623d748SDimitry Andric } 39530623d748SDimitry Andric } 39540623d748SDimitry Andric } 39550623d748SDimitry Andric 39560623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the 39570623d748SDimitry Andric // passed in function. 39580623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 39590623d748SDimitry Andric const FunctionDecl *FD) { 39600623d748SDimitry Andric StringRef TargetCPU = Target.getTargetOpts().CPU; 39610623d748SDimitry Andric if (const auto *TD = FD->getAttr<TargetAttr>()) { 39620623d748SDimitry Andric // If we have a TargetAttr build up the feature map based on that. 39630623d748SDimitry Andric TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); 39640623d748SDimitry Andric 39650623d748SDimitry Andric // Make a copy of the features as passed on the command line into the 39660623d748SDimitry Andric // beginning of the additional features from the function to override. 39670623d748SDimitry Andric ParsedAttr.first.insert(ParsedAttr.first.begin(), 39680623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.begin(), 39690623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.end()); 39700623d748SDimitry Andric 39710623d748SDimitry Andric if (ParsedAttr.second != "") 39720623d748SDimitry Andric TargetCPU = ParsedAttr.second; 39730623d748SDimitry Andric 39740623d748SDimitry Andric // Now populate the feature map, first with the TargetCPU which is either 39750623d748SDimitry Andric // the default or a new one from the target attribute string. Then we'll use 39760623d748SDimitry Andric // the passed in features (FeaturesAsWritten) along with the new ones from 39770623d748SDimitry Andric // the attribute. 39780623d748SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first); 39790623d748SDimitry Andric } else { 39800623d748SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 39810623d748SDimitry Andric Target.getTargetOpts().Features); 39820623d748SDimitry Andric } 39838f0fd8f6SDimitry Andric } 3984