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 } 378ea942507SDimitry Andric if (OpenMPRuntime) 379ea942507SDimitry Andric if (llvm::Function *OpenMPRegistrationFunction = 380ea942507SDimitry Andric OpenMPRuntime->emitRegistrationFunction()) 381ea942507SDimitry Andric AddGlobalCtor(OpenMPRegistrationFunction, 0); 3820623d748SDimitry Andric if (PGOReader) { 3830623d748SDimitry Andric getModule().setMaximumFunctionCount(PGOReader->getMaximumFunctionCount()); 3840623d748SDimitry Andric if (PGOStats.hasDiagnostics()) 38559d1ed5bSDimitry Andric PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 3860623d748SDimitry Andric } 387f22ef01cSRoman Divacky EmitCtorList(GlobalCtors, "llvm.global_ctors"); 388f22ef01cSRoman Divacky EmitCtorList(GlobalDtors, "llvm.global_dtors"); 3896122f3e6SDimitry Andric EmitGlobalAnnotations(); 390284c1978SDimitry Andric EmitStaticExternCAliases(); 39139d628a0SDimitry Andric EmitDeferredUnusedCoverageMappings(); 39239d628a0SDimitry Andric if (CoverageMapping) 39339d628a0SDimitry Andric CoverageMapping->emit(); 39459d1ed5bSDimitry Andric emitLLVMUsed(); 395ffd1746dSEd Schouten 396f785676fSDimitry Andric if (CodeGenOpts.Autolink && 397f785676fSDimitry Andric (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 398139f7f9bSDimitry Andric EmitModuleLinkOptions(); 399139f7f9bSDimitry Andric } 4000623d748SDimitry Andric if (CodeGenOpts.DwarfVersion) { 401f785676fSDimitry Andric // We actually want the latest version when there are conflicts. 402f785676fSDimitry Andric // We can change from Warning to Latest if such mode is supported. 403f785676fSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 404f785676fSDimitry Andric CodeGenOpts.DwarfVersion); 4050623d748SDimitry Andric } 4060623d748SDimitry Andric if (CodeGenOpts.EmitCodeView) { 4070623d748SDimitry Andric // Indicate that we want CodeView in the metadata. 4080623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 4090623d748SDimitry Andric } 4100623d748SDimitry Andric if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 4110623d748SDimitry Andric // We don't support LTO with 2 with different StrictVTablePointers 4120623d748SDimitry Andric // FIXME: we could support it by stripping all the information introduced 4130623d748SDimitry Andric // by StrictVTablePointers. 4140623d748SDimitry Andric 4150623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 4160623d748SDimitry Andric 4170623d748SDimitry Andric llvm::Metadata *Ops[2] = { 4180623d748SDimitry Andric llvm::MDString::get(VMContext, "StrictVTablePointers"), 4190623d748SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 4200623d748SDimitry Andric llvm::Type::getInt32Ty(VMContext), 1))}; 4210623d748SDimitry Andric 4220623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Require, 4230623d748SDimitry Andric "StrictVTablePointersRequirement", 4240623d748SDimitry Andric llvm::MDNode::get(VMContext, Ops)); 4250623d748SDimitry Andric } 426f785676fSDimitry Andric if (DebugInfo) 42759d1ed5bSDimitry Andric // We support a single version in the linked module. The LLVM 42859d1ed5bSDimitry Andric // parser will drop debug info with a different version number 42959d1ed5bSDimitry Andric // (and warn about it, too). 43059d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 431f785676fSDimitry Andric llvm::DEBUG_METADATA_VERSION); 432139f7f9bSDimitry Andric 43359d1ed5bSDimitry Andric // We need to record the widths of enums and wchar_t, so that we can generate 43459d1ed5bSDimitry Andric // the correct build attributes in the ARM backend. 43559d1ed5bSDimitry Andric llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 43659d1ed5bSDimitry Andric if ( Arch == llvm::Triple::arm 43759d1ed5bSDimitry Andric || Arch == llvm::Triple::armeb 43859d1ed5bSDimitry Andric || Arch == llvm::Triple::thumb 43959d1ed5bSDimitry Andric || Arch == llvm::Triple::thumbeb) { 44059d1ed5bSDimitry Andric // Width of wchar_t in bytes 44159d1ed5bSDimitry Andric uint64_t WCharWidth = 44259d1ed5bSDimitry Andric Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 44359d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 44459d1ed5bSDimitry Andric 44559d1ed5bSDimitry Andric // The minimum width of an enum in bytes 44659d1ed5bSDimitry Andric uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 44759d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 44859d1ed5bSDimitry Andric } 44959d1ed5bSDimitry Andric 4500623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 4510623d748SDimitry Andric // Indicate that we want cross-DSO control flow integrity checks. 4520623d748SDimitry Andric getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 4530623d748SDimitry Andric } 4540623d748SDimitry Andric 45539d628a0SDimitry Andric if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 45639d628a0SDimitry Andric llvm::PICLevel::Level PL = llvm::PICLevel::Default; 45739d628a0SDimitry Andric switch (PLevel) { 45839d628a0SDimitry Andric case 0: break; 45939d628a0SDimitry Andric case 1: PL = llvm::PICLevel::Small; break; 46039d628a0SDimitry Andric case 2: PL = llvm::PICLevel::Large; break; 46139d628a0SDimitry Andric default: llvm_unreachable("Invalid PIC Level"); 46239d628a0SDimitry Andric } 46339d628a0SDimitry Andric 46439d628a0SDimitry Andric getModule().setPICLevel(PL); 46539d628a0SDimitry Andric } 46639d628a0SDimitry Andric 4672754fe60SDimitry Andric SimplifyPersonality(); 4682754fe60SDimitry Andric 469ffd1746dSEd Schouten if (getCodeGenOpts().EmitDeclMetadata) 470ffd1746dSEd Schouten EmitDeclMetadata(); 471bd5abe19SDimitry Andric 472bd5abe19SDimitry Andric if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 473bd5abe19SDimitry Andric EmitCoverageFile(); 4746122f3e6SDimitry Andric 4756122f3e6SDimitry Andric if (DebugInfo) 4766122f3e6SDimitry Andric DebugInfo->finalize(); 477f785676fSDimitry Andric 478f785676fSDimitry Andric EmitVersionIdentMetadata(); 47959d1ed5bSDimitry Andric 48059d1ed5bSDimitry Andric EmitTargetMetadata(); 481f22ef01cSRoman Divacky } 482f22ef01cSRoman Divacky 4833b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 4843b0f4066SDimitry Andric // Make sure that this type is translated. 4853b0f4066SDimitry Andric Types.UpdateCompletedType(TD); 4863b0f4066SDimitry Andric } 4873b0f4066SDimitry Andric 4882754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 4892754fe60SDimitry Andric if (!TBAA) 49059d1ed5bSDimitry Andric return nullptr; 4912754fe60SDimitry Andric return TBAA->getTBAAInfo(QTy); 4922754fe60SDimitry Andric } 4932754fe60SDimitry Andric 494dff0c46cSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 495dff0c46cSDimitry Andric if (!TBAA) 49659d1ed5bSDimitry Andric return nullptr; 497dff0c46cSDimitry Andric return TBAA->getTBAAInfoForVTablePtr(); 498dff0c46cSDimitry Andric } 499dff0c46cSDimitry Andric 5003861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 5013861d79fSDimitry Andric if (!TBAA) 50259d1ed5bSDimitry Andric return nullptr; 5033861d79fSDimitry Andric return TBAA->getTBAAStructInfo(QTy); 5043861d79fSDimitry Andric } 5053861d79fSDimitry Andric 506139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy, 507139f7f9bSDimitry Andric llvm::MDNode *AccessN, 508139f7f9bSDimitry Andric uint64_t O) { 509139f7f9bSDimitry Andric if (!TBAA) 51059d1ed5bSDimitry Andric return nullptr; 511139f7f9bSDimitry Andric return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O); 512139f7f9bSDimitry Andric } 513139f7f9bSDimitry Andric 514f785676fSDimitry Andric /// Decorate the instruction with a TBAA tag. For both scalar TBAA 515f785676fSDimitry Andric /// and struct-path aware TBAA, the tag has the same format: 516f785676fSDimitry Andric /// base type, access type and offset. 517284c1978SDimitry Andric /// When ConvertTypeToTag is true, we create a tag based on the scalar type. 5180623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 519284c1978SDimitry Andric llvm::MDNode *TBAAInfo, 520284c1978SDimitry Andric bool ConvertTypeToTag) { 521f785676fSDimitry Andric if (ConvertTypeToTag && TBAA) 522284c1978SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, 523284c1978SDimitry Andric TBAA->getTBAAScalarTagInfo(TBAAInfo)); 524284c1978SDimitry Andric else 5252754fe60SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 5262754fe60SDimitry Andric } 5272754fe60SDimitry Andric 5280623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup( 5290623d748SDimitry Andric llvm::Instruction *I, const CXXRecordDecl *RD) { 5300623d748SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 5310623d748SDimitry Andric auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD); 5320623d748SDimitry Andric // Check if we have to wrap MDString in MDNode. 5330623d748SDimitry Andric if (!MetaDataNode) 5340623d748SDimitry Andric MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD); 5350623d748SDimitry Andric I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode); 5360623d748SDimitry Andric } 5370623d748SDimitry Andric 53859d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) { 53959d1ed5bSDimitry Andric unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 54059d1ed5bSDimitry Andric getDiags().Report(Context.getFullLoc(loc), diagID) << message; 541f22ef01cSRoman Divacky } 542f22ef01cSRoman Divacky 543f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 544f22ef01cSRoman Divacky /// specified stmt yet. 545f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 5466122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 547f22ef01cSRoman Divacky "cannot compile this %0 yet"); 548f22ef01cSRoman Divacky std::string Msg = Type; 549f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 550f22ef01cSRoman Divacky << Msg << S->getSourceRange(); 551f22ef01cSRoman Divacky } 552f22ef01cSRoman Divacky 553f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 554f22ef01cSRoman Divacky /// specified decl yet. 555f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 5566122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 557f22ef01cSRoman Divacky "cannot compile this %0 yet"); 558f22ef01cSRoman Divacky std::string Msg = Type; 559f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 560f22ef01cSRoman Divacky } 561f22ef01cSRoman Divacky 56217a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 56317a519f9SDimitry Andric return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 56417a519f9SDimitry Andric } 56517a519f9SDimitry Andric 566f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 5672754fe60SDimitry Andric const NamedDecl *D) const { 568f22ef01cSRoman Divacky // Internal definitions always have default visibility. 569f22ef01cSRoman Divacky if (GV->hasLocalLinkage()) { 570f22ef01cSRoman Divacky GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 571f22ef01cSRoman Divacky return; 572f22ef01cSRoman Divacky } 573f22ef01cSRoman Divacky 5742754fe60SDimitry Andric // Set visibility for definitions. 575139f7f9bSDimitry Andric LinkageInfo LV = D->getLinkageAndVisibility(); 576139f7f9bSDimitry Andric if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 577139f7f9bSDimitry Andric GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 578f22ef01cSRoman Divacky } 579f22ef01cSRoman Divacky 5807ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 5817ae0e2c9SDimitry Andric return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 5827ae0e2c9SDimitry Andric .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 5837ae0e2c9SDimitry Andric .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 5847ae0e2c9SDimitry Andric .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 5857ae0e2c9SDimitry Andric .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 5867ae0e2c9SDimitry Andric } 5877ae0e2c9SDimitry Andric 5887ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 5897ae0e2c9SDimitry Andric CodeGenOptions::TLSModel M) { 5907ae0e2c9SDimitry Andric switch (M) { 5917ae0e2c9SDimitry Andric case CodeGenOptions::GeneralDynamicTLSModel: 5927ae0e2c9SDimitry Andric return llvm::GlobalVariable::GeneralDynamicTLSModel; 5937ae0e2c9SDimitry Andric case CodeGenOptions::LocalDynamicTLSModel: 5947ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalDynamicTLSModel; 5957ae0e2c9SDimitry Andric case CodeGenOptions::InitialExecTLSModel: 5967ae0e2c9SDimitry Andric return llvm::GlobalVariable::InitialExecTLSModel; 5977ae0e2c9SDimitry Andric case CodeGenOptions::LocalExecTLSModel: 5987ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalExecTLSModel; 5997ae0e2c9SDimitry Andric } 6007ae0e2c9SDimitry Andric llvm_unreachable("Invalid TLS model!"); 6017ae0e2c9SDimitry Andric } 6027ae0e2c9SDimitry Andric 60339d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 604284c1978SDimitry Andric assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 6057ae0e2c9SDimitry Andric 60639d628a0SDimitry Andric llvm::GlobalValue::ThreadLocalMode TLM; 6073861d79fSDimitry Andric TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 6087ae0e2c9SDimitry Andric 6097ae0e2c9SDimitry Andric // Override the TLS model if it is explicitly specified. 61059d1ed5bSDimitry Andric if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 6117ae0e2c9SDimitry Andric TLM = GetLLVMTLSModel(Attr->getModel()); 6127ae0e2c9SDimitry Andric } 6137ae0e2c9SDimitry Andric 6147ae0e2c9SDimitry Andric GV->setThreadLocalMode(TLM); 6157ae0e2c9SDimitry Andric } 6167ae0e2c9SDimitry Andric 6176122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 61859d1ed5bSDimitry Andric StringRef &FoundStr = MangledDeclNames[GD.getCanonicalDecl()]; 61959d1ed5bSDimitry Andric if (!FoundStr.empty()) 62059d1ed5bSDimitry Andric return FoundStr; 621f22ef01cSRoman Divacky 62259d1ed5bSDimitry Andric const auto *ND = cast<NamedDecl>(GD.getDecl()); 623dff0c46cSDimitry Andric SmallString<256> Buffer; 62459d1ed5bSDimitry Andric StringRef Str; 62559d1ed5bSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 6262754fe60SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 62759d1ed5bSDimitry Andric if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) 6282754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 62959d1ed5bSDimitry Andric else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) 6302754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 631ffd1746dSEd Schouten else 6322754fe60SDimitry Andric getCXXABI().getMangleContext().mangleName(ND, Out); 63359d1ed5bSDimitry Andric Str = Out.str(); 63459d1ed5bSDimitry Andric } else { 63559d1ed5bSDimitry Andric IdentifierInfo *II = ND->getIdentifier(); 63659d1ed5bSDimitry Andric assert(II && "Attempt to mangle unnamed decl."); 63759d1ed5bSDimitry Andric Str = II->getName(); 638ffd1746dSEd Schouten } 639ffd1746dSEd Schouten 64039d628a0SDimitry Andric // Keep the first result in the case of a mangling collision. 64139d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Str, GD)); 64239d628a0SDimitry Andric return FoundStr = Result.first->first(); 64359d1ed5bSDimitry Andric } 64459d1ed5bSDimitry Andric 64559d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 646ffd1746dSEd Schouten const BlockDecl *BD) { 6472754fe60SDimitry Andric MangleContext &MangleCtx = getCXXABI().getMangleContext(); 6482754fe60SDimitry Andric const Decl *D = GD.getDecl(); 64959d1ed5bSDimitry Andric 65059d1ed5bSDimitry Andric SmallString<256> Buffer; 65159d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(Buffer); 65259d1ed5bSDimitry Andric if (!D) 6537ae0e2c9SDimitry Andric MangleCtx.mangleGlobalBlock(BD, 6547ae0e2c9SDimitry Andric dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 65559d1ed5bSDimitry Andric else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 6562754fe60SDimitry Andric MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 65759d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 6582754fe60SDimitry Andric MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 6592754fe60SDimitry Andric else 6602754fe60SDimitry Andric MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 66159d1ed5bSDimitry Andric 66239d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 66339d628a0SDimitry Andric return Result.first->first(); 664f22ef01cSRoman Divacky } 665f22ef01cSRoman Divacky 6666122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 667f22ef01cSRoman Divacky return getModule().getNamedValue(Name); 668f22ef01cSRoman Divacky } 669f22ef01cSRoman Divacky 670f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before 671f22ef01cSRoman Divacky /// main() runs. 67259d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 67359d1ed5bSDimitry Andric llvm::Constant *AssociatedData) { 674f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 67559d1ed5bSDimitry Andric GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 676f22ef01cSRoman Divacky } 677f22ef01cSRoman Divacky 678f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called 679f22ef01cSRoman Divacky /// when the module is unloaded. 680f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) { 681f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 68259d1ed5bSDimitry Andric GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 683f22ef01cSRoman Divacky } 684f22ef01cSRoman Divacky 685f22ef01cSRoman Divacky void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 686f22ef01cSRoman Divacky // Ctor function type is void()*. 687bd5abe19SDimitry Andric llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 688f22ef01cSRoman Divacky llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 689f22ef01cSRoman Divacky 69059d1ed5bSDimitry Andric // Get the type of a ctor entry, { i32, void ()*, i8* }. 69159d1ed5bSDimitry Andric llvm::StructType *CtorStructTy = llvm::StructType::get( 69239d628a0SDimitry Andric Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr); 693f22ef01cSRoman Divacky 694f22ef01cSRoman Divacky // Construct the constructor and destructor arrays. 695dff0c46cSDimitry Andric SmallVector<llvm::Constant *, 8> Ctors; 6968f0fd8f6SDimitry Andric for (const auto &I : Fns) { 697dff0c46cSDimitry Andric llvm::Constant *S[] = { 6988f0fd8f6SDimitry Andric llvm::ConstantInt::get(Int32Ty, I.Priority, false), 6998f0fd8f6SDimitry Andric llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy), 7008f0fd8f6SDimitry Andric (I.AssociatedData 7018f0fd8f6SDimitry Andric ? llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy) 7028f0fd8f6SDimitry Andric : llvm::Constant::getNullValue(VoidPtrTy))}; 703f22ef01cSRoman Divacky Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 704f22ef01cSRoman Divacky } 705f22ef01cSRoman Divacky 706f22ef01cSRoman Divacky if (!Ctors.empty()) { 707f22ef01cSRoman Divacky llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 708f22ef01cSRoman Divacky new llvm::GlobalVariable(TheModule, AT, false, 709f22ef01cSRoman Divacky llvm::GlobalValue::AppendingLinkage, 710f22ef01cSRoman Divacky llvm::ConstantArray::get(AT, Ctors), 711f22ef01cSRoman Divacky GlobalName); 712f22ef01cSRoman Divacky } 713f22ef01cSRoman Divacky } 714f22ef01cSRoman Divacky 715f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes 716f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 71759d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 718f785676fSDimitry Andric 719e580952dSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 720f22ef01cSRoman Divacky 72159d1ed5bSDimitry Andric if (isa<CXXDestructorDecl>(D) && 72259d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 72359d1ed5bSDimitry Andric GD.getDtorType())) { 72459d1ed5bSDimitry Andric // Destructor variants in the Microsoft C++ ABI are always internal or 72559d1ed5bSDimitry Andric // linkonce_odr thunks emitted on an as-needed basis. 72659d1ed5bSDimitry Andric return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage 72759d1ed5bSDimitry Andric : llvm::GlobalValue::LinkOnceODRLinkage; 728f22ef01cSRoman Divacky } 729f22ef01cSRoman Divacky 73059d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false); 73159d1ed5bSDimitry Andric } 732f22ef01cSRoman Divacky 73397bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) { 73497bc6c73SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 73597bc6c73SDimitry Andric 73697bc6c73SDimitry Andric if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) { 73797bc6c73SDimitry Andric if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) { 73897bc6c73SDimitry Andric // Don't dllexport/import destructor thunks. 73997bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 74097bc6c73SDimitry Andric return; 74197bc6c73SDimitry Andric } 74297bc6c73SDimitry Andric } 74397bc6c73SDimitry Andric 74497bc6c73SDimitry Andric if (FD->hasAttr<DLLImportAttr>()) 74597bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 74697bc6c73SDimitry Andric else if (FD->hasAttr<DLLExportAttr>()) 74797bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 74897bc6c73SDimitry Andric else 74997bc6c73SDimitry Andric F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 75097bc6c73SDimitry Andric } 75197bc6c73SDimitry Andric 7520623d748SDimitry Andric llvm::ConstantInt * 7530623d748SDimitry Andric CodeGenModule::CreateCfiIdForTypeMetadata(llvm::Metadata *MD) { 7540623d748SDimitry Andric llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 7550623d748SDimitry Andric if (!MDS) return nullptr; 7560623d748SDimitry Andric 7570623d748SDimitry Andric llvm::MD5 md5; 7580623d748SDimitry Andric llvm::MD5::MD5Result result; 7590623d748SDimitry Andric md5.update(MDS->getString()); 7600623d748SDimitry Andric md5.final(result); 7610623d748SDimitry Andric uint64_t id = 0; 7620623d748SDimitry Andric for (int i = 0; i < 8; ++i) 7630623d748SDimitry Andric id |= static_cast<uint64_t>(result[i]) << (i * 8); 7640623d748SDimitry Andric return llvm::ConstantInt::get(Int64Ty, id); 7650623d748SDimitry Andric } 7660623d748SDimitry Andric 76759d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D, 76859d1ed5bSDimitry Andric llvm::Function *F) { 76959d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 770f22ef01cSRoman Divacky } 771f22ef01cSRoman Divacky 772f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 773f22ef01cSRoman Divacky const CGFunctionInfo &Info, 774f22ef01cSRoman Divacky llvm::Function *F) { 775f22ef01cSRoman Divacky unsigned CallingConv; 776f22ef01cSRoman Divacky AttributeListType AttributeList; 777ea942507SDimitry Andric ConstructAttributeList(F->getName(), Info, D, AttributeList, CallingConv, 778ea942507SDimitry Andric false); 779139f7f9bSDimitry Andric F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList)); 780f22ef01cSRoman Divacky F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 781f22ef01cSRoman Divacky } 782f22ef01cSRoman Divacky 7836122f3e6SDimitry Andric /// Determines whether the language options require us to model 7846122f3e6SDimitry Andric /// unwind exceptions. We treat -fexceptions as mandating this 7856122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions 7866122f3e6SDimitry Andric /// enabled. This means, for example, that C with -fexceptions 7876122f3e6SDimitry Andric /// enables this. 788dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) { 7896122f3e6SDimitry Andric // If exceptions are completely disabled, obviously this is false. 790dff0c46cSDimitry Andric if (!LangOpts.Exceptions) return false; 7916122f3e6SDimitry Andric 7926122f3e6SDimitry Andric // If C++ exceptions are enabled, this is true. 793dff0c46cSDimitry Andric if (LangOpts.CXXExceptions) return true; 7946122f3e6SDimitry Andric 7956122f3e6SDimitry Andric // If ObjC exceptions are enabled, this depends on the ABI. 796dff0c46cSDimitry Andric if (LangOpts.ObjCExceptions) { 7977ae0e2c9SDimitry Andric return LangOpts.ObjCRuntime.hasUnwindExceptions(); 7986122f3e6SDimitry Andric } 7996122f3e6SDimitry Andric 8006122f3e6SDimitry Andric return true; 8016122f3e6SDimitry Andric } 8026122f3e6SDimitry Andric 803f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 804f22ef01cSRoman Divacky llvm::Function *F) { 805f785676fSDimitry Andric llvm::AttrBuilder B; 806f785676fSDimitry Andric 807bd5abe19SDimitry Andric if (CodeGenOpts.UnwindTables) 808f785676fSDimitry Andric B.addAttribute(llvm::Attribute::UWTable); 809bd5abe19SDimitry Andric 810dff0c46cSDimitry Andric if (!hasUnwindExceptions(LangOpts)) 811f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoUnwind); 812f22ef01cSRoman Divacky 8130623d748SDimitry Andric if (LangOpts.getStackProtector() == LangOptions::SSPOn) 8140623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtect); 8150623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 8160623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 8170623d748SDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 8180623d748SDimitry Andric B.addAttribute(llvm::Attribute::StackProtectReq); 8190623d748SDimitry Andric 8200623d748SDimitry Andric if (!D) { 8210623d748SDimitry Andric F->addAttributes(llvm::AttributeSet::FunctionIndex, 8220623d748SDimitry Andric llvm::AttributeSet::get( 8230623d748SDimitry Andric F->getContext(), 8240623d748SDimitry Andric llvm::AttributeSet::FunctionIndex, B)); 8250623d748SDimitry Andric return; 8260623d748SDimitry Andric } 8270623d748SDimitry Andric 8286122f3e6SDimitry Andric if (D->hasAttr<NakedAttr>()) { 8296122f3e6SDimitry Andric // Naked implies noinline: we should not be inlining such functions. 830f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Naked); 831f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 83259d1ed5bSDimitry Andric } else if (D->hasAttr<NoDuplicateAttr>()) { 83359d1ed5bSDimitry Andric B.addAttribute(llvm::Attribute::NoDuplicate); 834f785676fSDimitry Andric } else if (D->hasAttr<NoInlineAttr>()) { 835f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 83659d1ed5bSDimitry Andric } else if (D->hasAttr<AlwaysInlineAttr>() && 837f785676fSDimitry Andric !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex, 838f785676fSDimitry Andric llvm::Attribute::NoInline)) { 839f785676fSDimitry Andric // (noinline wins over always_inline, and we can't specify both in IR) 840f785676fSDimitry Andric B.addAttribute(llvm::Attribute::AlwaysInline); 8416122f3e6SDimitry Andric } 8422754fe60SDimitry Andric 843f785676fSDimitry Andric if (D->hasAttr<ColdAttr>()) { 84439d628a0SDimitry Andric if (!D->hasAttr<OptimizeNoneAttr>()) 845f785676fSDimitry Andric B.addAttribute(llvm::Attribute::OptimizeForSize); 846f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Cold); 847f785676fSDimitry Andric } 8483861d79fSDimitry Andric 8493861d79fSDimitry Andric if (D->hasAttr<MinSizeAttr>()) 850f785676fSDimitry Andric B.addAttribute(llvm::Attribute::MinSize); 851f22ef01cSRoman Divacky 852f785676fSDimitry Andric F->addAttributes(llvm::AttributeSet::FunctionIndex, 853f785676fSDimitry Andric llvm::AttributeSet::get( 854f785676fSDimitry Andric F->getContext(), llvm::AttributeSet::FunctionIndex, B)); 855f785676fSDimitry Andric 85639d628a0SDimitry Andric if (D->hasAttr<OptimizeNoneAttr>()) { 85739d628a0SDimitry Andric // OptimizeNone implies noinline; we should not be inlining such functions. 85839d628a0SDimitry Andric F->addFnAttr(llvm::Attribute::OptimizeNone); 85939d628a0SDimitry Andric F->addFnAttr(llvm::Attribute::NoInline); 86039d628a0SDimitry Andric 86139d628a0SDimitry Andric // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline. 8620623d748SDimitry Andric F->removeFnAttr(llvm::Attribute::OptimizeForSize); 8630623d748SDimitry Andric F->removeFnAttr(llvm::Attribute::MinSize); 86439d628a0SDimitry Andric assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 86539d628a0SDimitry Andric "OptimizeNone and AlwaysInline on same function!"); 86639d628a0SDimitry Andric 86739d628a0SDimitry Andric // Attribute 'inlinehint' has no effect on 'optnone' functions. 86839d628a0SDimitry Andric // Explicitly remove it from the set of function attributes. 86939d628a0SDimitry Andric F->removeFnAttr(llvm::Attribute::InlineHint); 87039d628a0SDimitry Andric } 87139d628a0SDimitry Andric 872f785676fSDimitry Andric if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 873f785676fSDimitry Andric F->setUnnamedAddr(true); 87459d1ed5bSDimitry Andric else if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) 875f785676fSDimitry Andric if (MD->isVirtual()) 876f785676fSDimitry Andric F->setUnnamedAddr(true); 877f785676fSDimitry Andric 878e580952dSDimitry Andric unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 879e580952dSDimitry Andric if (alignment) 880e580952dSDimitry Andric F->setAlignment(alignment); 881e580952dSDimitry Andric 8820623d748SDimitry Andric // Some C++ ABIs require 2-byte alignment for member functions, in order to 8830623d748SDimitry Andric // reserve a bit for differentiating between virtual and non-virtual member 8840623d748SDimitry Andric // functions. If the current target's C++ ABI requires this and this is a 8850623d748SDimitry Andric // member function, set its alignment accordingly. 8860623d748SDimitry Andric if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 887f22ef01cSRoman Divacky if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 888f22ef01cSRoman Divacky F->setAlignment(2); 889f22ef01cSRoman Divacky } 8900623d748SDimitry Andric } 891f22ef01cSRoman Divacky 892f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D, 893f22ef01cSRoman Divacky llvm::GlobalValue *GV) { 8940623d748SDimitry Andric if (const auto *ND = dyn_cast_or_null<NamedDecl>(D)) 8952754fe60SDimitry Andric setGlobalVisibility(GV, ND); 8962754fe60SDimitry Andric else 8972754fe60SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 898f22ef01cSRoman Divacky 8990623d748SDimitry Andric if (D && D->hasAttr<UsedAttr>()) 90059d1ed5bSDimitry Andric addUsedGlobal(GV); 90159d1ed5bSDimitry Andric } 90259d1ed5bSDimitry Andric 90339d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D, 90439d628a0SDimitry Andric llvm::GlobalValue *GV) { 90539d628a0SDimitry Andric SetCommonAttributes(D, GV); 90639d628a0SDimitry Andric 90739d628a0SDimitry Andric // Process the dllexport attribute based on whether the original definition 90839d628a0SDimitry Andric // (not necessarily the aliasee) was exported. 90939d628a0SDimitry Andric if (D->hasAttr<DLLExportAttr>()) 91039d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 91139d628a0SDimitry Andric } 91239d628a0SDimitry Andric 91359d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D, 91459d1ed5bSDimitry Andric llvm::GlobalObject *GO) { 91559d1ed5bSDimitry Andric SetCommonAttributes(D, GO); 916f22ef01cSRoman Divacky 9170623d748SDimitry Andric if (D) 918f22ef01cSRoman Divacky if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 91959d1ed5bSDimitry Andric GO->setSection(SA->getName()); 920f22ef01cSRoman Divacky 92197bc6c73SDimitry Andric getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 922f22ef01cSRoman Divacky } 923f22ef01cSRoman Divacky 924f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 925f22ef01cSRoman Divacky llvm::Function *F, 926f22ef01cSRoman Divacky const CGFunctionInfo &FI) { 927f22ef01cSRoman Divacky SetLLVMFunctionAttributes(D, FI, F); 928f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, F); 929f22ef01cSRoman Divacky 930f22ef01cSRoman Divacky F->setLinkage(llvm::Function::InternalLinkage); 931f22ef01cSRoman Divacky 93259d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 93359d1ed5bSDimitry Andric } 93459d1ed5bSDimitry Andric 93559d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, 93659d1ed5bSDimitry Andric const NamedDecl *ND) { 93759d1ed5bSDimitry Andric // Set linkage and visibility in case we never see a definition. 93859d1ed5bSDimitry Andric LinkageInfo LV = ND->getLinkageAndVisibility(); 93959d1ed5bSDimitry Andric if (LV.getLinkage() != ExternalLinkage) { 94059d1ed5bSDimitry Andric // Don't set internal linkage on declarations. 94159d1ed5bSDimitry Andric } else { 94259d1ed5bSDimitry Andric if (ND->hasAttr<DLLImportAttr>()) { 94359d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 94459d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 94559d1ed5bSDimitry Andric } else if (ND->hasAttr<DLLExportAttr>()) { 94659d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 94759d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 94859d1ed5bSDimitry Andric } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 94959d1ed5bSDimitry Andric // "extern_weak" is overloaded in LLVM; we probably should have 95059d1ed5bSDimitry Andric // separate linkage types for this. 95159d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 95259d1ed5bSDimitry Andric } 95359d1ed5bSDimitry Andric 95459d1ed5bSDimitry Andric // Set visibility on a declaration only if it's explicit. 95559d1ed5bSDimitry Andric if (LV.isVisibilityExplicit()) 95659d1ed5bSDimitry Andric GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility())); 95759d1ed5bSDimitry Andric } 958f22ef01cSRoman Divacky } 959f22ef01cSRoman Divacky 9600623d748SDimitry Andric void CodeGenModule::CreateFunctionBitSetEntry(const FunctionDecl *FD, 9610623d748SDimitry Andric llvm::Function *F) { 9620623d748SDimitry Andric // Only if we are checking indirect calls. 9630623d748SDimitry Andric if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 9640623d748SDimitry Andric return; 9650623d748SDimitry Andric 9660623d748SDimitry Andric // Non-static class methods are handled via vtable pointer checks elsewhere. 9670623d748SDimitry Andric if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 9680623d748SDimitry Andric return; 9690623d748SDimitry Andric 9700623d748SDimitry Andric // Additionally, if building with cross-DSO support... 9710623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 9720623d748SDimitry Andric // Don't emit entries for function declarations. In cross-DSO mode these are 9730623d748SDimitry Andric // handled with better precision at run time. 9740623d748SDimitry Andric if (!FD->hasBody()) 9750623d748SDimitry Andric return; 9760623d748SDimitry Andric // Skip available_externally functions. They won't be codegen'ed in the 9770623d748SDimitry Andric // current module anyway. 9780623d748SDimitry Andric if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally) 9790623d748SDimitry Andric return; 9800623d748SDimitry Andric } 9810623d748SDimitry Andric 9820623d748SDimitry Andric llvm::NamedMDNode *BitsetsMD = 9830623d748SDimitry Andric getModule().getOrInsertNamedMetadata("llvm.bitsets"); 9840623d748SDimitry Andric 9850623d748SDimitry Andric llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 9860623d748SDimitry Andric llvm::Metadata *BitsetOps[] = { 9870623d748SDimitry Andric MD, llvm::ConstantAsMetadata::get(F), 9880623d748SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int64Ty, 0))}; 9890623d748SDimitry Andric BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps)); 9900623d748SDimitry Andric 9910623d748SDimitry Andric // Emit a hash-based bit set entry for cross-DSO calls. 9920623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 9930623d748SDimitry Andric if (auto TypeId = CreateCfiIdForTypeMetadata(MD)) { 9940623d748SDimitry Andric llvm::Metadata *BitsetOps2[] = { 9950623d748SDimitry Andric llvm::ConstantAsMetadata::get(TypeId), 9960623d748SDimitry Andric llvm::ConstantAsMetadata::get(F), 9970623d748SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int64Ty, 0))}; 9980623d748SDimitry Andric BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps2)); 9990623d748SDimitry Andric } 10000623d748SDimitry Andric } 10010623d748SDimitry Andric } 10020623d748SDimitry Andric 100339d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 100439d628a0SDimitry Andric bool IsIncompleteFunction, 100539d628a0SDimitry Andric bool IsThunk) { 100633956c43SDimitry Andric if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 10073b0f4066SDimitry Andric // If this is an intrinsic function, set the function's attributes 10083b0f4066SDimitry Andric // to the intrinsic's attributes. 100933956c43SDimitry Andric F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 10103b0f4066SDimitry Andric return; 10113b0f4066SDimitry Andric } 10123b0f4066SDimitry Andric 101359d1ed5bSDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1014f22ef01cSRoman Divacky 1015f22ef01cSRoman Divacky if (!IsIncompleteFunction) 1016dff0c46cSDimitry Andric SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 1017f22ef01cSRoman Divacky 101859d1ed5bSDimitry Andric // Add the Returned attribute for "this", except for iOS 5 and earlier 101959d1ed5bSDimitry Andric // where substantial code, including the libstdc++ dylib, was compiled with 102059d1ed5bSDimitry Andric // GCC and does not actually return "this". 102139d628a0SDimitry Andric if (!IsThunk && getCXXABI().HasThisReturn(GD) && 102259d1ed5bSDimitry Andric !(getTarget().getTriple().isiOS() && 102359d1ed5bSDimitry Andric getTarget().getTriple().isOSVersionLT(6))) { 1024f785676fSDimitry Andric assert(!F->arg_empty() && 1025f785676fSDimitry Andric F->arg_begin()->getType() 1026f785676fSDimitry Andric ->canLosslesslyBitCastTo(F->getReturnType()) && 1027f785676fSDimitry Andric "unexpected this return"); 1028f785676fSDimitry Andric F->addAttribute(1, llvm::Attribute::Returned); 1029f785676fSDimitry Andric } 1030f785676fSDimitry Andric 1031f22ef01cSRoman Divacky // Only a few attributes are set on declarations; these may later be 1032f22ef01cSRoman Divacky // overridden by a definition. 1033f22ef01cSRoman Divacky 103459d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(F, FD); 10352754fe60SDimitry Andric 1036f22ef01cSRoman Divacky if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 1037f22ef01cSRoman Divacky F->setSection(SA->getName()); 1038f785676fSDimitry Andric 1039f785676fSDimitry Andric // A replaceable global allocation function does not act like a builtin by 1040f785676fSDimitry Andric // default, only if it is invoked by a new-expression or delete-expression. 1041f785676fSDimitry Andric if (FD->isReplaceableGlobalAllocationFunction()) 1042f785676fSDimitry Andric F->addAttribute(llvm::AttributeSet::FunctionIndex, 1043f785676fSDimitry Andric llvm::Attribute::NoBuiltin); 10440623d748SDimitry Andric 10450623d748SDimitry Andric CreateFunctionBitSetEntry(FD, F); 1046f22ef01cSRoman Divacky } 1047f22ef01cSRoman Divacky 104859d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 1049f22ef01cSRoman Divacky assert(!GV->isDeclaration() && 1050f22ef01cSRoman Divacky "Only globals with definition can force usage."); 105197bc6c73SDimitry Andric LLVMUsed.emplace_back(GV); 1052f22ef01cSRoman Divacky } 1053f22ef01cSRoman Divacky 105459d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 105559d1ed5bSDimitry Andric assert(!GV->isDeclaration() && 105659d1ed5bSDimitry Andric "Only globals with definition can force usage."); 105797bc6c73SDimitry Andric LLVMCompilerUsed.emplace_back(GV); 105859d1ed5bSDimitry Andric } 105959d1ed5bSDimitry Andric 106059d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name, 106159d1ed5bSDimitry Andric std::vector<llvm::WeakVH> &List) { 1062f22ef01cSRoman Divacky // Don't create llvm.used if there is no need. 106359d1ed5bSDimitry Andric if (List.empty()) 1064f22ef01cSRoman Divacky return; 1065f22ef01cSRoman Divacky 106659d1ed5bSDimitry Andric // Convert List to what ConstantArray needs. 1067dff0c46cSDimitry Andric SmallVector<llvm::Constant*, 8> UsedArray; 106859d1ed5bSDimitry Andric UsedArray.resize(List.size()); 106959d1ed5bSDimitry Andric for (unsigned i = 0, e = List.size(); i != e; ++i) { 1070f22ef01cSRoman Divacky UsedArray[i] = 107144f7b0dcSDimitry Andric llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 107244f7b0dcSDimitry Andric cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 1073f22ef01cSRoman Divacky } 1074f22ef01cSRoman Divacky 1075f22ef01cSRoman Divacky if (UsedArray.empty()) 1076f22ef01cSRoman Divacky return; 107759d1ed5bSDimitry Andric llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 1078f22ef01cSRoman Divacky 107959d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 108059d1ed5bSDimitry Andric CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 108159d1ed5bSDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), Name); 1082f22ef01cSRoman Divacky 1083f22ef01cSRoman Divacky GV->setSection("llvm.metadata"); 1084f22ef01cSRoman Divacky } 1085f22ef01cSRoman Divacky 108659d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() { 108759d1ed5bSDimitry Andric emitUsed(*this, "llvm.used", LLVMUsed); 108859d1ed5bSDimitry Andric emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 108959d1ed5bSDimitry Andric } 109059d1ed5bSDimitry Andric 1091f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 109239d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 1093f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1094f785676fSDimitry Andric } 1095f785676fSDimitry Andric 1096f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 1097f785676fSDimitry Andric llvm::SmallString<32> Opt; 1098f785676fSDimitry Andric getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 109939d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1100f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1101f785676fSDimitry Andric } 1102f785676fSDimitry Andric 1103f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) { 1104f785676fSDimitry Andric llvm::SmallString<24> Opt; 1105f785676fSDimitry Andric getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 110639d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 1107f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 1108f785676fSDimitry Andric } 1109f785676fSDimitry Andric 1110139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules 1111139f7f9bSDimitry Andric /// it depends on, using a postorder walk. 111239d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 111339d628a0SDimitry Andric SmallVectorImpl<llvm::Metadata *> &Metadata, 1114139f7f9bSDimitry Andric llvm::SmallPtrSet<Module *, 16> &Visited) { 1115139f7f9bSDimitry Andric // Import this module's parent. 111639d628a0SDimitry Andric if (Mod->Parent && Visited.insert(Mod->Parent).second) { 1117f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 1118139f7f9bSDimitry Andric } 1119139f7f9bSDimitry Andric 1120139f7f9bSDimitry Andric // Import this module's dependencies. 1121139f7f9bSDimitry Andric for (unsigned I = Mod->Imports.size(); I > 0; --I) { 112239d628a0SDimitry Andric if (Visited.insert(Mod->Imports[I - 1]).second) 1123f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 1124139f7f9bSDimitry Andric } 1125139f7f9bSDimitry Andric 1126139f7f9bSDimitry Andric // Add linker options to link against the libraries/frameworks 1127139f7f9bSDimitry Andric // described by this module. 1128f785676fSDimitry Andric llvm::LLVMContext &Context = CGM.getLLVMContext(); 1129139f7f9bSDimitry Andric for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 1130f785676fSDimitry Andric // Link against a framework. Frameworks are currently Darwin only, so we 1131f785676fSDimitry Andric // don't to ask TargetCodeGenInfo for the spelling of the linker option. 1132139f7f9bSDimitry Andric if (Mod->LinkLibraries[I-1].IsFramework) { 113339d628a0SDimitry Andric llvm::Metadata *Args[2] = { 1134139f7f9bSDimitry Andric llvm::MDString::get(Context, "-framework"), 113539d628a0SDimitry Andric llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 1136139f7f9bSDimitry Andric 1137139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 1138139f7f9bSDimitry Andric continue; 1139139f7f9bSDimitry Andric } 1140139f7f9bSDimitry Andric 1141139f7f9bSDimitry Andric // Link against a library. 1142f785676fSDimitry Andric llvm::SmallString<24> Opt; 1143f785676fSDimitry Andric CGM.getTargetCodeGenInfo().getDependentLibraryOption( 1144f785676fSDimitry Andric Mod->LinkLibraries[I-1].Library, Opt); 114539d628a0SDimitry Andric auto *OptString = llvm::MDString::get(Context, Opt); 1146139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, OptString)); 1147139f7f9bSDimitry Andric } 1148139f7f9bSDimitry Andric } 1149139f7f9bSDimitry Andric 1150139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() { 1151139f7f9bSDimitry Andric // Collect the set of all of the modules we want to visit to emit link 1152139f7f9bSDimitry Andric // options, which is essentially the imported modules and all of their 1153139f7f9bSDimitry Andric // non-explicit child modules. 1154139f7f9bSDimitry Andric llvm::SetVector<clang::Module *> LinkModules; 1155139f7f9bSDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 1156139f7f9bSDimitry Andric SmallVector<clang::Module *, 16> Stack; 1157139f7f9bSDimitry Andric 1158139f7f9bSDimitry Andric // Seed the stack with imported modules. 11598f0fd8f6SDimitry Andric for (Module *M : ImportedModules) 11608f0fd8f6SDimitry Andric if (Visited.insert(M).second) 11618f0fd8f6SDimitry Andric Stack.push_back(M); 1162139f7f9bSDimitry Andric 1163139f7f9bSDimitry Andric // Find all of the modules to import, making a little effort to prune 1164139f7f9bSDimitry Andric // non-leaf modules. 1165139f7f9bSDimitry Andric while (!Stack.empty()) { 1166f785676fSDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 1167139f7f9bSDimitry Andric 1168139f7f9bSDimitry Andric bool AnyChildren = false; 1169139f7f9bSDimitry Andric 1170139f7f9bSDimitry Andric // Visit the submodules of this module. 1171139f7f9bSDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 1172139f7f9bSDimitry Andric SubEnd = Mod->submodule_end(); 1173139f7f9bSDimitry Andric Sub != SubEnd; ++Sub) { 1174139f7f9bSDimitry Andric // Skip explicit children; they need to be explicitly imported to be 1175139f7f9bSDimitry Andric // linked against. 1176139f7f9bSDimitry Andric if ((*Sub)->IsExplicit) 1177139f7f9bSDimitry Andric continue; 1178139f7f9bSDimitry Andric 117939d628a0SDimitry Andric if (Visited.insert(*Sub).second) { 1180139f7f9bSDimitry Andric Stack.push_back(*Sub); 1181139f7f9bSDimitry Andric AnyChildren = true; 1182139f7f9bSDimitry Andric } 1183139f7f9bSDimitry Andric } 1184139f7f9bSDimitry Andric 1185139f7f9bSDimitry Andric // We didn't find any children, so add this module to the list of 1186139f7f9bSDimitry Andric // modules to link against. 1187139f7f9bSDimitry Andric if (!AnyChildren) { 1188139f7f9bSDimitry Andric LinkModules.insert(Mod); 1189139f7f9bSDimitry Andric } 1190139f7f9bSDimitry Andric } 1191139f7f9bSDimitry Andric 1192139f7f9bSDimitry Andric // Add link options for all of the imported modules in reverse topological 1193f785676fSDimitry Andric // order. We don't do anything to try to order import link flags with respect 1194f785676fSDimitry Andric // to linker options inserted by things like #pragma comment(). 119539d628a0SDimitry Andric SmallVector<llvm::Metadata *, 16> MetadataArgs; 1196139f7f9bSDimitry Andric Visited.clear(); 11978f0fd8f6SDimitry Andric for (Module *M : LinkModules) 11988f0fd8f6SDimitry Andric if (Visited.insert(M).second) 11998f0fd8f6SDimitry Andric addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 1200139f7f9bSDimitry Andric std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 1201f785676fSDimitry Andric LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 1202139f7f9bSDimitry Andric 1203139f7f9bSDimitry Andric // Add the linker options metadata flag. 1204139f7f9bSDimitry Andric getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options", 1205f785676fSDimitry Andric llvm::MDNode::get(getLLVMContext(), 1206f785676fSDimitry Andric LinkerOptionsMetadata)); 1207139f7f9bSDimitry Andric } 1208139f7f9bSDimitry Andric 1209f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() { 1210f22ef01cSRoman Divacky // Emit code for any potentially referenced deferred decls. Since a 1211f22ef01cSRoman Divacky // previously unused static decl may become used during the generation of code 1212f22ef01cSRoman Divacky // for a static function, iterate until no changes are made. 1213f22ef01cSRoman Divacky 1214f22ef01cSRoman Divacky if (!DeferredVTables.empty()) { 1215139f7f9bSDimitry Andric EmitDeferredVTables(); 1216139f7f9bSDimitry Andric 1217139f7f9bSDimitry Andric // Emitting a v-table doesn't directly cause more v-tables to 1218139f7f9bSDimitry Andric // become deferred, although it can cause functions to be 1219139f7f9bSDimitry Andric // emitted that then need those v-tables. 1220139f7f9bSDimitry Andric assert(DeferredVTables.empty()); 1221f22ef01cSRoman Divacky } 1222f22ef01cSRoman Divacky 1223139f7f9bSDimitry Andric // Stop if we're out of both deferred v-tables and deferred declarations. 122433956c43SDimitry Andric if (DeferredDeclsToEmit.empty()) 122533956c43SDimitry Andric return; 1226139f7f9bSDimitry Andric 122733956c43SDimitry Andric // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 122833956c43SDimitry Andric // work, it will not interfere with this. 122933956c43SDimitry Andric std::vector<DeferredGlobal> CurDeclsToEmit; 123033956c43SDimitry Andric CurDeclsToEmit.swap(DeferredDeclsToEmit); 123133956c43SDimitry Andric 123233956c43SDimitry Andric for (DeferredGlobal &G : CurDeclsToEmit) { 123359d1ed5bSDimitry Andric GlobalDecl D = G.GD; 123459d1ed5bSDimitry Andric llvm::GlobalValue *GV = G.GV; 123533956c43SDimitry Andric G.GV = nullptr; 1236f22ef01cSRoman Divacky 12370623d748SDimitry Andric // We should call GetAddrOfGlobal with IsForDefinition set to true in order 12380623d748SDimitry Andric // to get GlobalValue with exactly the type we need, not something that 12390623d748SDimitry Andric // might had been created for another decl with the same mangled name but 12400623d748SDimitry Andric // different type. 12410623d748SDimitry Andric // FIXME: Support for variables is not implemented yet. 12420623d748SDimitry Andric if (isa<FunctionDecl>(D.getDecl())) 12430623d748SDimitry Andric GV = cast<llvm::GlobalValue>(GetAddrOfGlobal(D, /*IsForDefinition=*/true)); 12440623d748SDimitry Andric else 124539d628a0SDimitry Andric if (!GV) 124639d628a0SDimitry Andric GV = GetGlobalValue(getMangledName(D)); 124739d628a0SDimitry Andric 1248f22ef01cSRoman Divacky // Check to see if we've already emitted this. This is necessary 1249f22ef01cSRoman Divacky // for a couple of reasons: first, decls can end up in the 1250f22ef01cSRoman Divacky // deferred-decls queue multiple times, and second, decls can end 1251f22ef01cSRoman Divacky // up with definitions in unusual ways (e.g. by an extern inline 1252f22ef01cSRoman Divacky // function acquiring a strong function redefinition). Just 1253f22ef01cSRoman Divacky // ignore these cases. 125439d628a0SDimitry Andric if (GV && !GV->isDeclaration()) 1255f22ef01cSRoman Divacky continue; 1256f22ef01cSRoman Divacky 1257f22ef01cSRoman Divacky // Otherwise, emit the definition and move on to the next one. 125859d1ed5bSDimitry Andric EmitGlobalDefinition(D, GV); 125933956c43SDimitry Andric 126033956c43SDimitry Andric // If we found out that we need to emit more decls, do that recursively. 126133956c43SDimitry Andric // This has the advantage that the decls are emitted in a DFS and related 126233956c43SDimitry Andric // ones are close together, which is convenient for testing. 126333956c43SDimitry Andric if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 126433956c43SDimitry Andric EmitDeferred(); 126533956c43SDimitry Andric assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 126633956c43SDimitry Andric } 1267f22ef01cSRoman Divacky } 1268f22ef01cSRoman Divacky } 1269f22ef01cSRoman Divacky 12706122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() { 12716122f3e6SDimitry Andric if (Annotations.empty()) 12726122f3e6SDimitry Andric return; 12736122f3e6SDimitry Andric 12746122f3e6SDimitry Andric // Create a new global variable for the ConstantStruct in the Module. 12756122f3e6SDimitry Andric llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 12766122f3e6SDimitry Andric Annotations[0]->getType(), Annotations.size()), Annotations); 127759d1ed5bSDimitry Andric auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 127859d1ed5bSDimitry Andric llvm::GlobalValue::AppendingLinkage, 127959d1ed5bSDimitry Andric Array, "llvm.global.annotations"); 12806122f3e6SDimitry Andric gv->setSection(AnnotationSection); 12816122f3e6SDimitry Andric } 12826122f3e6SDimitry Andric 1283139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1284f785676fSDimitry Andric llvm::Constant *&AStr = AnnotationStrings[Str]; 1285f785676fSDimitry Andric if (AStr) 1286f785676fSDimitry Andric return AStr; 12876122f3e6SDimitry Andric 12886122f3e6SDimitry Andric // Not found yet, create a new global. 1289dff0c46cSDimitry Andric llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 129059d1ed5bSDimitry Andric auto *gv = 129159d1ed5bSDimitry Andric new llvm::GlobalVariable(getModule(), s->getType(), true, 129259d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, s, ".str"); 12936122f3e6SDimitry Andric gv->setSection(AnnotationSection); 12946122f3e6SDimitry Andric gv->setUnnamedAddr(true); 1295f785676fSDimitry Andric AStr = gv; 12966122f3e6SDimitry Andric return gv; 12976122f3e6SDimitry Andric } 12986122f3e6SDimitry Andric 12996122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 13006122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 13016122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(Loc); 13026122f3e6SDimitry Andric if (PLoc.isValid()) 13036122f3e6SDimitry Andric return EmitAnnotationString(PLoc.getFilename()); 13046122f3e6SDimitry Andric return EmitAnnotationString(SM.getBufferName(Loc)); 13056122f3e6SDimitry Andric } 13066122f3e6SDimitry Andric 13076122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 13086122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 13096122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(L); 13106122f3e6SDimitry Andric unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 13116122f3e6SDimitry Andric SM.getExpansionLineNumber(L); 13126122f3e6SDimitry Andric return llvm::ConstantInt::get(Int32Ty, LineNo); 13136122f3e6SDimitry Andric } 13146122f3e6SDimitry Andric 1315f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1316f22ef01cSRoman Divacky const AnnotateAttr *AA, 13176122f3e6SDimitry Andric SourceLocation L) { 13186122f3e6SDimitry Andric // Get the globals for file name, annotation, and the line number. 13196122f3e6SDimitry Andric llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 13206122f3e6SDimitry Andric *UnitGV = EmitAnnotationUnit(L), 13216122f3e6SDimitry Andric *LineNoCst = EmitAnnotationLineNo(L); 1322f22ef01cSRoman Divacky 1323f22ef01cSRoman Divacky // Create the ConstantStruct for the global annotation. 1324f22ef01cSRoman Divacky llvm::Constant *Fields[4] = { 13256122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 13266122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 13276122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 13286122f3e6SDimitry Andric LineNoCst 1329f22ef01cSRoman Divacky }; 133017a519f9SDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 1331f22ef01cSRoman Divacky } 1332f22ef01cSRoman Divacky 13336122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 13346122f3e6SDimitry Andric llvm::GlobalValue *GV) { 13356122f3e6SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 13366122f3e6SDimitry Andric // Get the struct elements for these annotations. 133759d1ed5bSDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 133859d1ed5bSDimitry Andric Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 13396122f3e6SDimitry Andric } 13406122f3e6SDimitry Andric 134139d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn, 134239d628a0SDimitry Andric SourceLocation Loc) const { 134339d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 134439d628a0SDimitry Andric // Blacklist by function name. 134539d628a0SDimitry Andric if (SanitizerBL.isBlacklistedFunction(Fn->getName())) 134639d628a0SDimitry Andric return true; 134739d628a0SDimitry Andric // Blacklist by location. 13480623d748SDimitry Andric if (Loc.isValid()) 134939d628a0SDimitry Andric return SanitizerBL.isBlacklistedLocation(Loc); 135039d628a0SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 135139d628a0SDimitry Andric // it's located in the main file. 135239d628a0SDimitry Andric auto &SM = Context.getSourceManager(); 135339d628a0SDimitry Andric if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 135439d628a0SDimitry Andric return SanitizerBL.isBlacklistedFile(MainFile->getName()); 135539d628a0SDimitry Andric } 135639d628a0SDimitry Andric return false; 135739d628a0SDimitry Andric } 135839d628a0SDimitry Andric 135939d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 136039d628a0SDimitry Andric SourceLocation Loc, QualType Ty, 136139d628a0SDimitry Andric StringRef Category) const { 13628f0fd8f6SDimitry Andric // For now globals can be blacklisted only in ASan and KASan. 13638f0fd8f6SDimitry Andric if (!LangOpts.Sanitize.hasOneOf( 13648f0fd8f6SDimitry Andric SanitizerKind::Address | SanitizerKind::KernelAddress)) 136539d628a0SDimitry Andric return false; 136639d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 136739d628a0SDimitry Andric if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category)) 136839d628a0SDimitry Andric return true; 136939d628a0SDimitry Andric if (SanitizerBL.isBlacklistedLocation(Loc, Category)) 137039d628a0SDimitry Andric return true; 137139d628a0SDimitry Andric // Check global type. 137239d628a0SDimitry Andric if (!Ty.isNull()) { 137339d628a0SDimitry Andric // Drill down the array types: if global variable of a fixed type is 137439d628a0SDimitry Andric // blacklisted, we also don't instrument arrays of them. 137539d628a0SDimitry Andric while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 137639d628a0SDimitry Andric Ty = AT->getElementType(); 137739d628a0SDimitry Andric Ty = Ty.getCanonicalType().getUnqualifiedType(); 137839d628a0SDimitry Andric // We allow to blacklist only record types (classes, structs etc.) 137939d628a0SDimitry Andric if (Ty->isRecordType()) { 138039d628a0SDimitry Andric std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 138139d628a0SDimitry Andric if (SanitizerBL.isBlacklistedType(TypeStr, Category)) 138239d628a0SDimitry Andric return true; 138339d628a0SDimitry Andric } 138439d628a0SDimitry Andric } 138539d628a0SDimitry Andric return false; 138639d628a0SDimitry Andric } 138739d628a0SDimitry Andric 138839d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 1389e580952dSDimitry Andric // Never defer when EmitAllDecls is specified. 1390dff0c46cSDimitry Andric if (LangOpts.EmitAllDecls) 139139d628a0SDimitry Andric return true; 139239d628a0SDimitry Andric 139339d628a0SDimitry Andric return getContext().DeclMustBeEmitted(Global); 139439d628a0SDimitry Andric } 139539d628a0SDimitry Andric 139639d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 139739d628a0SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) 139839d628a0SDimitry Andric if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 139939d628a0SDimitry Andric // Implicit template instantiations may change linkage if they are later 140039d628a0SDimitry Andric // explicitly instantiated, so they should not be emitted eagerly. 1401f22ef01cSRoman Divacky return false; 1402875ed548SDimitry Andric // If OpenMP is enabled and threadprivates must be generated like TLS, delay 1403875ed548SDimitry Andric // codegen for global variables, because they may be marked as threadprivate. 1404875ed548SDimitry Andric if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 1405875ed548SDimitry Andric getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global)) 1406875ed548SDimitry Andric return false; 1407f22ef01cSRoman Divacky 140839d628a0SDimitry Andric return true; 1409f22ef01cSRoman Divacky } 1410f22ef01cSRoman Divacky 14110623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor( 14123861d79fSDimitry Andric const CXXUuidofExpr* E) { 14133861d79fSDimitry Andric // Sema has verified that IIDSource has a __declspec(uuid()), and that its 14143861d79fSDimitry Andric // well-formed. 1415f785676fSDimitry Andric StringRef Uuid = E->getUuidAsStringRef(Context); 1416f785676fSDimitry Andric std::string Name = "_GUID_" + Uuid.lower(); 1417f785676fSDimitry Andric std::replace(Name.begin(), Name.end(), '-', '_'); 14183861d79fSDimitry Andric 14190623d748SDimitry Andric // Contains a 32-bit field. 14200623d748SDimitry Andric CharUnits Alignment = CharUnits::fromQuantity(4); 14210623d748SDimitry Andric 14223861d79fSDimitry Andric // Look for an existing global. 14233861d79fSDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 14240623d748SDimitry Andric return ConstantAddress(GV, Alignment); 14253861d79fSDimitry Andric 142639d628a0SDimitry Andric llvm::Constant *Init = EmitUuidofInitializer(Uuid); 14273861d79fSDimitry Andric assert(Init && "failed to initialize as constant"); 14283861d79fSDimitry Andric 142959d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 1430f785676fSDimitry Andric getModule(), Init->getType(), 1431f785676fSDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 143233956c43SDimitry Andric if (supportsCOMDAT()) 143333956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 14340623d748SDimitry Andric return ConstantAddress(GV, Alignment); 14353861d79fSDimitry Andric } 14363861d79fSDimitry Andric 14370623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1438f22ef01cSRoman Divacky const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1439f22ef01cSRoman Divacky assert(AA && "No alias?"); 1440f22ef01cSRoman Divacky 14410623d748SDimitry Andric CharUnits Alignment = getContext().getDeclAlign(VD); 14426122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1443f22ef01cSRoman Divacky 1444f22ef01cSRoman Divacky // See if there is already something with the target's name in the module. 1445f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 14463861d79fSDimitry Andric if (Entry) { 14473861d79fSDimitry Andric unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 14480623d748SDimitry Andric auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 14490623d748SDimitry Andric return ConstantAddress(Ptr, Alignment); 14503861d79fSDimitry Andric } 1451f22ef01cSRoman Divacky 1452f22ef01cSRoman Divacky llvm::Constant *Aliasee; 1453f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 14543861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 14553861d79fSDimitry Andric GlobalDecl(cast<FunctionDecl>(VD)), 14562754fe60SDimitry Andric /*ForVTable=*/false); 1457f22ef01cSRoman Divacky else 1458f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 145959d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 146059d1ed5bSDimitry Andric nullptr); 14613861d79fSDimitry Andric 146259d1ed5bSDimitry Andric auto *F = cast<llvm::GlobalValue>(Aliasee); 1463f22ef01cSRoman Divacky F->setLinkage(llvm::Function::ExternalWeakLinkage); 1464f22ef01cSRoman Divacky WeakRefReferences.insert(F); 1465f22ef01cSRoman Divacky 14660623d748SDimitry Andric return ConstantAddress(Aliasee, Alignment); 1467f22ef01cSRoman Divacky } 1468f22ef01cSRoman Divacky 1469f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) { 147059d1ed5bSDimitry Andric const auto *Global = cast<ValueDecl>(GD.getDecl()); 1471f22ef01cSRoman Divacky 1472f22ef01cSRoman Divacky // Weak references don't produce any output by themselves. 1473f22ef01cSRoman Divacky if (Global->hasAttr<WeakRefAttr>()) 1474f22ef01cSRoman Divacky return; 1475f22ef01cSRoman Divacky 1476f22ef01cSRoman Divacky // If this is an alias definition (which otherwise looks like a declaration) 1477f22ef01cSRoman Divacky // emit it now. 1478f22ef01cSRoman Divacky if (Global->hasAttr<AliasAttr>()) 1479f22ef01cSRoman Divacky return EmitAliasDefinition(GD); 1480f22ef01cSRoman Divacky 14816122f3e6SDimitry Andric // If this is CUDA, be selective about which declarations we emit. 1482dff0c46cSDimitry Andric if (LangOpts.CUDA) { 148333956c43SDimitry Andric if (LangOpts.CUDAIsDevice) { 14846122f3e6SDimitry Andric if (!Global->hasAttr<CUDADeviceAttr>() && 14856122f3e6SDimitry Andric !Global->hasAttr<CUDAGlobalAttr>() && 14866122f3e6SDimitry Andric !Global->hasAttr<CUDAConstantAttr>() && 14876122f3e6SDimitry Andric !Global->hasAttr<CUDASharedAttr>()) 14886122f3e6SDimitry Andric return; 14896122f3e6SDimitry Andric } else { 14906122f3e6SDimitry Andric if (!Global->hasAttr<CUDAHostAttr>() && ( 14916122f3e6SDimitry Andric Global->hasAttr<CUDADeviceAttr>() || 14926122f3e6SDimitry Andric Global->hasAttr<CUDAConstantAttr>() || 14936122f3e6SDimitry Andric Global->hasAttr<CUDASharedAttr>())) 14946122f3e6SDimitry Andric return; 1495e580952dSDimitry Andric } 1496e580952dSDimitry Andric } 1497e580952dSDimitry Andric 1498ea942507SDimitry Andric // If this is OpenMP device, check if it is legal to emit this global 1499ea942507SDimitry Andric // normally. 1500ea942507SDimitry Andric if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 1501ea942507SDimitry Andric return; 1502ea942507SDimitry Andric 15036122f3e6SDimitry Andric // Ignore declarations, they will be emitted on their first use. 150459d1ed5bSDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 1505f22ef01cSRoman Divacky // Forward declarations are emitted lazily on first use. 15066122f3e6SDimitry Andric if (!FD->doesThisDeclarationHaveABody()) { 15076122f3e6SDimitry Andric if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1508f22ef01cSRoman Divacky return; 15096122f3e6SDimitry Andric 15106122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 151159d1ed5bSDimitry Andric 151259d1ed5bSDimitry Andric // Compute the function info and LLVM type. 151359d1ed5bSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 151459d1ed5bSDimitry Andric llvm::Type *Ty = getTypes().GetFunctionType(FI); 151559d1ed5bSDimitry Andric 151659d1ed5bSDimitry Andric GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 151759d1ed5bSDimitry Andric /*DontDefer=*/false); 15186122f3e6SDimitry Andric return; 15196122f3e6SDimitry Andric } 1520f22ef01cSRoman Divacky } else { 152159d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(Global); 1522f22ef01cSRoman Divacky assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1523f22ef01cSRoman Divacky 152459d1ed5bSDimitry Andric if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 152559d1ed5bSDimitry Andric !Context.isMSStaticDataMemberInlineDefinition(VD)) 1526f22ef01cSRoman Divacky return; 1527f22ef01cSRoman Divacky } 1528f22ef01cSRoman Divacky 152939d628a0SDimitry Andric // Defer code generation to first use when possible, e.g. if this is an inline 153039d628a0SDimitry Andric // function. If the global must always be emitted, do it eagerly if possible 153139d628a0SDimitry Andric // to benefit from cache locality. 153239d628a0SDimitry Andric if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 1533f22ef01cSRoman Divacky // Emit the definition if it can't be deferred. 1534f22ef01cSRoman Divacky EmitGlobalDefinition(GD); 1535f22ef01cSRoman Divacky return; 1536f22ef01cSRoman Divacky } 1537f22ef01cSRoman Divacky 1538e580952dSDimitry Andric // If we're deferring emission of a C++ variable with an 1539e580952dSDimitry Andric // initializer, remember the order in which it appeared in the file. 1540dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1541e580952dSDimitry Andric cast<VarDecl>(Global)->hasInit()) { 1542e580952dSDimitry Andric DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 154359d1ed5bSDimitry Andric CXXGlobalInits.push_back(nullptr); 1544e580952dSDimitry Andric } 1545e580952dSDimitry Andric 15466122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 154739d628a0SDimitry Andric if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) { 154839d628a0SDimitry Andric // The value has already been used and should therefore be emitted. 154959d1ed5bSDimitry Andric addDeferredDeclToEmit(GV, GD); 155039d628a0SDimitry Andric } else if (MustBeEmitted(Global)) { 155139d628a0SDimitry Andric // The value must be emitted, but cannot be emitted eagerly. 155239d628a0SDimitry Andric assert(!MayBeEmittedEagerly(Global)); 155339d628a0SDimitry Andric addDeferredDeclToEmit(/*GV=*/nullptr, GD); 155439d628a0SDimitry Andric } else { 1555f22ef01cSRoman Divacky // Otherwise, remember that we saw a deferred decl with this name. The 1556f22ef01cSRoman Divacky // first use of the mangled name will cause it to move into 1557f22ef01cSRoman Divacky // DeferredDeclsToEmit. 1558f22ef01cSRoman Divacky DeferredDecls[MangledName] = GD; 1559f22ef01cSRoman Divacky } 1560f22ef01cSRoman Divacky } 1561f22ef01cSRoman Divacky 1562f8254f43SDimitry Andric namespace { 1563f8254f43SDimitry Andric struct FunctionIsDirectlyRecursive : 1564f8254f43SDimitry Andric public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1565f8254f43SDimitry Andric const StringRef Name; 1566dff0c46cSDimitry Andric const Builtin::Context &BI; 1567f8254f43SDimitry Andric bool Result; 1568dff0c46cSDimitry Andric FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1569dff0c46cSDimitry Andric Name(N), BI(C), Result(false) { 1570f8254f43SDimitry Andric } 1571f8254f43SDimitry Andric typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1572f8254f43SDimitry Andric 1573f8254f43SDimitry Andric bool TraverseCallExpr(CallExpr *E) { 1574dff0c46cSDimitry Andric const FunctionDecl *FD = E->getDirectCallee(); 1575dff0c46cSDimitry Andric if (!FD) 1576f8254f43SDimitry Andric return true; 1577dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1578dff0c46cSDimitry Andric if (Attr && Name == Attr->getLabel()) { 1579dff0c46cSDimitry Andric Result = true; 1580dff0c46cSDimitry Andric return false; 1581dff0c46cSDimitry Andric } 1582dff0c46cSDimitry Andric unsigned BuiltinID = FD->getBuiltinID(); 15833dac3a9bSDimitry Andric if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 1584f8254f43SDimitry Andric return true; 15850623d748SDimitry Andric StringRef BuiltinName = BI.getName(BuiltinID); 1586dff0c46cSDimitry Andric if (BuiltinName.startswith("__builtin_") && 1587dff0c46cSDimitry Andric Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1588f8254f43SDimitry Andric Result = true; 1589f8254f43SDimitry Andric return false; 1590f8254f43SDimitry Andric } 1591f8254f43SDimitry Andric return true; 1592f8254f43SDimitry Andric } 1593f8254f43SDimitry Andric }; 15940623d748SDimitry Andric 15950623d748SDimitry Andric struct DLLImportFunctionVisitor 15960623d748SDimitry Andric : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 15970623d748SDimitry Andric bool SafeToInline = true; 15980623d748SDimitry Andric 15990623d748SDimitry Andric bool VisitVarDecl(VarDecl *VD) { 16000623d748SDimitry Andric // A thread-local variable cannot be imported. 16010623d748SDimitry Andric SafeToInline = !VD->getTLSKind(); 16020623d748SDimitry Andric return SafeToInline; 16030623d748SDimitry Andric } 16040623d748SDimitry Andric 16050623d748SDimitry Andric // Make sure we're not referencing non-imported vars or functions. 16060623d748SDimitry Andric bool VisitDeclRefExpr(DeclRefExpr *E) { 16070623d748SDimitry Andric ValueDecl *VD = E->getDecl(); 16080623d748SDimitry Andric if (isa<FunctionDecl>(VD)) 16090623d748SDimitry Andric SafeToInline = VD->hasAttr<DLLImportAttr>(); 16100623d748SDimitry Andric else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 16110623d748SDimitry Andric SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 16120623d748SDimitry Andric return SafeToInline; 16130623d748SDimitry Andric } 16140623d748SDimitry Andric bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 16150623d748SDimitry Andric SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 16160623d748SDimitry Andric return SafeToInline; 16170623d748SDimitry Andric } 16180623d748SDimitry Andric bool VisitCXXNewExpr(CXXNewExpr *E) { 16190623d748SDimitry Andric SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 16200623d748SDimitry Andric return SafeToInline; 16210623d748SDimitry Andric } 16220623d748SDimitry Andric }; 1623f8254f43SDimitry Andric } 1624f8254f43SDimitry Andric 1625dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another 1626dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin, 1627dff0c46cSDimitry Andric // ends up pointing to itself. 1628f8254f43SDimitry Andric bool 1629dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1630dff0c46cSDimitry Andric StringRef Name; 1631dff0c46cSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1632dff0c46cSDimitry Andric // asm labels are a special kind of mangling we have to support. 1633dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1634dff0c46cSDimitry Andric if (!Attr) 1635f8254f43SDimitry Andric return false; 1636dff0c46cSDimitry Andric Name = Attr->getLabel(); 1637dff0c46cSDimitry Andric } else { 1638dff0c46cSDimitry Andric Name = FD->getName(); 1639dff0c46cSDimitry Andric } 1640f8254f43SDimitry Andric 1641dff0c46cSDimitry Andric FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1642dff0c46cSDimitry Andric Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1643f8254f43SDimitry Andric return Walker.Result; 1644f8254f43SDimitry Andric } 1645f8254f43SDimitry Andric 1646f8254f43SDimitry Andric bool 1647f785676fSDimitry Andric CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1648f785676fSDimitry Andric if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1649f8254f43SDimitry Andric return true; 165059d1ed5bSDimitry Andric const auto *F = cast<FunctionDecl>(GD.getDecl()); 165159d1ed5bSDimitry Andric if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1652f8254f43SDimitry Andric return false; 16530623d748SDimitry Andric 16540623d748SDimitry Andric if (F->hasAttr<DLLImportAttr>()) { 16550623d748SDimitry Andric // Check whether it would be safe to inline this dllimport function. 16560623d748SDimitry Andric DLLImportFunctionVisitor Visitor; 16570623d748SDimitry Andric Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 16580623d748SDimitry Andric if (!Visitor.SafeToInline) 16590623d748SDimitry Andric return false; 16600623d748SDimitry Andric } 16610623d748SDimitry Andric 1662f8254f43SDimitry Andric // PR9614. Avoid cases where the source code is lying to us. An available 1663f8254f43SDimitry Andric // externally function should have an equivalent function somewhere else, 1664f8254f43SDimitry Andric // but a function that calls itself is clearly not equivalent to the real 1665f8254f43SDimitry Andric // implementation. 1666f8254f43SDimitry Andric // This happens in glibc's btowc and in some configure checks. 1667dff0c46cSDimitry Andric return !isTriviallyRecursive(F); 1668f8254f43SDimitry Andric } 1669f8254f43SDimitry Andric 1670f785676fSDimitry Andric /// If the type for the method's class was generated by 1671f785676fSDimitry Andric /// CGDebugInfo::createContextChain(), the cache contains only a 1672f785676fSDimitry Andric /// limited DIType without any declarations. Since EmitFunctionStart() 1673f785676fSDimitry Andric /// needs to find the canonical declaration for each method, we need 1674f785676fSDimitry Andric /// to construct the complete type prior to emitting the method. 1675f785676fSDimitry Andric void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) { 1676f785676fSDimitry Andric if (!D->isInstance()) 1677f785676fSDimitry Andric return; 1678f785676fSDimitry Andric 1679f785676fSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 1680f785676fSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) { 168159d1ed5bSDimitry Andric const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext())); 1682f785676fSDimitry Andric DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation()); 1683f785676fSDimitry Andric } 1684f785676fSDimitry Andric } 1685f785676fSDimitry Andric 168659d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 168759d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 1688f22ef01cSRoman Divacky 1689f22ef01cSRoman Divacky PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1690f22ef01cSRoman Divacky Context.getSourceManager(), 1691f22ef01cSRoman Divacky "Generating code for declaration"); 1692f22ef01cSRoman Divacky 1693f785676fSDimitry Andric if (isa<FunctionDecl>(D)) { 1694ffd1746dSEd Schouten // At -O0, don't generate IR for functions with available_externally 1695ffd1746dSEd Schouten // linkage. 1696f785676fSDimitry Andric if (!shouldEmitFunction(GD)) 1697ffd1746dSEd Schouten return; 1698ffd1746dSEd Schouten 169959d1ed5bSDimitry Andric if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 1700f785676fSDimitry Andric CompleteDIClassType(Method); 1701bd5abe19SDimitry Andric // Make sure to emit the definition(s) before we emit the thunks. 1702bd5abe19SDimitry Andric // This is necessary for the generation of certain thunks. 170359d1ed5bSDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 170439d628a0SDimitry Andric ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); 170559d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 170639d628a0SDimitry Andric ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); 1707bd5abe19SDimitry Andric else 170859d1ed5bSDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 1709bd5abe19SDimitry Andric 1710f22ef01cSRoman Divacky if (Method->isVirtual()) 1711f22ef01cSRoman Divacky getVTables().EmitThunks(GD); 1712f22ef01cSRoman Divacky 1713bd5abe19SDimitry Andric return; 1714ffd1746dSEd Schouten } 1715f22ef01cSRoman Divacky 171659d1ed5bSDimitry Andric return EmitGlobalFunctionDefinition(GD, GV); 1717ffd1746dSEd Schouten } 1718f22ef01cSRoman Divacky 171959d1ed5bSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 1720f22ef01cSRoman Divacky return EmitGlobalVarDefinition(VD); 1721f22ef01cSRoman Divacky 17226122f3e6SDimitry Andric llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1723f22ef01cSRoman Divacky } 1724f22ef01cSRoman Divacky 17250623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 17260623d748SDimitry Andric llvm::Function *NewFn); 17270623d748SDimitry Andric 1728f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1729f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there 1730f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 1731f22ef01cSRoman Divacky /// bitcasted to the right type. 1732f22ef01cSRoman Divacky /// 1733f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 1734f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created. 1735f22ef01cSRoman Divacky llvm::Constant * 17366122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 17376122f3e6SDimitry Andric llvm::Type *Ty, 1738f785676fSDimitry Andric GlobalDecl GD, bool ForVTable, 173939d628a0SDimitry Andric bool DontDefer, bool IsThunk, 17400623d748SDimitry Andric llvm::AttributeSet ExtraAttrs, 17410623d748SDimitry Andric bool IsForDefinition) { 1742f785676fSDimitry Andric const Decl *D = GD.getDecl(); 1743f785676fSDimitry Andric 1744f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 1745f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1746f22ef01cSRoman Divacky if (Entry) { 17473861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 1748f785676fSDimitry Andric const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 1749f22ef01cSRoman Divacky if (FD && !FD->hasAttr<WeakAttr>()) 1750f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 1751f22ef01cSRoman Divacky } 1752f22ef01cSRoman Divacky 175339d628a0SDimitry Andric // Handle dropped DLL attributes. 175439d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 175539d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 175639d628a0SDimitry Andric 17570623d748SDimitry Andric // If there are two attempts to define the same mangled name, issue an 17580623d748SDimitry Andric // error. 17590623d748SDimitry Andric if (IsForDefinition && !Entry->isDeclaration()) { 17600623d748SDimitry Andric GlobalDecl OtherGD; 17610623d748SDimitry Andric // Check that GD is not yet in ExplicitDefinitions is required to make 17620623d748SDimitry Andric // sure that we issue an error only once. 17630623d748SDimitry Andric if (lookupRepresentativeDecl(MangledName, OtherGD) && 17640623d748SDimitry Andric (GD.getCanonicalDecl().getDecl() != 17650623d748SDimitry Andric OtherGD.getCanonicalDecl().getDecl()) && 17660623d748SDimitry Andric DiagnosedConflictingDefinitions.insert(GD).second) { 17670623d748SDimitry Andric getDiags().Report(D->getLocation(), 17680623d748SDimitry Andric diag::err_duplicate_mangled_name); 17690623d748SDimitry Andric getDiags().Report(OtherGD.getDecl()->getLocation(), 17700623d748SDimitry Andric diag::note_previous_definition); 17710623d748SDimitry Andric } 17720623d748SDimitry Andric } 17730623d748SDimitry Andric 17740623d748SDimitry Andric if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 17750623d748SDimitry Andric (Entry->getType()->getElementType() == Ty)) { 1776f22ef01cSRoman Divacky return Entry; 17770623d748SDimitry Andric } 1778f22ef01cSRoman Divacky 1779f22ef01cSRoman Divacky // Make sure the result is of the correct type. 17800623d748SDimitry Andric // (If function is requested for a definition, we always need to create a new 17810623d748SDimitry Andric // function, not just return a bitcast.) 17820623d748SDimitry Andric if (!IsForDefinition) 178317a519f9SDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1784f22ef01cSRoman Divacky } 1785f22ef01cSRoman Divacky 1786f22ef01cSRoman Divacky // This function doesn't have a complete type (for example, the return 1787f22ef01cSRoman Divacky // type is an incomplete struct). Use a fake type instead, and make 1788f22ef01cSRoman Divacky // sure not to try to set attributes. 1789f22ef01cSRoman Divacky bool IsIncompleteFunction = false; 1790f22ef01cSRoman Divacky 17916122f3e6SDimitry Andric llvm::FunctionType *FTy; 1792f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(Ty)) { 1793f22ef01cSRoman Divacky FTy = cast<llvm::FunctionType>(Ty); 1794f22ef01cSRoman Divacky } else { 1795bd5abe19SDimitry Andric FTy = llvm::FunctionType::get(VoidTy, false); 1796f22ef01cSRoman Divacky IsIncompleteFunction = true; 1797f22ef01cSRoman Divacky } 1798ffd1746dSEd Schouten 17990623d748SDimitry Andric llvm::Function *F = 18000623d748SDimitry Andric llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 18010623d748SDimitry Andric Entry ? StringRef() : MangledName, &getModule()); 18020623d748SDimitry Andric 18030623d748SDimitry Andric // If we already created a function with the same mangled name (but different 18040623d748SDimitry Andric // type) before, take its name and add it to the list of functions to be 18050623d748SDimitry Andric // replaced with F at the end of CodeGen. 18060623d748SDimitry Andric // 18070623d748SDimitry Andric // This happens if there is a prototype for a function (e.g. "int f()") and 18080623d748SDimitry Andric // then a definition of a different type (e.g. "int f(int x)"). 18090623d748SDimitry Andric if (Entry) { 18100623d748SDimitry Andric F->takeName(Entry); 18110623d748SDimitry Andric 18120623d748SDimitry Andric // This might be an implementation of a function without a prototype, in 18130623d748SDimitry Andric // which case, try to do special replacement of calls which match the new 18140623d748SDimitry Andric // prototype. The really key thing here is that we also potentially drop 18150623d748SDimitry Andric // arguments from the call site so as to make a direct call, which makes the 18160623d748SDimitry Andric // inliner happier and suppresses a number of optimizer warnings (!) about 18170623d748SDimitry Andric // dropping arguments. 18180623d748SDimitry Andric if (!Entry->use_empty()) { 18190623d748SDimitry Andric ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 18200623d748SDimitry Andric Entry->removeDeadConstantUsers(); 18210623d748SDimitry Andric } 18220623d748SDimitry Andric 18230623d748SDimitry Andric llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 18240623d748SDimitry Andric F, Entry->getType()->getElementType()->getPointerTo()); 18250623d748SDimitry Andric addGlobalValReplacement(Entry, BC); 18260623d748SDimitry Andric } 18270623d748SDimitry Andric 1828f22ef01cSRoman Divacky assert(F->getName() == MangledName && "name was uniqued!"); 1829f785676fSDimitry Andric if (D) 183039d628a0SDimitry Andric SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 1831139f7f9bSDimitry Andric if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) { 1832139f7f9bSDimitry Andric llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex); 1833139f7f9bSDimitry Andric F->addAttributes(llvm::AttributeSet::FunctionIndex, 1834139f7f9bSDimitry Andric llvm::AttributeSet::get(VMContext, 1835139f7f9bSDimitry Andric llvm::AttributeSet::FunctionIndex, 1836139f7f9bSDimitry Andric B)); 1837139f7f9bSDimitry Andric } 1838f22ef01cSRoman Divacky 183959d1ed5bSDimitry Andric if (!DontDefer) { 184059d1ed5bSDimitry Andric // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 184159d1ed5bSDimitry Andric // each other bottoming out with the base dtor. Therefore we emit non-base 184259d1ed5bSDimitry Andric // dtors on usage, even if there is no dtor definition in the TU. 184359d1ed5bSDimitry Andric if (D && isa<CXXDestructorDecl>(D) && 184459d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 184559d1ed5bSDimitry Andric GD.getDtorType())) 184659d1ed5bSDimitry Andric addDeferredDeclToEmit(F, GD); 184759d1ed5bSDimitry Andric 1848f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 1849f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 1850f22ef01cSRoman Divacky // of the file. 185159d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 1852f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 185359d1ed5bSDimitry Andric // Move the potentially referenced deferred decl to the 185459d1ed5bSDimitry Andric // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 185559d1ed5bSDimitry Andric // don't need it anymore). 185659d1ed5bSDimitry Andric addDeferredDeclToEmit(F, DDI->second); 1857f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 18582754fe60SDimitry Andric 18592754fe60SDimitry Andric // Otherwise, there are cases we have to worry about where we're 18602754fe60SDimitry Andric // using a declaration for which we must emit a definition but where 18612754fe60SDimitry Andric // we might not find a top-level definition: 18622754fe60SDimitry Andric // - member functions defined inline in their classes 18632754fe60SDimitry Andric // - friend functions defined inline in some class 18642754fe60SDimitry Andric // - special member functions with implicit definitions 18652754fe60SDimitry Andric // If we ever change our AST traversal to walk into class methods, 18662754fe60SDimitry Andric // this will be unnecessary. 18672754fe60SDimitry Andric // 186859d1ed5bSDimitry Andric // We also don't emit a definition for a function if it's going to be an 186939d628a0SDimitry Andric // entry in a vtable, unless it's already marked as used. 1870f785676fSDimitry Andric } else if (getLangOpts().CPlusPlus && D) { 18712754fe60SDimitry Andric // Look for a declaration that's lexically in a record. 187239d628a0SDimitry Andric for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 187339d628a0SDimitry Andric FD = FD->getPreviousDecl()) { 18742754fe60SDimitry Andric if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 187539d628a0SDimitry Andric if (FD->doesThisDeclarationHaveABody()) { 187659d1ed5bSDimitry Andric addDeferredDeclToEmit(F, GD.getWithDecl(FD)); 18772754fe60SDimitry Andric break; 1878f22ef01cSRoman Divacky } 1879f22ef01cSRoman Divacky } 188039d628a0SDimitry Andric } 1881f22ef01cSRoman Divacky } 188259d1ed5bSDimitry Andric } 1883f22ef01cSRoman Divacky 1884f22ef01cSRoman Divacky // Make sure the result is of the requested type. 1885f22ef01cSRoman Divacky if (!IsIncompleteFunction) { 1886f22ef01cSRoman Divacky assert(F->getType()->getElementType() == Ty); 1887f22ef01cSRoman Divacky return F; 1888f22ef01cSRoman Divacky } 1889f22ef01cSRoman Divacky 189017a519f9SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1891f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(F, PTy); 1892f22ef01cSRoman Divacky } 1893f22ef01cSRoman Divacky 1894f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function. If Ty is 1895f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to 1896f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function). 1897f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 18986122f3e6SDimitry Andric llvm::Type *Ty, 189959d1ed5bSDimitry Andric bool ForVTable, 19000623d748SDimitry Andric bool DontDefer, 19010623d748SDimitry Andric bool IsForDefinition) { 1902f22ef01cSRoman Divacky // If there was no specific requested type, just convert it now. 19030623d748SDimitry Andric if (!Ty) { 19040623d748SDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 19050623d748SDimitry Andric auto CanonTy = Context.getCanonicalType(FD->getType()); 19060623d748SDimitry Andric Ty = getTypes().ConvertFunctionType(CanonTy, FD); 19070623d748SDimitry Andric } 1908ffd1746dSEd Schouten 19096122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 19100623d748SDimitry Andric return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 19110623d748SDimitry Andric /*IsThunk=*/false, llvm::AttributeSet(), 19120623d748SDimitry Andric IsForDefinition); 1913f22ef01cSRoman Divacky } 1914f22ef01cSRoman Divacky 1915f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified 1916f22ef01cSRoman Divacky /// type and name. 1917f22ef01cSRoman Divacky llvm::Constant * 19186122f3e6SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 19196122f3e6SDimitry Andric StringRef Name, 1920139f7f9bSDimitry Andric llvm::AttributeSet ExtraAttrs) { 192159d1ed5bSDimitry Andric llvm::Constant *C = 192259d1ed5bSDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 192339d628a0SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 192459d1ed5bSDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) 1925139f7f9bSDimitry Andric if (F->empty()) 1926139f7f9bSDimitry Andric F->setCallingConv(getRuntimeCC()); 1927139f7f9bSDimitry Andric return C; 1928f22ef01cSRoman Divacky } 1929f22ef01cSRoman Divacky 193039d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified 193139d628a0SDimitry Andric /// type and name. 193239d628a0SDimitry Andric llvm::Constant * 193339d628a0SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, 193439d628a0SDimitry Andric StringRef Name, 193539d628a0SDimitry Andric llvm::AttributeSet ExtraAttrs) { 193639d628a0SDimitry Andric llvm::Constant *C = 193739d628a0SDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 193839d628a0SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 193939d628a0SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) 194039d628a0SDimitry Andric if (F->empty()) 194139d628a0SDimitry Andric F->setCallingConv(getBuiltinCC()); 194239d628a0SDimitry Andric return C; 194339d628a0SDimitry Andric } 194439d628a0SDimitry Andric 1945dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted 1946dff0c46cSDimitry Andric /// as a constant. 1947dff0c46cSDimitry Andric /// 1948dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs 1949dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is 1950dff0c46cSDimitry Andric /// not written to during its construction. 1951dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 1952dff0c46cSDimitry Andric if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 1953f22ef01cSRoman Divacky return false; 1954bd5abe19SDimitry Andric 1955dff0c46cSDimitry Andric if (Context.getLangOpts().CPlusPlus) { 1956dff0c46cSDimitry Andric if (const CXXRecordDecl *Record 1957dff0c46cSDimitry Andric = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 1958dff0c46cSDimitry Andric return ExcludeCtor && !Record->hasMutableFields() && 1959dff0c46cSDimitry Andric Record->hasTrivialDestructor(); 1960f22ef01cSRoman Divacky } 1961bd5abe19SDimitry Andric 1962f22ef01cSRoman Divacky return true; 1963f22ef01cSRoman Divacky } 1964f22ef01cSRoman Divacky 1965f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 1966f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type. If there 1967f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 1968f22ef01cSRoman Divacky /// bitcasted to the right type. 1969f22ef01cSRoman Divacky /// 1970f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 1971f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created. 1972f22ef01cSRoman Divacky llvm::Constant * 19736122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 19746122f3e6SDimitry Andric llvm::PointerType *Ty, 197559d1ed5bSDimitry Andric const VarDecl *D) { 1976f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 1977f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1978f22ef01cSRoman Divacky if (Entry) { 19793861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 1980f22ef01cSRoman Divacky if (D && !D->hasAttr<WeakAttr>()) 1981f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 1982f22ef01cSRoman Divacky } 1983f22ef01cSRoman Divacky 198439d628a0SDimitry Andric // Handle dropped DLL attributes. 198539d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 198639d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 198739d628a0SDimitry Andric 1988f22ef01cSRoman Divacky if (Entry->getType() == Ty) 1989f22ef01cSRoman Divacky return Entry; 1990f22ef01cSRoman Divacky 1991f22ef01cSRoman Divacky // Make sure the result is of the correct type. 1992f785676fSDimitry Andric if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 1993f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 1994f785676fSDimitry Andric 1995f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(Entry, Ty); 1996f22ef01cSRoman Divacky } 1997f22ef01cSRoman Divacky 199859d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 199959d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 200059d1ed5bSDimitry Andric getModule(), Ty->getElementType(), false, 200159d1ed5bSDimitry Andric llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 200259d1ed5bSDimitry Andric llvm::GlobalVariable::NotThreadLocal, AddrSpace); 200359d1ed5bSDimitry Andric 2004f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 2005f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 2006f22ef01cSRoman Divacky // of the file. 200759d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 2008f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 2009f22ef01cSRoman Divacky // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 2010f22ef01cSRoman Divacky // list, and remove it from DeferredDecls (since we don't need it anymore). 201159d1ed5bSDimitry Andric addDeferredDeclToEmit(GV, DDI->second); 2012f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 2013f22ef01cSRoman Divacky } 2014f22ef01cSRoman Divacky 2015f22ef01cSRoman Divacky // Handle things which are present even on external declarations. 2016f22ef01cSRoman Divacky if (D) { 2017f22ef01cSRoman Divacky // FIXME: This code is overly simple and should be merged with other global 2018f22ef01cSRoman Divacky // handling. 2019dff0c46cSDimitry Andric GV->setConstant(isTypeConstant(D->getType(), false)); 2020f22ef01cSRoman Divacky 202133956c43SDimitry Andric GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 202233956c43SDimitry Andric 202359d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(GV, D); 20242754fe60SDimitry Andric 2025284c1978SDimitry Andric if (D->getTLSKind()) { 2026284c1978SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 20270623d748SDimitry Andric CXXThreadLocals.push_back(D); 20287ae0e2c9SDimitry Andric setTLSMode(GV, *D); 2029f22ef01cSRoman Divacky } 2030f785676fSDimitry Andric 2031f785676fSDimitry Andric // If required by the ABI, treat declarations of static data members with 2032f785676fSDimitry Andric // inline initializers as definitions. 203359d1ed5bSDimitry Andric if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 2034f785676fSDimitry Andric EmitGlobalVarDefinition(D); 2035284c1978SDimitry Andric } 2036f22ef01cSRoman Divacky 203759d1ed5bSDimitry Andric // Handle XCore specific ABI requirements. 203859d1ed5bSDimitry Andric if (getTarget().getTriple().getArch() == llvm::Triple::xcore && 203959d1ed5bSDimitry Andric D->getLanguageLinkage() == CLanguageLinkage && 204059d1ed5bSDimitry Andric D->getType().isConstant(Context) && 204159d1ed5bSDimitry Andric isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 204259d1ed5bSDimitry Andric GV->setSection(".cp.rodata"); 204359d1ed5bSDimitry Andric } 204459d1ed5bSDimitry Andric 20457ae0e2c9SDimitry Andric if (AddrSpace != Ty->getAddressSpace()) 2046f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty); 2047f785676fSDimitry Andric 2048f22ef01cSRoman Divacky return GV; 2049f22ef01cSRoman Divacky } 2050f22ef01cSRoman Divacky 20510623d748SDimitry Andric llvm::Constant * 20520623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, 20530623d748SDimitry Andric bool IsForDefinition) { 20540623d748SDimitry Andric if (isa<CXXConstructorDecl>(GD.getDecl())) 20550623d748SDimitry Andric return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()), 20560623d748SDimitry Andric getFromCtorType(GD.getCtorType()), 20570623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 20580623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 20590623d748SDimitry Andric else if (isa<CXXDestructorDecl>(GD.getDecl())) 20600623d748SDimitry Andric return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()), 20610623d748SDimitry Andric getFromDtorType(GD.getDtorType()), 20620623d748SDimitry Andric /*FnInfo=*/nullptr, /*FnType=*/nullptr, 20630623d748SDimitry Andric /*DontDefer=*/false, IsForDefinition); 20640623d748SDimitry Andric else if (isa<CXXMethodDecl>(GD.getDecl())) { 20650623d748SDimitry Andric auto FInfo = &getTypes().arrangeCXXMethodDeclaration( 20660623d748SDimitry Andric cast<CXXMethodDecl>(GD.getDecl())); 20670623d748SDimitry Andric auto Ty = getTypes().GetFunctionType(*FInfo); 20680623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 20690623d748SDimitry Andric IsForDefinition); 20700623d748SDimitry Andric } else if (isa<FunctionDecl>(GD.getDecl())) { 20710623d748SDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 20720623d748SDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 20730623d748SDimitry Andric return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 20740623d748SDimitry Andric IsForDefinition); 20750623d748SDimitry Andric } else 20760623d748SDimitry Andric return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl())); 20770623d748SDimitry Andric } 2078f22ef01cSRoman Divacky 20792754fe60SDimitry Andric llvm::GlobalVariable * 20806122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 20816122f3e6SDimitry Andric llvm::Type *Ty, 20822754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage) { 20832754fe60SDimitry Andric llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 208459d1ed5bSDimitry Andric llvm::GlobalVariable *OldGV = nullptr; 20852754fe60SDimitry Andric 20862754fe60SDimitry Andric if (GV) { 20872754fe60SDimitry Andric // Check if the variable has the right type. 20882754fe60SDimitry Andric if (GV->getType()->getElementType() == Ty) 20892754fe60SDimitry Andric return GV; 20902754fe60SDimitry Andric 20912754fe60SDimitry Andric // Because C++ name mangling, the only way we can end up with an already 20922754fe60SDimitry Andric // existing global with the same name is if it has been declared extern "C". 20932754fe60SDimitry Andric assert(GV->isDeclaration() && "Declaration has wrong type!"); 20942754fe60SDimitry Andric OldGV = GV; 20952754fe60SDimitry Andric } 20962754fe60SDimitry Andric 20972754fe60SDimitry Andric // Create a new variable. 20982754fe60SDimitry Andric GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 209959d1ed5bSDimitry Andric Linkage, nullptr, Name); 21002754fe60SDimitry Andric 21012754fe60SDimitry Andric if (OldGV) { 21022754fe60SDimitry Andric // Replace occurrences of the old variable if needed. 21032754fe60SDimitry Andric GV->takeName(OldGV); 21042754fe60SDimitry Andric 21052754fe60SDimitry Andric if (!OldGV->use_empty()) { 21062754fe60SDimitry Andric llvm::Constant *NewPtrForOldDecl = 21072754fe60SDimitry Andric llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 21082754fe60SDimitry Andric OldGV->replaceAllUsesWith(NewPtrForOldDecl); 21092754fe60SDimitry Andric } 21102754fe60SDimitry Andric 21112754fe60SDimitry Andric OldGV->eraseFromParent(); 21122754fe60SDimitry Andric } 21132754fe60SDimitry Andric 211433956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker() && 211533956c43SDimitry Andric !GV->hasAvailableExternallyLinkage()) 211633956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 211733956c43SDimitry Andric 21182754fe60SDimitry Andric return GV; 21192754fe60SDimitry Andric } 21202754fe60SDimitry Andric 2121f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 2122f22ef01cSRoman Divacky /// given global variable. If Ty is non-null and if the global doesn't exist, 2123cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the 2124f22ef01cSRoman Divacky /// normal requested type would be. 2125f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 21266122f3e6SDimitry Andric llvm::Type *Ty) { 2127f22ef01cSRoman Divacky assert(D->hasGlobalStorage() && "Not a global variable"); 2128f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 212959d1ed5bSDimitry Andric if (!Ty) 2130f22ef01cSRoman Divacky Ty = getTypes().ConvertTypeForMem(ASTTy); 2131f22ef01cSRoman Divacky 21326122f3e6SDimitry Andric llvm::PointerType *PTy = 21333b0f4066SDimitry Andric llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 2134f22ef01cSRoman Divacky 21356122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2136f22ef01cSRoman Divacky return GetOrCreateLLVMGlobal(MangledName, PTy, D); 2137f22ef01cSRoman Divacky } 2138f22ef01cSRoman Divacky 2139f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the 2140f22ef01cSRoman Divacky /// specified type and name. 2141f22ef01cSRoman Divacky llvm::Constant * 21426122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 21436122f3e6SDimitry Andric StringRef Name) { 214459d1ed5bSDimitry Andric return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr); 2145f22ef01cSRoman Divacky } 2146f22ef01cSRoman Divacky 2147f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 2148f22ef01cSRoman Divacky assert(!D->getInit() && "Cannot emit definite definitions here!"); 2149f22ef01cSRoman Divacky 215039d628a0SDimitry Andric if (!MustBeEmitted(D)) { 2151f22ef01cSRoman Divacky // If we have not seen a reference to this variable yet, place it 2152f22ef01cSRoman Divacky // into the deferred declarations table to be emitted if needed 2153f22ef01cSRoman Divacky // later. 21546122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 2155f22ef01cSRoman Divacky if (!GetGlobalValue(MangledName)) { 2156f22ef01cSRoman Divacky DeferredDecls[MangledName] = D; 2157f22ef01cSRoman Divacky return; 2158f22ef01cSRoman Divacky } 2159f22ef01cSRoman Divacky } 2160f22ef01cSRoman Divacky 2161f22ef01cSRoman Divacky // The tentative definition is the only definition. 2162f22ef01cSRoman Divacky EmitGlobalVarDefinition(D); 2163f22ef01cSRoman Divacky } 2164f22ef01cSRoman Divacky 21656122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 21662754fe60SDimitry Andric return Context.toCharUnitsFromBits( 21670623d748SDimitry Andric getDataLayout().getTypeStoreSizeInBits(Ty)); 2168f22ef01cSRoman Divacky } 2169f22ef01cSRoman Divacky 21707ae0e2c9SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 21717ae0e2c9SDimitry Andric unsigned AddrSpace) { 217233956c43SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 21737ae0e2c9SDimitry Andric if (D->hasAttr<CUDAConstantAttr>()) 21747ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 21757ae0e2c9SDimitry Andric else if (D->hasAttr<CUDASharedAttr>()) 21767ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 21777ae0e2c9SDimitry Andric else 21787ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 21797ae0e2c9SDimitry Andric } 21807ae0e2c9SDimitry Andric 21817ae0e2c9SDimitry Andric return AddrSpace; 21827ae0e2c9SDimitry Andric } 21837ae0e2c9SDimitry Andric 2184284c1978SDimitry Andric template<typename SomeDecl> 2185284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 2186284c1978SDimitry Andric llvm::GlobalValue *GV) { 2187284c1978SDimitry Andric if (!getLangOpts().CPlusPlus) 2188284c1978SDimitry Andric return; 2189284c1978SDimitry Andric 2190284c1978SDimitry Andric // Must have 'used' attribute, or else inline assembly can't rely on 2191284c1978SDimitry Andric // the name existing. 2192284c1978SDimitry Andric if (!D->template hasAttr<UsedAttr>()) 2193284c1978SDimitry Andric return; 2194284c1978SDimitry Andric 2195284c1978SDimitry Andric // Must have internal linkage and an ordinary name. 2196f785676fSDimitry Andric if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 2197284c1978SDimitry Andric return; 2198284c1978SDimitry Andric 2199284c1978SDimitry Andric // Must be in an extern "C" context. Entities declared directly within 2200284c1978SDimitry Andric // a record are not extern "C" even if the record is in such a context. 2201f785676fSDimitry Andric const SomeDecl *First = D->getFirstDecl(); 2202284c1978SDimitry Andric if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 2203284c1978SDimitry Andric return; 2204284c1978SDimitry Andric 2205284c1978SDimitry Andric // OK, this is an internal linkage entity inside an extern "C" linkage 2206284c1978SDimitry Andric // specification. Make a note of that so we can give it the "expected" 2207284c1978SDimitry Andric // mangled name if nothing else is using that name. 2208284c1978SDimitry Andric std::pair<StaticExternCMap::iterator, bool> R = 2209284c1978SDimitry Andric StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 2210284c1978SDimitry Andric 2211284c1978SDimitry Andric // If we have multiple internal linkage entities with the same name 2212284c1978SDimitry Andric // in extern "C" regions, none of them gets that name. 2213284c1978SDimitry Andric if (!R.second) 221459d1ed5bSDimitry Andric R.first->second = nullptr; 2215284c1978SDimitry Andric } 2216284c1978SDimitry Andric 221733956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 221833956c43SDimitry Andric if (!CGM.supportsCOMDAT()) 221933956c43SDimitry Andric return false; 222033956c43SDimitry Andric 222133956c43SDimitry Andric if (D.hasAttr<SelectAnyAttr>()) 222233956c43SDimitry Andric return true; 222333956c43SDimitry Andric 222433956c43SDimitry Andric GVALinkage Linkage; 222533956c43SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(&D)) 222633956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 222733956c43SDimitry Andric else 222833956c43SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 222933956c43SDimitry Andric 223033956c43SDimitry Andric switch (Linkage) { 223133956c43SDimitry Andric case GVA_Internal: 223233956c43SDimitry Andric case GVA_AvailableExternally: 223333956c43SDimitry Andric case GVA_StrongExternal: 223433956c43SDimitry Andric return false; 223533956c43SDimitry Andric case GVA_DiscardableODR: 223633956c43SDimitry Andric case GVA_StrongODR: 223733956c43SDimitry Andric return true; 223833956c43SDimitry Andric } 223933956c43SDimitry Andric llvm_unreachable("No such linkage"); 224033956c43SDimitry Andric } 224133956c43SDimitry Andric 224233956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 224333956c43SDimitry Andric llvm::GlobalObject &GO) { 224433956c43SDimitry Andric if (!shouldBeInCOMDAT(*this, D)) 224533956c43SDimitry Andric return; 224633956c43SDimitry Andric GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 224733956c43SDimitry Andric } 224833956c43SDimitry Andric 2249f22ef01cSRoman Divacky void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 225059d1ed5bSDimitry Andric llvm::Constant *Init = nullptr; 2251f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 2252dff0c46cSDimitry Andric CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 2253dff0c46cSDimitry Andric bool NeedsGlobalCtor = false; 2254dff0c46cSDimitry Andric bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 2255f22ef01cSRoman Divacky 2256dff0c46cSDimitry Andric const VarDecl *InitDecl; 2257dff0c46cSDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 2258f22ef01cSRoman Divacky 22590623d748SDimitry Andric // CUDA E.2.4.1 "__shared__ variables cannot have an initialization as part 22600623d748SDimitry Andric // of their declaration." 22610623d748SDimitry Andric if (getLangOpts().CPlusPlus && getLangOpts().CUDAIsDevice 22620623d748SDimitry Andric && D->hasAttr<CUDASharedAttr>()) { 22630623d748SDimitry Andric if (InitExpr) { 22640623d748SDimitry Andric const auto *C = dyn_cast<CXXConstructExpr>(InitExpr); 22650623d748SDimitry Andric if (C == nullptr || !C->getConstructor()->hasTrivialBody()) 22660623d748SDimitry Andric Error(D->getLocation(), 22670623d748SDimitry Andric "__shared__ variable cannot have an initialization."); 22680623d748SDimitry Andric } 22690623d748SDimitry Andric Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 22700623d748SDimitry Andric } else if (!InitExpr) { 2271f22ef01cSRoman Divacky // This is a tentative definition; tentative definitions are 2272f22ef01cSRoman Divacky // implicitly initialized with { 0 }. 2273f22ef01cSRoman Divacky // 2274f22ef01cSRoman Divacky // Note that tentative definitions are only emitted at the end of 2275f22ef01cSRoman Divacky // a translation unit, so they should never have incomplete 2276f22ef01cSRoman Divacky // type. In addition, EmitTentativeDefinition makes sure that we 2277f22ef01cSRoman Divacky // never attempt to emit a tentative definition if a real one 2278f22ef01cSRoman Divacky // exists. A use may still exists, however, so we still may need 2279f22ef01cSRoman Divacky // to do a RAUW. 2280f22ef01cSRoman Divacky assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 2281f22ef01cSRoman Divacky Init = EmitNullConstant(D->getType()); 2282f22ef01cSRoman Divacky } else { 22837ae0e2c9SDimitry Andric initializedGlobalDecl = GlobalDecl(D); 2284dff0c46cSDimitry Andric Init = EmitConstantInit(*InitDecl); 2285f785676fSDimitry Andric 2286f22ef01cSRoman Divacky if (!Init) { 2287f22ef01cSRoman Divacky QualType T = InitExpr->getType(); 2288f22ef01cSRoman Divacky if (D->getType()->isReferenceType()) 2289f22ef01cSRoman Divacky T = D->getType(); 2290f22ef01cSRoman Divacky 2291dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus) { 2292f22ef01cSRoman Divacky Init = EmitNullConstant(T); 2293dff0c46cSDimitry Andric NeedsGlobalCtor = true; 2294f22ef01cSRoman Divacky } else { 2295f22ef01cSRoman Divacky ErrorUnsupported(D, "static initializer"); 2296f22ef01cSRoman Divacky Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 2297f22ef01cSRoman Divacky } 2298e580952dSDimitry Andric } else { 2299e580952dSDimitry Andric // We don't need an initializer, so remove the entry for the delayed 2300dff0c46cSDimitry Andric // initializer position (just in case this entry was delayed) if we 2301dff0c46cSDimitry Andric // also don't need to register a destructor. 2302dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 2303e580952dSDimitry Andric DelayedCXXInitPosition.erase(D); 2304f22ef01cSRoman Divacky } 2305f22ef01cSRoman Divacky } 2306f22ef01cSRoman Divacky 23076122f3e6SDimitry Andric llvm::Type* InitType = Init->getType(); 2308f22ef01cSRoman Divacky llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 2309f22ef01cSRoman Divacky 2310f22ef01cSRoman Divacky // Strip off a bitcast if we got one back. 231159d1ed5bSDimitry Andric if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2312f22ef01cSRoman Divacky assert(CE->getOpcode() == llvm::Instruction::BitCast || 2313f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 2314f785676fSDimitry Andric // All zero index gep. 2315f22ef01cSRoman Divacky CE->getOpcode() == llvm::Instruction::GetElementPtr); 2316f22ef01cSRoman Divacky Entry = CE->getOperand(0); 2317f22ef01cSRoman Divacky } 2318f22ef01cSRoman Divacky 2319f22ef01cSRoman Divacky // Entry is now either a Function or GlobalVariable. 232059d1ed5bSDimitry Andric auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 2321f22ef01cSRoman Divacky 2322f22ef01cSRoman Divacky // We have a definition after a declaration with the wrong type. 2323f22ef01cSRoman Divacky // We must make a new GlobalVariable* and update everything that used OldGV 2324f22ef01cSRoman Divacky // (a declaration or tentative definition) with the new GlobalVariable* 2325f22ef01cSRoman Divacky // (which will be a definition). 2326f22ef01cSRoman Divacky // 2327f22ef01cSRoman Divacky // This happens if there is a prototype for a global (e.g. 2328f22ef01cSRoman Divacky // "extern int x[];") and then a definition of a different type (e.g. 2329f22ef01cSRoman Divacky // "int x[10];"). This also happens when an initializer has a different type 2330f22ef01cSRoman Divacky // from the type of the global (this happens with unions). 233159d1ed5bSDimitry Andric if (!GV || 2332f22ef01cSRoman Divacky GV->getType()->getElementType() != InitType || 23333b0f4066SDimitry Andric GV->getType()->getAddressSpace() != 23347ae0e2c9SDimitry Andric GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 2335f22ef01cSRoman Divacky 2336f22ef01cSRoman Divacky // Move the old entry aside so that we'll create a new one. 23376122f3e6SDimitry Andric Entry->setName(StringRef()); 2338f22ef01cSRoman Divacky 2339f22ef01cSRoman Divacky // Make a new global with the correct type, this is now guaranteed to work. 2340f22ef01cSRoman Divacky GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 2341f22ef01cSRoman Divacky 2342f22ef01cSRoman Divacky // Replace all uses of the old global with the new global 2343f22ef01cSRoman Divacky llvm::Constant *NewPtrForOldDecl = 2344f22ef01cSRoman Divacky llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2345f22ef01cSRoman Divacky Entry->replaceAllUsesWith(NewPtrForOldDecl); 2346f22ef01cSRoman Divacky 2347f22ef01cSRoman Divacky // Erase the old global, since it is no longer used. 2348f22ef01cSRoman Divacky cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 2349f22ef01cSRoman Divacky } 2350f22ef01cSRoman Divacky 2351284c1978SDimitry Andric MaybeHandleStaticInExternC(D, GV); 2352284c1978SDimitry Andric 23536122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 23546122f3e6SDimitry Andric AddGlobalAnnotations(D, GV); 2355f22ef01cSRoman Divacky 23560623d748SDimitry Andric // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 23570623d748SDimitry Andric // the device. [...]" 23580623d748SDimitry Andric // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 23590623d748SDimitry Andric // __device__, declares a variable that: [...] 23600623d748SDimitry Andric // Is accessible from all the threads within the grid and from the host 23610623d748SDimitry Andric // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 23620623d748SDimitry Andric // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 23630623d748SDimitry Andric if (GV && LangOpts.CUDA && LangOpts.CUDAIsDevice && 23640623d748SDimitry Andric (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>())) { 23650623d748SDimitry Andric GV->setExternallyInitialized(true); 23660623d748SDimitry Andric } 2367f22ef01cSRoman Divacky GV->setInitializer(Init); 2368f22ef01cSRoman Divacky 2369f22ef01cSRoman Divacky // If it is safe to mark the global 'constant', do so now. 2370dff0c46cSDimitry Andric GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 2371dff0c46cSDimitry Andric isTypeConstant(D->getType(), true)); 2372f22ef01cSRoman Divacky 237339d628a0SDimitry Andric // If it is in a read-only section, mark it 'constant'. 237439d628a0SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 237539d628a0SDimitry Andric const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 237639d628a0SDimitry Andric if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 237739d628a0SDimitry Andric GV->setConstant(true); 237839d628a0SDimitry Andric } 237939d628a0SDimitry Andric 2380f22ef01cSRoman Divacky GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 2381f22ef01cSRoman Divacky 2382f22ef01cSRoman Divacky // Set the llvm linkage type as appropriate. 23832754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 238459d1ed5bSDimitry Andric getLLVMLinkageVarDefinition(D, GV->isConstant()); 2385f785676fSDimitry Andric 23860623d748SDimitry Andric // On Darwin, if the normal linkage of a C++ thread_local variable is 23870623d748SDimitry Andric // LinkOnce or Weak, we keep the normal linkage to prevent multiple 23880623d748SDimitry Andric // copies within a linkage unit; otherwise, the backing variable has 23890623d748SDimitry Andric // internal linkage and all accesses should just be calls to the 239059d1ed5bSDimitry Andric // Itanium-specified entry point, which has the normal linkage of the 23910623d748SDimitry Andric // variable. This is to preserve the ability to change the implementation 23920623d748SDimitry Andric // behind the scenes. 239339d628a0SDimitry Andric if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic && 23940623d748SDimitry Andric Context.getTargetInfo().getTriple().isOSDarwin() && 23950623d748SDimitry Andric !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) && 23960623d748SDimitry Andric !llvm::GlobalVariable::isWeakLinkage(Linkage)) 239759d1ed5bSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 239859d1ed5bSDimitry Andric 239959d1ed5bSDimitry Andric GV->setLinkage(Linkage); 240059d1ed5bSDimitry Andric if (D->hasAttr<DLLImportAttr>()) 240159d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 240259d1ed5bSDimitry Andric else if (D->hasAttr<DLLExportAttr>()) 240359d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 240439d628a0SDimitry Andric else 240539d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 2406f785676fSDimitry Andric 24072754fe60SDimitry Andric if (Linkage == llvm::GlobalVariable::CommonLinkage) 2408f22ef01cSRoman Divacky // common vars aren't constant even if declared const. 2409f22ef01cSRoman Divacky GV->setConstant(false); 2410f22ef01cSRoman Divacky 241159d1ed5bSDimitry Andric setNonAliasAttributes(D, GV); 2412f22ef01cSRoman Divacky 241339d628a0SDimitry Andric if (D->getTLSKind() && !GV->isThreadLocal()) { 241439d628a0SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 24150623d748SDimitry Andric CXXThreadLocals.push_back(D); 241639d628a0SDimitry Andric setTLSMode(GV, *D); 241739d628a0SDimitry Andric } 241839d628a0SDimitry Andric 241933956c43SDimitry Andric maybeSetTrivialComdat(*D, *GV); 242033956c43SDimitry Andric 24212754fe60SDimitry Andric // Emit the initializer function if necessary. 2422dff0c46cSDimitry Andric if (NeedsGlobalCtor || NeedsGlobalDtor) 2423dff0c46cSDimitry Andric EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 24242754fe60SDimitry Andric 242539d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 24263861d79fSDimitry Andric 2427f22ef01cSRoman Divacky // Emit global variable debug information. 24286122f3e6SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 24293861d79fSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 2430f22ef01cSRoman Divacky DI->EmitGlobalVariable(GV, D); 2431f22ef01cSRoman Divacky } 2432f22ef01cSRoman Divacky 243339d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context, 243433956c43SDimitry Andric CodeGenModule &CGM, const VarDecl *D, 243533956c43SDimitry Andric bool NoCommon) { 243659d1ed5bSDimitry Andric // Don't give variables common linkage if -fno-common was specified unless it 243759d1ed5bSDimitry Andric // was overridden by a NoCommon attribute. 243859d1ed5bSDimitry Andric if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 243959d1ed5bSDimitry Andric return true; 244059d1ed5bSDimitry Andric 244159d1ed5bSDimitry Andric // C11 6.9.2/2: 244259d1ed5bSDimitry Andric // A declaration of an identifier for an object that has file scope without 244359d1ed5bSDimitry Andric // an initializer, and without a storage-class specifier or with the 244459d1ed5bSDimitry Andric // storage-class specifier static, constitutes a tentative definition. 244559d1ed5bSDimitry Andric if (D->getInit() || D->hasExternalStorage()) 244659d1ed5bSDimitry Andric return true; 244759d1ed5bSDimitry Andric 244859d1ed5bSDimitry Andric // A variable cannot be both common and exist in a section. 244959d1ed5bSDimitry Andric if (D->hasAttr<SectionAttr>()) 245059d1ed5bSDimitry Andric return true; 245159d1ed5bSDimitry Andric 245259d1ed5bSDimitry Andric // Thread local vars aren't considered common linkage. 245359d1ed5bSDimitry Andric if (D->getTLSKind()) 245459d1ed5bSDimitry Andric return true; 245559d1ed5bSDimitry Andric 245659d1ed5bSDimitry Andric // Tentative definitions marked with WeakImportAttr are true definitions. 245759d1ed5bSDimitry Andric if (D->hasAttr<WeakImportAttr>()) 245859d1ed5bSDimitry Andric return true; 245959d1ed5bSDimitry Andric 246033956c43SDimitry Andric // A variable cannot be both common and exist in a comdat. 246133956c43SDimitry Andric if (shouldBeInCOMDAT(CGM, *D)) 246233956c43SDimitry Andric return true; 246333956c43SDimitry Andric 246439d628a0SDimitry Andric // Declarations with a required alignment do not have common linakge in MSVC 246539d628a0SDimitry Andric // mode. 24660623d748SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 246733956c43SDimitry Andric if (D->hasAttr<AlignedAttr>()) 246839d628a0SDimitry Andric return true; 246933956c43SDimitry Andric QualType VarType = D->getType(); 247033956c43SDimitry Andric if (Context.isAlignmentRequired(VarType)) 247133956c43SDimitry Andric return true; 247233956c43SDimitry Andric 247333956c43SDimitry Andric if (const auto *RT = VarType->getAs<RecordType>()) { 247433956c43SDimitry Andric const RecordDecl *RD = RT->getDecl(); 247533956c43SDimitry Andric for (const FieldDecl *FD : RD->fields()) { 247633956c43SDimitry Andric if (FD->isBitField()) 247733956c43SDimitry Andric continue; 247833956c43SDimitry Andric if (FD->hasAttr<AlignedAttr>()) 247933956c43SDimitry Andric return true; 248033956c43SDimitry Andric if (Context.isAlignmentRequired(FD->getType())) 248133956c43SDimitry Andric return true; 248233956c43SDimitry Andric } 248333956c43SDimitry Andric } 248433956c43SDimitry Andric } 248539d628a0SDimitry Andric 248659d1ed5bSDimitry Andric return false; 248759d1ed5bSDimitry Andric } 248859d1ed5bSDimitry Andric 248959d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 249059d1ed5bSDimitry Andric const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 24912754fe60SDimitry Andric if (Linkage == GVA_Internal) 24922754fe60SDimitry Andric return llvm::Function::InternalLinkage; 249359d1ed5bSDimitry Andric 249459d1ed5bSDimitry Andric if (D->hasAttr<WeakAttr>()) { 249559d1ed5bSDimitry Andric if (IsConstantVariable) 249659d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 249759d1ed5bSDimitry Andric else 249859d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakAnyLinkage; 249959d1ed5bSDimitry Andric } 250059d1ed5bSDimitry Andric 250159d1ed5bSDimitry Andric // We are guaranteed to have a strong definition somewhere else, 250259d1ed5bSDimitry Andric // so we can use available_externally linkage. 250359d1ed5bSDimitry Andric if (Linkage == GVA_AvailableExternally) 250459d1ed5bSDimitry Andric return llvm::Function::AvailableExternallyLinkage; 250559d1ed5bSDimitry Andric 250659d1ed5bSDimitry Andric // Note that Apple's kernel linker doesn't support symbol 250759d1ed5bSDimitry Andric // coalescing, so we need to avoid linkonce and weak linkages there. 250859d1ed5bSDimitry Andric // Normally, this means we just map to internal, but for explicit 250959d1ed5bSDimitry Andric // instantiations we'll map to external. 251059d1ed5bSDimitry Andric 251159d1ed5bSDimitry Andric // In C++, the compiler has to emit a definition in every translation unit 251259d1ed5bSDimitry Andric // that references the function. We should use linkonce_odr because 251359d1ed5bSDimitry Andric // a) if all references in this translation unit are optimized away, we 251459d1ed5bSDimitry Andric // don't need to codegen it. b) if the function persists, it needs to be 251559d1ed5bSDimitry Andric // merged with other definitions. c) C++ has the ODR, so we know the 251659d1ed5bSDimitry Andric // definition is dependable. 251759d1ed5bSDimitry Andric if (Linkage == GVA_DiscardableODR) 251859d1ed5bSDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 251959d1ed5bSDimitry Andric : llvm::Function::InternalLinkage; 252059d1ed5bSDimitry Andric 252159d1ed5bSDimitry Andric // An explicit instantiation of a template has weak linkage, since 252259d1ed5bSDimitry Andric // explicit instantiations can occur in multiple translation units 252359d1ed5bSDimitry Andric // and must all be equivalent. However, we are not allowed to 252459d1ed5bSDimitry Andric // throw away these explicit instantiations. 252559d1ed5bSDimitry Andric if (Linkage == GVA_StrongODR) 252659d1ed5bSDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage 252759d1ed5bSDimitry Andric : llvm::Function::ExternalLinkage; 252859d1ed5bSDimitry Andric 252959d1ed5bSDimitry Andric // C++ doesn't have tentative definitions and thus cannot have common 253059d1ed5bSDimitry Andric // linkage. 253159d1ed5bSDimitry Andric if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 253233956c43SDimitry Andric !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 253339d628a0SDimitry Andric CodeGenOpts.NoCommon)) 253459d1ed5bSDimitry Andric return llvm::GlobalVariable::CommonLinkage; 253559d1ed5bSDimitry Andric 2536f785676fSDimitry Andric // selectany symbols are externally visible, so use weak instead of 2537f785676fSDimitry Andric // linkonce. MSVC optimizes away references to const selectany globals, so 2538f785676fSDimitry Andric // all definitions should be the same and ODR linkage should be used. 2539f785676fSDimitry Andric // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 254059d1ed5bSDimitry Andric if (D->hasAttr<SelectAnyAttr>()) 2541f785676fSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 254259d1ed5bSDimitry Andric 254359d1ed5bSDimitry Andric // Otherwise, we have strong external linkage. 254459d1ed5bSDimitry Andric assert(Linkage == GVA_StrongExternal); 25452754fe60SDimitry Andric return llvm::GlobalVariable::ExternalLinkage; 25462754fe60SDimitry Andric } 25472754fe60SDimitry Andric 254859d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 254959d1ed5bSDimitry Andric const VarDecl *VD, bool IsConstant) { 255059d1ed5bSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 255159d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 255259d1ed5bSDimitry Andric } 255359d1ed5bSDimitry Andric 2554139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type. 2555139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites 2556139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 2557139f7f9bSDimitry Andric llvm::Function *newFn) { 2558139f7f9bSDimitry Andric // Fast path. 2559139f7f9bSDimitry Andric if (old->use_empty()) return; 2560139f7f9bSDimitry Andric 2561139f7f9bSDimitry Andric llvm::Type *newRetTy = newFn->getReturnType(); 2562139f7f9bSDimitry Andric SmallVector<llvm::Value*, 4> newArgs; 25630623d748SDimitry Andric SmallVector<llvm::OperandBundleDef, 1> newBundles; 2564139f7f9bSDimitry Andric 2565139f7f9bSDimitry Andric for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 2566139f7f9bSDimitry Andric ui != ue; ) { 2567139f7f9bSDimitry Andric llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 256859d1ed5bSDimitry Andric llvm::User *user = use->getUser(); 2569139f7f9bSDimitry Andric 2570139f7f9bSDimitry Andric // Recognize and replace uses of bitcasts. Most calls to 2571139f7f9bSDimitry Andric // unprototyped functions will use bitcasts. 257259d1ed5bSDimitry Andric if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 2573139f7f9bSDimitry Andric if (bitcast->getOpcode() == llvm::Instruction::BitCast) 2574139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(bitcast, newFn); 2575139f7f9bSDimitry Andric continue; 2576139f7f9bSDimitry Andric } 2577139f7f9bSDimitry Andric 2578139f7f9bSDimitry Andric // Recognize calls to the function. 2579139f7f9bSDimitry Andric llvm::CallSite callSite(user); 2580139f7f9bSDimitry Andric if (!callSite) continue; 258159d1ed5bSDimitry Andric if (!callSite.isCallee(&*use)) continue; 2582139f7f9bSDimitry Andric 2583139f7f9bSDimitry Andric // If the return types don't match exactly, then we can't 2584139f7f9bSDimitry Andric // transform this call unless it's dead. 2585139f7f9bSDimitry Andric if (callSite->getType() != newRetTy && !callSite->use_empty()) 2586139f7f9bSDimitry Andric continue; 2587139f7f9bSDimitry Andric 2588139f7f9bSDimitry Andric // Get the call site's attribute list. 2589139f7f9bSDimitry Andric SmallVector<llvm::AttributeSet, 8> newAttrs; 2590139f7f9bSDimitry Andric llvm::AttributeSet oldAttrs = callSite.getAttributes(); 2591139f7f9bSDimitry Andric 2592139f7f9bSDimitry Andric // Collect any return attributes from the call. 2593139f7f9bSDimitry Andric if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex)) 2594139f7f9bSDimitry Andric newAttrs.push_back( 2595139f7f9bSDimitry Andric llvm::AttributeSet::get(newFn->getContext(), 2596139f7f9bSDimitry Andric oldAttrs.getRetAttributes())); 2597139f7f9bSDimitry Andric 2598139f7f9bSDimitry Andric // If the function was passed too few arguments, don't transform. 2599139f7f9bSDimitry Andric unsigned newNumArgs = newFn->arg_size(); 2600139f7f9bSDimitry Andric if (callSite.arg_size() < newNumArgs) continue; 2601139f7f9bSDimitry Andric 2602139f7f9bSDimitry Andric // If extra arguments were passed, we silently drop them. 2603139f7f9bSDimitry Andric // If any of the types mismatch, we don't transform. 2604139f7f9bSDimitry Andric unsigned argNo = 0; 2605139f7f9bSDimitry Andric bool dontTransform = false; 2606139f7f9bSDimitry Andric for (llvm::Function::arg_iterator ai = newFn->arg_begin(), 2607139f7f9bSDimitry Andric ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) { 2608139f7f9bSDimitry Andric if (callSite.getArgument(argNo)->getType() != ai->getType()) { 2609139f7f9bSDimitry Andric dontTransform = true; 2610139f7f9bSDimitry Andric break; 2611139f7f9bSDimitry Andric } 2612139f7f9bSDimitry Andric 2613139f7f9bSDimitry Andric // Add any parameter attributes. 2614139f7f9bSDimitry Andric if (oldAttrs.hasAttributes(argNo + 1)) 2615139f7f9bSDimitry Andric newAttrs. 2616139f7f9bSDimitry Andric push_back(llvm:: 2617139f7f9bSDimitry Andric AttributeSet::get(newFn->getContext(), 2618139f7f9bSDimitry Andric oldAttrs.getParamAttributes(argNo + 1))); 2619139f7f9bSDimitry Andric } 2620139f7f9bSDimitry Andric if (dontTransform) 2621139f7f9bSDimitry Andric continue; 2622139f7f9bSDimitry Andric 2623139f7f9bSDimitry Andric if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) 2624139f7f9bSDimitry Andric newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(), 2625139f7f9bSDimitry Andric oldAttrs.getFnAttributes())); 2626139f7f9bSDimitry Andric 2627139f7f9bSDimitry Andric // Okay, we can transform this. Create the new call instruction and copy 2628139f7f9bSDimitry Andric // over the required information. 2629139f7f9bSDimitry Andric newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 2630139f7f9bSDimitry Andric 26310623d748SDimitry Andric // Copy over any operand bundles. 26320623d748SDimitry Andric callSite.getOperandBundlesAsDefs(newBundles); 26330623d748SDimitry Andric 2634139f7f9bSDimitry Andric llvm::CallSite newCall; 2635139f7f9bSDimitry Andric if (callSite.isCall()) { 26360623d748SDimitry Andric newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "", 2637139f7f9bSDimitry Andric callSite.getInstruction()); 2638139f7f9bSDimitry Andric } else { 263959d1ed5bSDimitry Andric auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction()); 2640139f7f9bSDimitry Andric newCall = llvm::InvokeInst::Create(newFn, 2641139f7f9bSDimitry Andric oldInvoke->getNormalDest(), 2642139f7f9bSDimitry Andric oldInvoke->getUnwindDest(), 26430623d748SDimitry Andric newArgs, newBundles, "", 2644139f7f9bSDimitry Andric callSite.getInstruction()); 2645139f7f9bSDimitry Andric } 2646139f7f9bSDimitry Andric newArgs.clear(); // for the next iteration 2647139f7f9bSDimitry Andric 2648139f7f9bSDimitry Andric if (!newCall->getType()->isVoidTy()) 2649139f7f9bSDimitry Andric newCall->takeName(callSite.getInstruction()); 2650139f7f9bSDimitry Andric newCall.setAttributes( 2651139f7f9bSDimitry Andric llvm::AttributeSet::get(newFn->getContext(), newAttrs)); 2652139f7f9bSDimitry Andric newCall.setCallingConv(callSite.getCallingConv()); 2653139f7f9bSDimitry Andric 2654139f7f9bSDimitry Andric // Finally, remove the old call, replacing any uses with the new one. 2655139f7f9bSDimitry Andric if (!callSite->use_empty()) 2656139f7f9bSDimitry Andric callSite->replaceAllUsesWith(newCall.getInstruction()); 2657139f7f9bSDimitry Andric 2658139f7f9bSDimitry Andric // Copy debug location attached to CI. 265933956c43SDimitry Andric if (callSite->getDebugLoc()) 2660139f7f9bSDimitry Andric newCall->setDebugLoc(callSite->getDebugLoc()); 26610623d748SDimitry Andric 2662139f7f9bSDimitry Andric callSite->eraseFromParent(); 2663139f7f9bSDimitry Andric } 2664139f7f9bSDimitry Andric } 2665139f7f9bSDimitry Andric 2666f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 2667f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}". If there are 2668f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to 2669f22ef01cSRoman Divacky /// call the new function directly. 2670f22ef01cSRoman Divacky /// 2671f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to 2672f22ef01cSRoman Divacky /// functions to be able to inline them. If there is a bitcast in the way, it 2673f22ef01cSRoman Divacky /// won't inline them. Instcombine normally deletes these calls, but it isn't 2674f22ef01cSRoman Divacky /// run at -O0. 2675f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2676f22ef01cSRoman Divacky llvm::Function *NewFn) { 2677f22ef01cSRoman Divacky // If we're redefining a global as a function, don't transform it. 2678139f7f9bSDimitry Andric if (!isa<llvm::Function>(Old)) return; 2679f22ef01cSRoman Divacky 2680139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(Old, NewFn); 2681f22ef01cSRoman Divacky } 2682f22ef01cSRoman Divacky 2683dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 2684dff0c46cSDimitry Andric TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 2685dff0c46cSDimitry Andric // If we have a definition, this might be a deferred decl. If the 2686dff0c46cSDimitry Andric // instantiation is explicit, make sure we emit it at the end. 2687dff0c46cSDimitry Andric if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 2688dff0c46cSDimitry Andric GetAddrOfGlobalVar(VD); 2689139f7f9bSDimitry Andric 2690139f7f9bSDimitry Andric EmitTopLevelDecl(VD); 2691dff0c46cSDimitry Andric } 2692f22ef01cSRoman Divacky 269359d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 269459d1ed5bSDimitry Andric llvm::GlobalValue *GV) { 269559d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 26963b0f4066SDimitry Andric 26973b0f4066SDimitry Andric // Compute the function info and LLVM type. 2698dff0c46cSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2699dff0c46cSDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 27003b0f4066SDimitry Andric 2701f22ef01cSRoman Divacky // Get or create the prototype for the function. 27020623d748SDimitry Andric if (!GV || (GV->getType()->getElementType() != Ty)) 27030623d748SDimitry Andric GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 27040623d748SDimitry Andric /*DontDefer=*/true, 27050623d748SDimitry Andric /*IsForDefinition=*/true)); 2706f22ef01cSRoman Divacky 27070623d748SDimitry Andric // Already emitted. 27080623d748SDimitry Andric if (!GV->isDeclaration()) 2709f785676fSDimitry Andric return; 2710f22ef01cSRoman Divacky 27112754fe60SDimitry Andric // We need to set linkage and visibility on the function before 27122754fe60SDimitry Andric // generating code for it because various parts of IR generation 27132754fe60SDimitry Andric // want to propagate this information down (e.g. to local static 27142754fe60SDimitry Andric // declarations). 271559d1ed5bSDimitry Andric auto *Fn = cast<llvm::Function>(GV); 2716f785676fSDimitry Andric setFunctionLinkage(GD, Fn); 271797bc6c73SDimitry Andric setFunctionDLLStorageClass(GD, Fn); 2718f22ef01cSRoman Divacky 271959d1ed5bSDimitry Andric // FIXME: this is redundant with part of setFunctionDefinitionAttributes 27202754fe60SDimitry Andric setGlobalVisibility(Fn, D); 27212754fe60SDimitry Andric 2722284c1978SDimitry Andric MaybeHandleStaticInExternC(D, Fn); 2723284c1978SDimitry Andric 272433956c43SDimitry Andric maybeSetTrivialComdat(*D, *Fn); 272533956c43SDimitry Andric 27263b0f4066SDimitry Andric CodeGenFunction(*this).GenerateCode(D, Fn, FI); 2727f22ef01cSRoman Divacky 272859d1ed5bSDimitry Andric setFunctionDefinitionAttributes(D, Fn); 2729f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, Fn); 2730f22ef01cSRoman Divacky 2731f22ef01cSRoman Divacky if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 2732f22ef01cSRoman Divacky AddGlobalCtor(Fn, CA->getPriority()); 2733f22ef01cSRoman Divacky if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 2734f22ef01cSRoman Divacky AddGlobalDtor(Fn, DA->getPriority()); 27356122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 27366122f3e6SDimitry Andric AddGlobalAnnotations(D, Fn); 2737f22ef01cSRoman Divacky } 2738f22ef01cSRoman Divacky 2739f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 274059d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 2741f22ef01cSRoman Divacky const AliasAttr *AA = D->getAttr<AliasAttr>(); 2742f22ef01cSRoman Divacky assert(AA && "Not an alias?"); 2743f22ef01cSRoman Divacky 27446122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 2745f22ef01cSRoman Divacky 27469a4b3118SDimitry Andric if (AA->getAliasee() == MangledName) { 27479a4b3118SDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 27489a4b3118SDimitry Andric return; 27499a4b3118SDimitry Andric } 27509a4b3118SDimitry Andric 2751f22ef01cSRoman Divacky // If there is a definition in the module, then it wins over the alias. 2752f22ef01cSRoman Divacky // This is dubious, but allow it to be safe. Just ignore the alias. 2753f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2754f22ef01cSRoman Divacky if (Entry && !Entry->isDeclaration()) 2755f22ef01cSRoman Divacky return; 2756f22ef01cSRoman Divacky 2757f785676fSDimitry Andric Aliases.push_back(GD); 2758f785676fSDimitry Andric 27596122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 2760f22ef01cSRoman Divacky 2761f22ef01cSRoman Divacky // Create a reference to the named value. This ensures that it is emitted 2762f22ef01cSRoman Divacky // if a deferred decl. 2763f22ef01cSRoman Divacky llvm::Constant *Aliasee; 2764f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 27653861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 27662754fe60SDimitry Andric /*ForVTable=*/false); 2767f22ef01cSRoman Divacky else 2768f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 276959d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 277039d628a0SDimitry Andric /*D=*/nullptr); 2771f22ef01cSRoman Divacky 2772f22ef01cSRoman Divacky // Create the new alias itself, but don't set a name yet. 277359d1ed5bSDimitry Andric auto *GA = llvm::GlobalAlias::create( 27740623d748SDimitry Andric DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule()); 2775f22ef01cSRoman Divacky 2776f22ef01cSRoman Divacky if (Entry) { 277759d1ed5bSDimitry Andric if (GA->getAliasee() == Entry) { 277859d1ed5bSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 277959d1ed5bSDimitry Andric return; 278059d1ed5bSDimitry Andric } 278159d1ed5bSDimitry Andric 2782f22ef01cSRoman Divacky assert(Entry->isDeclaration()); 2783f22ef01cSRoman Divacky 2784f22ef01cSRoman Divacky // If there is a declaration in the module, then we had an extern followed 2785f22ef01cSRoman Divacky // by the alias, as in: 2786f22ef01cSRoman Divacky // extern int test6(); 2787f22ef01cSRoman Divacky // ... 2788f22ef01cSRoman Divacky // int test6() __attribute__((alias("test7"))); 2789f22ef01cSRoman Divacky // 2790f22ef01cSRoman Divacky // Remove it and replace uses of it with the alias. 2791f22ef01cSRoman Divacky GA->takeName(Entry); 2792f22ef01cSRoman Divacky 2793f22ef01cSRoman Divacky Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 2794f22ef01cSRoman Divacky Entry->getType())); 2795f22ef01cSRoman Divacky Entry->eraseFromParent(); 2796f22ef01cSRoman Divacky } else { 2797ffd1746dSEd Schouten GA->setName(MangledName); 2798f22ef01cSRoman Divacky } 2799f22ef01cSRoman Divacky 2800f22ef01cSRoman Divacky // Set attributes which are particular to an alias; this is a 2801f22ef01cSRoman Divacky // specialization of the attributes which may be set on a global 2802f22ef01cSRoman Divacky // variable/function. 280339d628a0SDimitry Andric if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 28043b0f4066SDimitry Andric D->isWeakImported()) { 2805f22ef01cSRoman Divacky GA->setLinkage(llvm::Function::WeakAnyLinkage); 2806f22ef01cSRoman Divacky } 2807f22ef01cSRoman Divacky 280839d628a0SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 280939d628a0SDimitry Andric if (VD->getTLSKind()) 281039d628a0SDimitry Andric setTLSMode(GA, *VD); 281139d628a0SDimitry Andric 281239d628a0SDimitry Andric setAliasAttributes(D, GA); 2813f22ef01cSRoman Divacky } 2814f22ef01cSRoman Divacky 281517a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 28166122f3e6SDimitry Andric ArrayRef<llvm::Type*> Tys) { 281717a519f9SDimitry Andric return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 281817a519f9SDimitry Andric Tys); 2819f22ef01cSRoman Divacky } 2820f22ef01cSRoman Divacky 282133956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 282233956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 282333956c43SDimitry Andric const StringLiteral *Literal, bool TargetIsLSB, 282433956c43SDimitry Andric bool &IsUTF16, unsigned &StringLength) { 28256122f3e6SDimitry Andric StringRef String = Literal->getString(); 2826e580952dSDimitry Andric unsigned NumBytes = String.size(); 2827f22ef01cSRoman Divacky 2828f22ef01cSRoman Divacky // Check for simple case. 2829f22ef01cSRoman Divacky if (!Literal->containsNonAsciiOrNull()) { 2830f22ef01cSRoman Divacky StringLength = NumBytes; 283139d628a0SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 2832f22ef01cSRoman Divacky } 2833f22ef01cSRoman Divacky 2834dff0c46cSDimitry Andric // Otherwise, convert the UTF8 literals into a string of shorts. 2835dff0c46cSDimitry Andric IsUTF16 = true; 2836dff0c46cSDimitry Andric 2837dff0c46cSDimitry Andric SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 28383861d79fSDimitry Andric const UTF8 *FromPtr = (const UTF8 *)String.data(); 2839f22ef01cSRoman Divacky UTF16 *ToPtr = &ToBuf[0]; 2840f22ef01cSRoman Divacky 28412754fe60SDimitry Andric (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 2842f22ef01cSRoman Divacky &ToPtr, ToPtr + NumBytes, 2843f22ef01cSRoman Divacky strictConversion); 2844f22ef01cSRoman Divacky 2845f22ef01cSRoman Divacky // ConvertUTF8toUTF16 returns the length in ToPtr. 2846f22ef01cSRoman Divacky StringLength = ToPtr - &ToBuf[0]; 2847f22ef01cSRoman Divacky 2848dff0c46cSDimitry Andric // Add an explicit null. 2849dff0c46cSDimitry Andric *ToPtr = 0; 285039d628a0SDimitry Andric return *Map.insert(std::make_pair( 285139d628a0SDimitry Andric StringRef(reinterpret_cast<const char *>(ToBuf.data()), 285239d628a0SDimitry Andric (StringLength + 1) * 2), 285339d628a0SDimitry Andric nullptr)).first; 2854f22ef01cSRoman Divacky } 2855f22ef01cSRoman Divacky 285633956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> & 285733956c43SDimitry Andric GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 285833956c43SDimitry Andric const StringLiteral *Literal, unsigned &StringLength) { 28596122f3e6SDimitry Andric StringRef String = Literal->getString(); 2860bd5abe19SDimitry Andric StringLength = String.size(); 286139d628a0SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 2862bd5abe19SDimitry Andric } 2863bd5abe19SDimitry Andric 28640623d748SDimitry Andric ConstantAddress 2865f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 2866f22ef01cSRoman Divacky unsigned StringLength = 0; 2867f22ef01cSRoman Divacky bool isUTF16 = false; 286833956c43SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2869f22ef01cSRoman Divacky GetConstantCFStringEntry(CFConstantStringMap, Literal, 287033956c43SDimitry Andric getDataLayout().isLittleEndian(), isUTF16, 287133956c43SDimitry Andric StringLength); 2872f22ef01cSRoman Divacky 287339d628a0SDimitry Andric if (auto *C = Entry.second) 28740623d748SDimitry Andric return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 2875f22ef01cSRoman Divacky 2876dff0c46cSDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2877f22ef01cSRoman Divacky llvm::Constant *Zeros[] = { Zero, Zero }; 2878284c1978SDimitry Andric llvm::Value *V; 2879f22ef01cSRoman Divacky 2880f22ef01cSRoman Divacky // If we don't already have it, get __CFConstantStringClassReference. 2881f22ef01cSRoman Divacky if (!CFConstantStringClassRef) { 28826122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2883f22ef01cSRoman Divacky Ty = llvm::ArrayType::get(Ty, 0); 2884f22ef01cSRoman Divacky llvm::Constant *GV = CreateRuntimeVariable(Ty, 2885f22ef01cSRoman Divacky "__CFConstantStringClassReference"); 2886f22ef01cSRoman Divacky // Decay array -> ptr 288733956c43SDimitry Andric V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros); 2888284c1978SDimitry Andric CFConstantStringClassRef = V; 2889f22ef01cSRoman Divacky } 2890284c1978SDimitry Andric else 2891284c1978SDimitry Andric V = CFConstantStringClassRef; 2892f22ef01cSRoman Divacky 2893f22ef01cSRoman Divacky QualType CFTy = getContext().getCFConstantStringType(); 2894f22ef01cSRoman Divacky 289559d1ed5bSDimitry Andric auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 2896f22ef01cSRoman Divacky 2897dff0c46cSDimitry Andric llvm::Constant *Fields[4]; 2898f22ef01cSRoman Divacky 2899f22ef01cSRoman Divacky // Class pointer. 2900284c1978SDimitry Andric Fields[0] = cast<llvm::ConstantExpr>(V); 2901f22ef01cSRoman Divacky 2902f22ef01cSRoman Divacky // Flags. 29036122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2904f22ef01cSRoman Divacky Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 2905f22ef01cSRoman Divacky llvm::ConstantInt::get(Ty, 0x07C8); 2906f22ef01cSRoman Divacky 2907f22ef01cSRoman Divacky // String pointer. 290859d1ed5bSDimitry Andric llvm::Constant *C = nullptr; 2909dff0c46cSDimitry Andric if (isUTF16) { 29100623d748SDimitry Andric auto Arr = llvm::makeArrayRef( 291139d628a0SDimitry Andric reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 291239d628a0SDimitry Andric Entry.first().size() / 2); 2913dff0c46cSDimitry Andric C = llvm::ConstantDataArray::get(VMContext, Arr); 2914dff0c46cSDimitry Andric } else { 291539d628a0SDimitry Andric C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 2916dff0c46cSDimitry Andric } 2917f22ef01cSRoman Divacky 2918dff0c46cSDimitry Andric // Note: -fwritable-strings doesn't make the backing store strings of 2919dff0c46cSDimitry Andric // CFStrings writable. (See <rdar://problem/10657500>) 292059d1ed5bSDimitry Andric auto *GV = 2921dff0c46cSDimitry Andric new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 292259d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, C, ".str"); 29232754fe60SDimitry Andric GV->setUnnamedAddr(true); 2924284c1978SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 2925284c1978SDimitry Andric // of the string is via this class initializer. 292659d1ed5bSDimitry Andric // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without 292759d1ed5bSDimitry Andric // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing 292859d1ed5bSDimitry Andric // that changes the section it ends in, which surprises ld64. 2929f22ef01cSRoman Divacky if (isUTF16) { 2930f22ef01cSRoman Divacky CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 2931f22ef01cSRoman Divacky GV->setAlignment(Align.getQuantity()); 293259d1ed5bSDimitry Andric GV->setSection("__TEXT,__ustring"); 29333b0f4066SDimitry Andric } else { 29343b0f4066SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 29353b0f4066SDimitry Andric GV->setAlignment(Align.getQuantity()); 293659d1ed5bSDimitry Andric GV->setSection("__TEXT,__cstring,cstring_literals"); 2937f22ef01cSRoman Divacky } 2938dff0c46cSDimitry Andric 2939dff0c46cSDimitry Andric // String. 294033956c43SDimitry Andric Fields[2] = 294133956c43SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 2942f22ef01cSRoman Divacky 2943dff0c46cSDimitry Andric if (isUTF16) 2944dff0c46cSDimitry Andric // Cast the UTF16 string to the correct type. 2945dff0c46cSDimitry Andric Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 2946dff0c46cSDimitry Andric 2947f22ef01cSRoman Divacky // String length. 2948f22ef01cSRoman Divacky Ty = getTypes().ConvertType(getContext().LongTy); 2949f22ef01cSRoman Divacky Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 2950f22ef01cSRoman Divacky 29510623d748SDimitry Andric CharUnits Alignment = getPointerAlign(); 29520623d748SDimitry Andric 2953f22ef01cSRoman Divacky // The struct. 2954f22ef01cSRoman Divacky C = llvm::ConstantStruct::get(STy, Fields); 2955f22ef01cSRoman Divacky GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2956f22ef01cSRoman Divacky llvm::GlobalVariable::PrivateLinkage, C, 2957f22ef01cSRoman Divacky "_unnamed_cfstring_"); 295859d1ed5bSDimitry Andric GV->setSection("__DATA,__cfstring"); 29590623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 296039d628a0SDimitry Andric Entry.second = GV; 2961f22ef01cSRoman Divacky 29620623d748SDimitry Andric return ConstantAddress(GV, Alignment); 2963f22ef01cSRoman Divacky } 2964f22ef01cSRoman Divacky 29650623d748SDimitry Andric ConstantAddress 29662754fe60SDimitry Andric CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 2967f22ef01cSRoman Divacky unsigned StringLength = 0; 296833956c43SDimitry Andric llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 2969bd5abe19SDimitry Andric GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 2970f22ef01cSRoman Divacky 297139d628a0SDimitry Andric if (auto *C = Entry.second) 29720623d748SDimitry Andric return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 2973f22ef01cSRoman Divacky 2974dff0c46cSDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2975f22ef01cSRoman Divacky llvm::Constant *Zeros[] = { Zero, Zero }; 2976284c1978SDimitry Andric llvm::Value *V; 2977f22ef01cSRoman Divacky // If we don't already have it, get _NSConstantStringClassReference. 29782754fe60SDimitry Andric if (!ConstantStringClassRef) { 2979dff0c46cSDimitry Andric std::string StringClass(getLangOpts().ObjCConstantStringClass); 29806122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 29812754fe60SDimitry Andric llvm::Constant *GV; 29827ae0e2c9SDimitry Andric if (LangOpts.ObjCRuntime.isNonFragile()) { 2983bd5abe19SDimitry Andric std::string str = 2984bd5abe19SDimitry Andric StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 2985bd5abe19SDimitry Andric : "OBJC_CLASS_$_" + StringClass; 2986bd5abe19SDimitry Andric GV = getObjCRuntime().GetClassGlobal(str); 2987bd5abe19SDimitry Andric // Make sure the result is of the correct type. 29886122f3e6SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2989284c1978SDimitry Andric V = llvm::ConstantExpr::getBitCast(GV, PTy); 2990284c1978SDimitry Andric ConstantStringClassRef = V; 2991bd5abe19SDimitry Andric } else { 2992bd5abe19SDimitry Andric std::string str = 2993bd5abe19SDimitry Andric StringClass.empty() ? "_NSConstantStringClassReference" 2994bd5abe19SDimitry Andric : "_" + StringClass + "ClassReference"; 29956122f3e6SDimitry Andric llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 2996bd5abe19SDimitry Andric GV = CreateRuntimeVariable(PTy, str); 2997f22ef01cSRoman Divacky // Decay array -> ptr 299833956c43SDimitry Andric V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros); 2999284c1978SDimitry Andric ConstantStringClassRef = V; 3000f22ef01cSRoman Divacky } 300133956c43SDimitry Andric } else 3002284c1978SDimitry Andric V = ConstantStringClassRef; 3003f22ef01cSRoman Divacky 30046122f3e6SDimitry Andric if (!NSConstantStringType) { 30056122f3e6SDimitry Andric // Construct the type for a constant NSString. 300659d1ed5bSDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString"); 30076122f3e6SDimitry Andric D->startDefinition(); 3008f22ef01cSRoman Divacky 30096122f3e6SDimitry Andric QualType FieldTypes[3]; 30106122f3e6SDimitry Andric 30116122f3e6SDimitry Andric // const int *isa; 30126122f3e6SDimitry Andric FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 30136122f3e6SDimitry Andric // const char *str; 30146122f3e6SDimitry Andric FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 30156122f3e6SDimitry Andric // unsigned int length; 30166122f3e6SDimitry Andric FieldTypes[2] = Context.UnsignedIntTy; 30176122f3e6SDimitry Andric 30186122f3e6SDimitry Andric // Create fields 30196122f3e6SDimitry Andric for (unsigned i = 0; i < 3; ++i) { 30206122f3e6SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, D, 30216122f3e6SDimitry Andric SourceLocation(), 302259d1ed5bSDimitry Andric SourceLocation(), nullptr, 302359d1ed5bSDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 302459d1ed5bSDimitry Andric /*BitWidth=*/nullptr, 30256122f3e6SDimitry Andric /*Mutable=*/false, 30267ae0e2c9SDimitry Andric ICIS_NoInit); 30276122f3e6SDimitry Andric Field->setAccess(AS_public); 30286122f3e6SDimitry Andric D->addDecl(Field); 30296122f3e6SDimitry Andric } 30306122f3e6SDimitry Andric 30316122f3e6SDimitry Andric D->completeDefinition(); 30326122f3e6SDimitry Andric QualType NSTy = Context.getTagDeclType(D); 30336122f3e6SDimitry Andric NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 30346122f3e6SDimitry Andric } 3035f22ef01cSRoman Divacky 3036dff0c46cSDimitry Andric llvm::Constant *Fields[3]; 3037f22ef01cSRoman Divacky 3038f22ef01cSRoman Divacky // Class pointer. 3039284c1978SDimitry Andric Fields[0] = cast<llvm::ConstantExpr>(V); 3040f22ef01cSRoman Divacky 3041f22ef01cSRoman Divacky // String pointer. 3042dff0c46cSDimitry Andric llvm::Constant *C = 304339d628a0SDimitry Andric llvm::ConstantDataArray::getString(VMContext, Entry.first()); 3044f22ef01cSRoman Divacky 3045f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes Linkage; 3046f22ef01cSRoman Divacky bool isConstant; 3047f22ef01cSRoman Divacky Linkage = llvm::GlobalValue::PrivateLinkage; 3048dff0c46cSDimitry Andric isConstant = !LangOpts.WritableStrings; 3049f22ef01cSRoman Divacky 305059d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant, 305159d1ed5bSDimitry Andric Linkage, C, ".str"); 30522754fe60SDimitry Andric GV->setUnnamedAddr(true); 3053284c1978SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 3054284c1978SDimitry Andric // of the string is via this class initializer. 30553b0f4066SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 30563b0f4066SDimitry Andric GV->setAlignment(Align.getQuantity()); 305733956c43SDimitry Andric Fields[1] = 305833956c43SDimitry Andric llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 3059f22ef01cSRoman Divacky 3060f22ef01cSRoman Divacky // String length. 30616122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 3062f22ef01cSRoman Divacky Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 3063f22ef01cSRoman Divacky 3064f22ef01cSRoman Divacky // The struct. 30650623d748SDimitry Andric CharUnits Alignment = getPointerAlign(); 30666122f3e6SDimitry Andric C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 3067f22ef01cSRoman Divacky GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 3068f22ef01cSRoman Divacky llvm::GlobalVariable::PrivateLinkage, C, 3069f22ef01cSRoman Divacky "_unnamed_nsstring_"); 30700623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 307159d1ed5bSDimitry Andric const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip"; 307259d1ed5bSDimitry Andric const char *NSStringNonFragileABISection = 307359d1ed5bSDimitry Andric "__DATA,__objc_stringobj,regular,no_dead_strip"; 3074f22ef01cSRoman Divacky // FIXME. Fix section. 307559d1ed5bSDimitry Andric GV->setSection(LangOpts.ObjCRuntime.isNonFragile() 307659d1ed5bSDimitry Andric ? NSStringNonFragileABISection 307759d1ed5bSDimitry Andric : NSStringSection); 307839d628a0SDimitry Andric Entry.second = GV; 3079f22ef01cSRoman Divacky 30800623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3081f22ef01cSRoman Divacky } 3082f22ef01cSRoman Divacky 30836122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() { 30846122f3e6SDimitry Andric if (ObjCFastEnumerationStateType.isNull()) { 308559d1ed5bSDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 30866122f3e6SDimitry Andric D->startDefinition(); 30876122f3e6SDimitry Andric 30886122f3e6SDimitry Andric QualType FieldTypes[] = { 30896122f3e6SDimitry Andric Context.UnsignedLongTy, 30906122f3e6SDimitry Andric Context.getPointerType(Context.getObjCIdType()), 30916122f3e6SDimitry Andric Context.getPointerType(Context.UnsignedLongTy), 30926122f3e6SDimitry Andric Context.getConstantArrayType(Context.UnsignedLongTy, 30936122f3e6SDimitry Andric llvm::APInt(32, 5), ArrayType::Normal, 0) 30946122f3e6SDimitry Andric }; 30956122f3e6SDimitry Andric 30966122f3e6SDimitry Andric for (size_t i = 0; i < 4; ++i) { 30976122f3e6SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, 30986122f3e6SDimitry Andric D, 30996122f3e6SDimitry Andric SourceLocation(), 310059d1ed5bSDimitry Andric SourceLocation(), nullptr, 310159d1ed5bSDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 310259d1ed5bSDimitry Andric /*BitWidth=*/nullptr, 31036122f3e6SDimitry Andric /*Mutable=*/false, 31047ae0e2c9SDimitry Andric ICIS_NoInit); 31056122f3e6SDimitry Andric Field->setAccess(AS_public); 31066122f3e6SDimitry Andric D->addDecl(Field); 31076122f3e6SDimitry Andric } 31086122f3e6SDimitry Andric 31096122f3e6SDimitry Andric D->completeDefinition(); 31106122f3e6SDimitry Andric ObjCFastEnumerationStateType = Context.getTagDeclType(D); 31116122f3e6SDimitry Andric } 31126122f3e6SDimitry Andric 31136122f3e6SDimitry Andric return ObjCFastEnumerationStateType; 31146122f3e6SDimitry Andric } 31156122f3e6SDimitry Andric 3116dff0c46cSDimitry Andric llvm::Constant * 3117dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 3118dff0c46cSDimitry Andric assert(!E->getType()->isPointerType() && "Strings are always arrays"); 3119f22ef01cSRoman Divacky 3120dff0c46cSDimitry Andric // Don't emit it as the address of the string, emit the string data itself 3121dff0c46cSDimitry Andric // as an inline array. 3122dff0c46cSDimitry Andric if (E->getCharByteWidth() == 1) { 3123dff0c46cSDimitry Andric SmallString<64> Str(E->getString()); 3124f22ef01cSRoman Divacky 3125dff0c46cSDimitry Andric // Resize the string to the right size, which is indicated by its type. 3126dff0c46cSDimitry Andric const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 3127dff0c46cSDimitry Andric Str.resize(CAT->getSize().getZExtValue()); 3128dff0c46cSDimitry Andric return llvm::ConstantDataArray::getString(VMContext, Str, false); 31296122f3e6SDimitry Andric } 3130f22ef01cSRoman Divacky 313159d1ed5bSDimitry Andric auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 3132dff0c46cSDimitry Andric llvm::Type *ElemTy = AType->getElementType(); 3133dff0c46cSDimitry Andric unsigned NumElements = AType->getNumElements(); 3134f22ef01cSRoman Divacky 3135dff0c46cSDimitry Andric // Wide strings have either 2-byte or 4-byte elements. 3136dff0c46cSDimitry Andric if (ElemTy->getPrimitiveSizeInBits() == 16) { 3137dff0c46cSDimitry Andric SmallVector<uint16_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); 3144dff0c46cSDimitry Andric } 3145dff0c46cSDimitry Andric 3146dff0c46cSDimitry Andric assert(ElemTy->getPrimitiveSizeInBits() == 32); 3147dff0c46cSDimitry Andric SmallVector<uint32_t, 32> Elements; 3148dff0c46cSDimitry Andric Elements.reserve(NumElements); 3149dff0c46cSDimitry Andric 3150dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 3151dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 3152dff0c46cSDimitry Andric Elements.resize(NumElements); 3153dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 3154f22ef01cSRoman Divacky } 3155f22ef01cSRoman Divacky 315659d1ed5bSDimitry Andric static llvm::GlobalVariable * 315759d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 315859d1ed5bSDimitry Andric CodeGenModule &CGM, StringRef GlobalName, 31590623d748SDimitry Andric CharUnits Alignment) { 316059d1ed5bSDimitry Andric // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 316159d1ed5bSDimitry Andric unsigned AddrSpace = 0; 316259d1ed5bSDimitry Andric if (CGM.getLangOpts().OpenCL) 316359d1ed5bSDimitry Andric AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 3164dff0c46cSDimitry Andric 316533956c43SDimitry Andric llvm::Module &M = CGM.getModule(); 316659d1ed5bSDimitry Andric // Create a global variable for this string 316759d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 316833956c43SDimitry Andric M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 316933956c43SDimitry Andric nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 31700623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 317159d1ed5bSDimitry Andric GV->setUnnamedAddr(true); 317233956c43SDimitry Andric if (GV->isWeakForLinker()) { 317333956c43SDimitry Andric assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 317433956c43SDimitry Andric GV->setComdat(M.getOrInsertComdat(GV->getName())); 317533956c43SDimitry Andric } 317633956c43SDimitry Andric 317759d1ed5bSDimitry Andric return GV; 3178f22ef01cSRoman Divacky } 3179dff0c46cSDimitry Andric 318059d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 318159d1ed5bSDimitry Andric /// constant array for the given string literal. 31820623d748SDimitry Andric ConstantAddress 318339d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 318439d628a0SDimitry Andric StringRef Name) { 31850623d748SDimitry Andric CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 3186dff0c46cSDimitry Andric 318759d1ed5bSDimitry Andric llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 318859d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 318959d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 319059d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 319159d1ed5bSDimitry Andric if (auto GV = *Entry) { 31920623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 31930623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 31940623d748SDimitry Andric return ConstantAddress(GV, Alignment); 319559d1ed5bSDimitry Andric } 319659d1ed5bSDimitry Andric } 319759d1ed5bSDimitry Andric 319859d1ed5bSDimitry Andric SmallString<256> MangledNameBuffer; 319959d1ed5bSDimitry Andric StringRef GlobalVariableName; 320059d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes LT; 320159d1ed5bSDimitry Andric 320259d1ed5bSDimitry Andric // Mangle the string literal if the ABI allows for it. However, we cannot 320359d1ed5bSDimitry Andric // do this if we are compiling with ASan or -fwritable-strings because they 320459d1ed5bSDimitry Andric // rely on strings having normal linkage. 320539d628a0SDimitry Andric if (!LangOpts.WritableStrings && 320639d628a0SDimitry Andric !LangOpts.Sanitize.has(SanitizerKind::Address) && 320759d1ed5bSDimitry Andric getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { 320859d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(MangledNameBuffer); 320959d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 321059d1ed5bSDimitry Andric 321159d1ed5bSDimitry Andric LT = llvm::GlobalValue::LinkOnceODRLinkage; 321259d1ed5bSDimitry Andric GlobalVariableName = MangledNameBuffer; 321359d1ed5bSDimitry Andric } else { 321459d1ed5bSDimitry Andric LT = llvm::GlobalValue::PrivateLinkage; 321539d628a0SDimitry Andric GlobalVariableName = Name; 321659d1ed5bSDimitry Andric } 321759d1ed5bSDimitry Andric 321859d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 321959d1ed5bSDimitry Andric if (Entry) 322059d1ed5bSDimitry Andric *Entry = GV; 322159d1ed5bSDimitry Andric 322239d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 322339d628a0SDimitry Andric QualType()); 32240623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3225f22ef01cSRoman Divacky } 3226f22ef01cSRoman Divacky 3227f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 3228f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node. 32290623d748SDimitry Andric ConstantAddress 3230f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 3231f22ef01cSRoman Divacky std::string Str; 3232f22ef01cSRoman Divacky getContext().getObjCEncodingForType(E->getEncodedType(), Str); 3233f22ef01cSRoman Divacky 3234f22ef01cSRoman Divacky return GetAddrOfConstantCString(Str); 3235f22ef01cSRoman Divacky } 3236f22ef01cSRoman Divacky 323759d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing 323859d1ed5bSDimitry Andric /// the literal and a terminating '\0' character. 323959d1ed5bSDimitry Andric /// The result has pointer to array type. 32400623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString( 32410623d748SDimitry Andric const std::string &Str, const char *GlobalName) { 324259d1ed5bSDimitry Andric StringRef StrWithNull(Str.c_str(), Str.size() + 1); 32430623d748SDimitry Andric CharUnits Alignment = 32440623d748SDimitry Andric getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 3245f22ef01cSRoman Divacky 324659d1ed5bSDimitry Andric llvm::Constant *C = 324759d1ed5bSDimitry Andric llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 324859d1ed5bSDimitry Andric 324959d1ed5bSDimitry Andric // Don't share any string literals if strings aren't constant. 325059d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 325159d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 325259d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 325359d1ed5bSDimitry Andric if (auto GV = *Entry) { 32540623d748SDimitry Andric if (Alignment.getQuantity() > GV->getAlignment()) 32550623d748SDimitry Andric GV->setAlignment(Alignment.getQuantity()); 32560623d748SDimitry Andric return ConstantAddress(GV, Alignment); 325759d1ed5bSDimitry Andric } 325859d1ed5bSDimitry Andric } 325959d1ed5bSDimitry Andric 3260f22ef01cSRoman Divacky // Get the default prefix if a name wasn't specified. 3261f22ef01cSRoman Divacky if (!GlobalName) 3262f22ef01cSRoman Divacky GlobalName = ".str"; 3263f22ef01cSRoman Divacky // Create a global variable for this. 326459d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 326559d1ed5bSDimitry Andric GlobalName, Alignment); 326659d1ed5bSDimitry Andric if (Entry) 326759d1ed5bSDimitry Andric *Entry = GV; 32680623d748SDimitry Andric return ConstantAddress(GV, Alignment); 3269f22ef01cSRoman Divacky } 3270f22ef01cSRoman Divacky 32710623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 3272f785676fSDimitry Andric const MaterializeTemporaryExpr *E, const Expr *Init) { 3273f785676fSDimitry Andric assert((E->getStorageDuration() == SD_Static || 3274f785676fSDimitry Andric E->getStorageDuration() == SD_Thread) && "not a global temporary"); 327559d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 3276f785676fSDimitry Andric 3277f785676fSDimitry Andric // If we're not materializing a subobject of the temporary, keep the 3278f785676fSDimitry Andric // cv-qualifiers from the type of the MaterializeTemporaryExpr. 3279f785676fSDimitry Andric QualType MaterializedType = Init->getType(); 3280f785676fSDimitry Andric if (Init == E->GetTemporaryExpr()) 3281f785676fSDimitry Andric MaterializedType = E->getType(); 3282f785676fSDimitry Andric 32830623d748SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 32840623d748SDimitry Andric 32850623d748SDimitry Andric if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E]) 32860623d748SDimitry Andric return ConstantAddress(Slot, Align); 3287f785676fSDimitry Andric 3288f785676fSDimitry Andric // FIXME: If an externally-visible declaration extends multiple temporaries, 3289f785676fSDimitry Andric // we need to give each temporary the same name in every translation unit (and 3290f785676fSDimitry Andric // we also need to make the temporaries externally-visible). 3291f785676fSDimitry Andric SmallString<256> Name; 3292f785676fSDimitry Andric llvm::raw_svector_ostream Out(Name); 329359d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleReferenceTemporary( 329459d1ed5bSDimitry Andric VD, E->getManglingNumber(), Out); 3295f785676fSDimitry Andric 329659d1ed5bSDimitry Andric APValue *Value = nullptr; 3297f785676fSDimitry Andric if (E->getStorageDuration() == SD_Static) { 3298f785676fSDimitry Andric // We might have a cached constant initializer for this temporary. Note 3299f785676fSDimitry Andric // that this might have a different value from the value computed by 3300f785676fSDimitry Andric // evaluating the initializer if the surrounding constant expression 3301f785676fSDimitry Andric // modifies the temporary. 3302f785676fSDimitry Andric Value = getContext().getMaterializedTemporaryValue(E, false); 3303f785676fSDimitry Andric if (Value && Value->isUninit()) 330459d1ed5bSDimitry Andric Value = nullptr; 3305f785676fSDimitry Andric } 3306f785676fSDimitry Andric 3307f785676fSDimitry Andric // Try evaluating it now, it might have a constant initializer. 3308f785676fSDimitry Andric Expr::EvalResult EvalResult; 3309f785676fSDimitry Andric if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 3310f785676fSDimitry Andric !EvalResult.hasSideEffects()) 3311f785676fSDimitry Andric Value = &EvalResult.Val; 3312f785676fSDimitry Andric 331359d1ed5bSDimitry Andric llvm::Constant *InitialValue = nullptr; 3314f785676fSDimitry Andric bool Constant = false; 3315f785676fSDimitry Andric llvm::Type *Type; 3316f785676fSDimitry Andric if (Value) { 3317f785676fSDimitry Andric // The temporary has a constant initializer, use it. 331859d1ed5bSDimitry Andric InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr); 3319f785676fSDimitry Andric Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 3320f785676fSDimitry Andric Type = InitialValue->getType(); 3321f785676fSDimitry Andric } else { 3322f785676fSDimitry Andric // No initializer, the initialization will be provided when we 3323f785676fSDimitry Andric // initialize the declaration which performed lifetime extension. 3324f785676fSDimitry Andric Type = getTypes().ConvertTypeForMem(MaterializedType); 3325f785676fSDimitry Andric } 3326f785676fSDimitry Andric 3327f785676fSDimitry Andric // Create a global variable for this lifetime-extended temporary. 332859d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 332959d1ed5bSDimitry Andric getLLVMLinkageVarDefinition(VD, Constant); 333033956c43SDimitry Andric if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 333133956c43SDimitry Andric const VarDecl *InitVD; 333233956c43SDimitry Andric if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 333333956c43SDimitry Andric isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 333433956c43SDimitry Andric // Temporaries defined inside a class get linkonce_odr linkage because the 333533956c43SDimitry Andric // class can be defined in multipe translation units. 333633956c43SDimitry Andric Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 333733956c43SDimitry Andric } else { 333833956c43SDimitry Andric // There is no need for this temporary to have external linkage if the 333933956c43SDimitry Andric // VarDecl has external linkage. 334033956c43SDimitry Andric Linkage = llvm::GlobalVariable::InternalLinkage; 334133956c43SDimitry Andric } 334233956c43SDimitry Andric } 334359d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace( 334459d1ed5bSDimitry Andric VD, getContext().getTargetAddressSpace(MaterializedType)); 334559d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 334659d1ed5bSDimitry Andric getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 334759d1ed5bSDimitry Andric /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, 334859d1ed5bSDimitry Andric AddrSpace); 334959d1ed5bSDimitry Andric setGlobalVisibility(GV, VD); 33500623d748SDimitry Andric GV->setAlignment(Align.getQuantity()); 335133956c43SDimitry Andric if (supportsCOMDAT() && GV->isWeakForLinker()) 335233956c43SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3353f785676fSDimitry Andric if (VD->getTLSKind()) 3354f785676fSDimitry Andric setTLSMode(GV, *VD); 33550623d748SDimitry Andric MaterializedGlobalTemporaryMap[E] = GV; 33560623d748SDimitry Andric return ConstantAddress(GV, Align); 3357f785676fSDimitry Andric } 3358f785676fSDimitry Andric 3359f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized 3360f22ef01cSRoman Divacky /// properties for an implementation. 3361f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const 3362f22ef01cSRoman Divacky ObjCImplementationDecl *D) { 336359d1ed5bSDimitry Andric for (const auto *PID : D->property_impls()) { 3364f22ef01cSRoman Divacky // Dynamic is just for type-checking. 3365f22ef01cSRoman Divacky if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 3366f22ef01cSRoman Divacky ObjCPropertyDecl *PD = PID->getPropertyDecl(); 3367f22ef01cSRoman Divacky 3368f22ef01cSRoman Divacky // Determine which methods need to be implemented, some may have 33693861d79fSDimitry Andric // been overridden. Note that ::isPropertyAccessor is not the method 3370f22ef01cSRoman Divacky // we want, that just indicates if the decl came from a 3371f22ef01cSRoman Divacky // property. What we want to know is if the method is defined in 3372f22ef01cSRoman Divacky // this implementation. 3373f22ef01cSRoman Divacky if (!D->getInstanceMethod(PD->getGetterName())) 3374f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCGetter( 3375f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3376f22ef01cSRoman Divacky if (!PD->isReadOnly() && 3377f22ef01cSRoman Divacky !D->getInstanceMethod(PD->getSetterName())) 3378f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCSetter( 3379f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3380f22ef01cSRoman Divacky } 3381f22ef01cSRoman Divacky } 3382f22ef01cSRoman Divacky } 3383f22ef01cSRoman Divacky 33843b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) { 33856122f3e6SDimitry Andric const ObjCInterfaceDecl *iface = impl->getClassInterface(); 33866122f3e6SDimitry Andric for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 33873b0f4066SDimitry Andric ivar; ivar = ivar->getNextIvar()) 33883b0f4066SDimitry Andric if (ivar->getType().isDestructedType()) 33893b0f4066SDimitry Andric return true; 33903b0f4066SDimitry Andric 33913b0f4066SDimitry Andric return false; 33923b0f4066SDimitry Andric } 33933b0f4066SDimitry Andric 339439d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM, 339539d628a0SDimitry Andric ObjCImplementationDecl *D) { 339639d628a0SDimitry Andric CodeGenFunction CGF(CGM); 339739d628a0SDimitry Andric for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 339839d628a0SDimitry Andric E = D->init_end(); B != E; ++B) { 339939d628a0SDimitry Andric CXXCtorInitializer *CtorInitExp = *B; 340039d628a0SDimitry Andric Expr *Init = CtorInitExp->getInit(); 340139d628a0SDimitry Andric if (!CGF.isTrivialInitializer(Init)) 340239d628a0SDimitry Andric return false; 340339d628a0SDimitry Andric } 340439d628a0SDimitry Andric return true; 340539d628a0SDimitry Andric } 340639d628a0SDimitry Andric 3407f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization 3408f22ef01cSRoman Divacky /// for an implementation. 3409f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 34103b0f4066SDimitry Andric // We might need a .cxx_destruct even if we don't have any ivar initializers. 34113b0f4066SDimitry Andric if (needsDestructMethod(D)) { 3412f22ef01cSRoman Divacky IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 3413f22ef01cSRoman Divacky Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 34143b0f4066SDimitry Andric ObjCMethodDecl *DTORMethod = 34153b0f4066SDimitry Andric ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 341659d1ed5bSDimitry Andric cxxSelector, getContext().VoidTy, nullptr, D, 34176122f3e6SDimitry Andric /*isInstance=*/true, /*isVariadic=*/false, 34183861d79fSDimitry Andric /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 34196122f3e6SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 3420f22ef01cSRoman Divacky D->addInstanceMethod(DTORMethod); 3421f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 34223861d79fSDimitry Andric D->setHasDestructors(true); 34233b0f4066SDimitry Andric } 3424f22ef01cSRoman Divacky 34253b0f4066SDimitry Andric // If the implementation doesn't have any ivar initializers, we don't need 34263b0f4066SDimitry Andric // a .cxx_construct. 342739d628a0SDimitry Andric if (D->getNumIvarInitializers() == 0 || 342839d628a0SDimitry Andric AllTrivialInitializers(*this, D)) 34293b0f4066SDimitry Andric return; 34303b0f4066SDimitry Andric 34313b0f4066SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 34323b0f4066SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 3433f22ef01cSRoman Divacky // The constructor returns 'self'. 3434f22ef01cSRoman Divacky ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 3435f22ef01cSRoman Divacky D->getLocation(), 34366122f3e6SDimitry Andric D->getLocation(), 34376122f3e6SDimitry Andric cxxSelector, 343859d1ed5bSDimitry Andric getContext().getObjCIdType(), 343959d1ed5bSDimitry Andric nullptr, D, /*isInstance=*/true, 34406122f3e6SDimitry Andric /*isVariadic=*/false, 34413861d79fSDimitry Andric /*isPropertyAccessor=*/true, 34426122f3e6SDimitry Andric /*isImplicitlyDeclared=*/true, 34436122f3e6SDimitry Andric /*isDefined=*/false, 3444f22ef01cSRoman Divacky ObjCMethodDecl::Required); 3445f22ef01cSRoman Divacky D->addInstanceMethod(CTORMethod); 3446f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 34473861d79fSDimitry Andric D->setHasNonZeroConstructors(true); 3448f22ef01cSRoman Divacky } 3449f22ef01cSRoman Divacky 3450f22ef01cSRoman Divacky /// EmitNamespace - Emit all declarations in a namespace. 3451f22ef01cSRoman Divacky void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 345259d1ed5bSDimitry Andric for (auto *I : ND->decls()) { 345359d1ed5bSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(I)) 3454f785676fSDimitry Andric if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 3455f785676fSDimitry Andric VD->getTemplateSpecializationKind() != TSK_Undeclared) 3456f785676fSDimitry Andric continue; 345759d1ed5bSDimitry Andric EmitTopLevelDecl(I); 3458f22ef01cSRoman Divacky } 3459f785676fSDimitry Andric } 3460f22ef01cSRoman Divacky 3461f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec. 3462f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 3463f22ef01cSRoman Divacky if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 3464f22ef01cSRoman Divacky LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 3465f22ef01cSRoman Divacky ErrorUnsupported(LSD, "linkage spec"); 3466f22ef01cSRoman Divacky return; 3467f22ef01cSRoman Divacky } 3468f22ef01cSRoman Divacky 346959d1ed5bSDimitry Andric for (auto *I : LSD->decls()) { 34703861d79fSDimitry Andric // Meta-data for ObjC class includes references to implemented methods. 34713861d79fSDimitry Andric // Generate class's method definitions first. 347259d1ed5bSDimitry Andric if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 347359d1ed5bSDimitry Andric for (auto *M : OID->methods()) 347459d1ed5bSDimitry Andric EmitTopLevelDecl(M); 34753861d79fSDimitry Andric } 347659d1ed5bSDimitry Andric EmitTopLevelDecl(I); 3477f22ef01cSRoman Divacky } 34783861d79fSDimitry Andric } 3479f22ef01cSRoman Divacky 3480f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration. 3481f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) { 3482f22ef01cSRoman Divacky // Ignore dependent declarations. 3483f22ef01cSRoman Divacky if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 3484f22ef01cSRoman Divacky return; 3485f22ef01cSRoman Divacky 3486f22ef01cSRoman Divacky switch (D->getKind()) { 3487f22ef01cSRoman Divacky case Decl::CXXConversion: 3488f22ef01cSRoman Divacky case Decl::CXXMethod: 3489f22ef01cSRoman Divacky case Decl::Function: 3490f22ef01cSRoman Divacky // Skip function templates 34913b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 34923b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3493f22ef01cSRoman Divacky return; 3494f22ef01cSRoman Divacky 3495f22ef01cSRoman Divacky EmitGlobal(cast<FunctionDecl>(D)); 349639d628a0SDimitry Andric // Always provide some coverage mapping 349739d628a0SDimitry Andric // even for the functions that aren't emitted. 349839d628a0SDimitry Andric AddDeferredUnusedCoverageMapping(D); 3499f22ef01cSRoman Divacky break; 3500f22ef01cSRoman Divacky 3501f22ef01cSRoman Divacky case Decl::Var: 3502f785676fSDimitry Andric // Skip variable templates 3503f785676fSDimitry Andric if (cast<VarDecl>(D)->getDescribedVarTemplate()) 3504f785676fSDimitry Andric return; 3505f785676fSDimitry Andric case Decl::VarTemplateSpecialization: 3506f22ef01cSRoman Divacky EmitGlobal(cast<VarDecl>(D)); 3507f22ef01cSRoman Divacky break; 3508f22ef01cSRoman Divacky 35093b0f4066SDimitry Andric // Indirect fields from global anonymous structs and unions can be 35103b0f4066SDimitry Andric // ignored; only the actual variable requires IR gen support. 35113b0f4066SDimitry Andric case Decl::IndirectField: 35123b0f4066SDimitry Andric break; 35133b0f4066SDimitry Andric 3514f22ef01cSRoman Divacky // C++ Decls 3515f22ef01cSRoman Divacky case Decl::Namespace: 3516f22ef01cSRoman Divacky EmitNamespace(cast<NamespaceDecl>(D)); 3517f22ef01cSRoman Divacky break; 3518f22ef01cSRoman Divacky // No code generation needed. 3519f22ef01cSRoman Divacky case Decl::UsingShadow: 3520f22ef01cSRoman Divacky case Decl::ClassTemplate: 3521f785676fSDimitry Andric case Decl::VarTemplate: 3522f785676fSDimitry Andric case Decl::VarTemplatePartialSpecialization: 3523f22ef01cSRoman Divacky case Decl::FunctionTemplate: 3524bd5abe19SDimitry Andric case Decl::TypeAliasTemplate: 3525bd5abe19SDimitry Andric case Decl::Block: 3526139f7f9bSDimitry Andric case Decl::Empty: 3527f22ef01cSRoman Divacky break; 352859d1ed5bSDimitry Andric case Decl::Using: // using X; [C++] 352959d1ed5bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 353059d1ed5bSDimitry Andric DI->EmitUsingDecl(cast<UsingDecl>(*D)); 353159d1ed5bSDimitry Andric return; 3532f785676fSDimitry Andric case Decl::NamespaceAlias: 3533f785676fSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3534f785676fSDimitry Andric DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 3535f785676fSDimitry Andric return; 3536284c1978SDimitry Andric case Decl::UsingDirective: // using namespace X; [C++] 3537284c1978SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3538284c1978SDimitry Andric DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 3539284c1978SDimitry Andric return; 3540f22ef01cSRoman Divacky case Decl::CXXConstructor: 3541f22ef01cSRoman Divacky // Skip function templates 35423b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 35433b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3544f22ef01cSRoman Divacky return; 3545f22ef01cSRoman Divacky 3546f785676fSDimitry Andric getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 3547f22ef01cSRoman Divacky break; 3548f22ef01cSRoman Divacky case Decl::CXXDestructor: 35493b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 35503b0f4066SDimitry Andric return; 3551f785676fSDimitry Andric getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 3552f22ef01cSRoman Divacky break; 3553f22ef01cSRoman Divacky 3554f22ef01cSRoman Divacky case Decl::StaticAssert: 3555f22ef01cSRoman Divacky // Nothing to do. 3556f22ef01cSRoman Divacky break; 3557f22ef01cSRoman Divacky 3558f22ef01cSRoman Divacky // Objective-C Decls 3559f22ef01cSRoman Divacky 3560f22ef01cSRoman Divacky // Forward declarations, no (immediate) code generation. 3561f22ef01cSRoman Divacky case Decl::ObjCInterface: 35627ae0e2c9SDimitry Andric case Decl::ObjCCategory: 3563f22ef01cSRoman Divacky break; 3564f22ef01cSRoman Divacky 3565dff0c46cSDimitry Andric case Decl::ObjCProtocol: { 356659d1ed5bSDimitry Andric auto *Proto = cast<ObjCProtocolDecl>(D); 3567dff0c46cSDimitry Andric if (Proto->isThisDeclarationADefinition()) 3568dff0c46cSDimitry Andric ObjCRuntime->GenerateProtocol(Proto); 3569f22ef01cSRoman Divacky break; 3570dff0c46cSDimitry Andric } 3571f22ef01cSRoman Divacky 3572f22ef01cSRoman Divacky case Decl::ObjCCategoryImpl: 3573f22ef01cSRoman Divacky // Categories have properties but don't support synthesize so we 3574f22ef01cSRoman Divacky // can ignore them here. 35756122f3e6SDimitry Andric ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 3576f22ef01cSRoman Divacky break; 3577f22ef01cSRoman Divacky 3578f22ef01cSRoman Divacky case Decl::ObjCImplementation: { 357959d1ed5bSDimitry Andric auto *OMD = cast<ObjCImplementationDecl>(D); 3580f22ef01cSRoman Divacky EmitObjCPropertyImplementations(OMD); 3581f22ef01cSRoman Divacky EmitObjCIvarInitializations(OMD); 35826122f3e6SDimitry Andric ObjCRuntime->GenerateClass(OMD); 3583dff0c46cSDimitry Andric // Emit global variable debug information. 3584dff0c46cSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3585139f7f9bSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 3586139f7f9bSDimitry Andric DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 3587139f7f9bSDimitry Andric OMD->getClassInterface()), OMD->getLocation()); 3588f22ef01cSRoman Divacky break; 3589f22ef01cSRoman Divacky } 3590f22ef01cSRoman Divacky case Decl::ObjCMethod: { 359159d1ed5bSDimitry Andric auto *OMD = cast<ObjCMethodDecl>(D); 3592f22ef01cSRoman Divacky // If this is not a prototype, emit the body. 3593f22ef01cSRoman Divacky if (OMD->getBody()) 3594f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCMethod(OMD); 3595f22ef01cSRoman Divacky break; 3596f22ef01cSRoman Divacky } 3597f22ef01cSRoman Divacky case Decl::ObjCCompatibleAlias: 3598dff0c46cSDimitry Andric ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 3599f22ef01cSRoman Divacky break; 3600f22ef01cSRoman Divacky 3601f22ef01cSRoman Divacky case Decl::LinkageSpec: 3602f22ef01cSRoman Divacky EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 3603f22ef01cSRoman Divacky break; 3604f22ef01cSRoman Divacky 3605f22ef01cSRoman Divacky case Decl::FileScopeAsm: { 360633956c43SDimitry Andric // File-scope asm is ignored during device-side CUDA compilation. 360733956c43SDimitry Andric if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 360833956c43SDimitry Andric break; 3609ea942507SDimitry Andric // File-scope asm is ignored during device-side OpenMP compilation. 3610ea942507SDimitry Andric if (LangOpts.OpenMPIsDevice) 3611ea942507SDimitry Andric break; 361259d1ed5bSDimitry Andric auto *AD = cast<FileScopeAsmDecl>(D); 361333956c43SDimitry Andric getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 3614f22ef01cSRoman Divacky break; 3615f22ef01cSRoman Divacky } 3616f22ef01cSRoman Divacky 3617139f7f9bSDimitry Andric case Decl::Import: { 361859d1ed5bSDimitry Andric auto *Import = cast<ImportDecl>(D); 3619139f7f9bSDimitry Andric 3620139f7f9bSDimitry Andric // Ignore import declarations that come from imported modules. 36210623d748SDimitry Andric if (Import->getImportedOwningModule()) 3622139f7f9bSDimitry Andric break; 36233dac3a9bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 36243dac3a9bSDimitry Andric DI->EmitImportDecl(*Import); 3625139f7f9bSDimitry Andric 3626139f7f9bSDimitry Andric ImportedModules.insert(Import->getImportedModule()); 3627139f7f9bSDimitry Andric break; 3628139f7f9bSDimitry Andric } 3629139f7f9bSDimitry Andric 363039d628a0SDimitry Andric case Decl::OMPThreadPrivate: 363139d628a0SDimitry Andric EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 363239d628a0SDimitry Andric break; 363339d628a0SDimitry Andric 363459d1ed5bSDimitry Andric case Decl::ClassTemplateSpecialization: { 363559d1ed5bSDimitry Andric const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 363659d1ed5bSDimitry Andric if (DebugInfo && 363739d628a0SDimitry Andric Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition && 363839d628a0SDimitry Andric Spec->hasDefinition()) 363959d1ed5bSDimitry Andric DebugInfo->completeTemplateDefinition(*Spec); 364039d628a0SDimitry Andric break; 364159d1ed5bSDimitry Andric } 364259d1ed5bSDimitry Andric 3643f22ef01cSRoman Divacky default: 3644f22ef01cSRoman Divacky // Make sure we handled everything we should, every other kind is a 3645f22ef01cSRoman Divacky // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 3646f22ef01cSRoman Divacky // function. Need to recode Decl::Kind to do that easily. 3647f22ef01cSRoman Divacky assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 364839d628a0SDimitry Andric break; 364939d628a0SDimitry Andric } 365039d628a0SDimitry Andric } 365139d628a0SDimitry Andric 365239d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 365339d628a0SDimitry Andric // Do we need to generate coverage mapping? 365439d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 365539d628a0SDimitry Andric return; 365639d628a0SDimitry Andric switch (D->getKind()) { 365739d628a0SDimitry Andric case Decl::CXXConversion: 365839d628a0SDimitry Andric case Decl::CXXMethod: 365939d628a0SDimitry Andric case Decl::Function: 366039d628a0SDimitry Andric case Decl::ObjCMethod: 366139d628a0SDimitry Andric case Decl::CXXConstructor: 366239d628a0SDimitry Andric case Decl::CXXDestructor: { 36630623d748SDimitry Andric if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 366439d628a0SDimitry Andric return; 366539d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 366639d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 366739d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = true; 366839d628a0SDimitry Andric break; 366939d628a0SDimitry Andric } 367039d628a0SDimitry Andric default: 367139d628a0SDimitry Andric break; 367239d628a0SDimitry Andric }; 367339d628a0SDimitry Andric } 367439d628a0SDimitry Andric 367539d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 367639d628a0SDimitry Andric // Do we need to generate coverage mapping? 367739d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 367839d628a0SDimitry Andric return; 367939d628a0SDimitry Andric if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 368039d628a0SDimitry Andric if (Fn->isTemplateInstantiation()) 368139d628a0SDimitry Andric ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 368239d628a0SDimitry Andric } 368339d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 368439d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 368539d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = false; 368639d628a0SDimitry Andric else 368739d628a0SDimitry Andric I->second = false; 368839d628a0SDimitry Andric } 368939d628a0SDimitry Andric 369039d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 369139d628a0SDimitry Andric std::vector<const Decl *> DeferredDecls; 369233956c43SDimitry Andric for (const auto &I : DeferredEmptyCoverageMappingDecls) { 369339d628a0SDimitry Andric if (!I.second) 369439d628a0SDimitry Andric continue; 369539d628a0SDimitry Andric DeferredDecls.push_back(I.first); 369639d628a0SDimitry Andric } 369739d628a0SDimitry Andric // Sort the declarations by their location to make sure that the tests get a 369839d628a0SDimitry Andric // predictable order for the coverage mapping for the unused declarations. 369939d628a0SDimitry Andric if (CodeGenOpts.DumpCoverageMapping) 370039d628a0SDimitry Andric std::sort(DeferredDecls.begin(), DeferredDecls.end(), 370139d628a0SDimitry Andric [] (const Decl *LHS, const Decl *RHS) { 370239d628a0SDimitry Andric return LHS->getLocStart() < RHS->getLocStart(); 370339d628a0SDimitry Andric }); 370439d628a0SDimitry Andric for (const auto *D : DeferredDecls) { 370539d628a0SDimitry Andric switch (D->getKind()) { 370639d628a0SDimitry Andric case Decl::CXXConversion: 370739d628a0SDimitry Andric case Decl::CXXMethod: 370839d628a0SDimitry Andric case Decl::Function: 370939d628a0SDimitry Andric case Decl::ObjCMethod: { 371039d628a0SDimitry Andric CodeGenPGO PGO(*this); 371139d628a0SDimitry Andric GlobalDecl GD(cast<FunctionDecl>(D)); 371239d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 371339d628a0SDimitry Andric getFunctionLinkage(GD)); 371439d628a0SDimitry Andric break; 371539d628a0SDimitry Andric } 371639d628a0SDimitry Andric case Decl::CXXConstructor: { 371739d628a0SDimitry Andric CodeGenPGO PGO(*this); 371839d628a0SDimitry Andric GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 371939d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 372039d628a0SDimitry Andric getFunctionLinkage(GD)); 372139d628a0SDimitry Andric break; 372239d628a0SDimitry Andric } 372339d628a0SDimitry Andric case Decl::CXXDestructor: { 372439d628a0SDimitry Andric CodeGenPGO PGO(*this); 372539d628a0SDimitry Andric GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 372639d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 372739d628a0SDimitry Andric getFunctionLinkage(GD)); 372839d628a0SDimitry Andric break; 372939d628a0SDimitry Andric } 373039d628a0SDimitry Andric default: 373139d628a0SDimitry Andric break; 373239d628a0SDimitry Andric }; 3733f22ef01cSRoman Divacky } 3734f22ef01cSRoman Divacky } 3735ffd1746dSEd Schouten 3736ffd1746dSEd Schouten /// Turns the given pointer into a constant. 3737ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 3738ffd1746dSEd Schouten const void *Ptr) { 3739ffd1746dSEd Schouten uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 37406122f3e6SDimitry Andric llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 3741ffd1746dSEd Schouten return llvm::ConstantInt::get(i64, PtrInt); 3742ffd1746dSEd Schouten } 3743ffd1746dSEd Schouten 3744ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 3745ffd1746dSEd Schouten llvm::NamedMDNode *&GlobalMetadata, 3746ffd1746dSEd Schouten GlobalDecl D, 3747ffd1746dSEd Schouten llvm::GlobalValue *Addr) { 3748ffd1746dSEd Schouten if (!GlobalMetadata) 3749ffd1746dSEd Schouten GlobalMetadata = 3750ffd1746dSEd Schouten CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 3751ffd1746dSEd Schouten 3752ffd1746dSEd Schouten // TODO: should we report variant information for ctors/dtors? 375339d628a0SDimitry Andric llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 375439d628a0SDimitry Andric llvm::ConstantAsMetadata::get(GetPointerConstant( 375539d628a0SDimitry Andric CGM.getLLVMContext(), D.getDecl()))}; 37563b0f4066SDimitry Andric GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 3757ffd1746dSEd Schouten } 3758ffd1746dSEd Schouten 3759284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked 3760284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled 3761284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer 3762284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the 3763284c1978SDimitry Andric /// same translation unit. 3764284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() { 37658f0fd8f6SDimitry Andric for (auto &I : StaticExternCValues) { 37668f0fd8f6SDimitry Andric IdentifierInfo *Name = I.first; 37678f0fd8f6SDimitry Andric llvm::GlobalValue *Val = I.second; 3768284c1978SDimitry Andric if (Val && !getModule().getNamedValue(Name->getName())) 376959d1ed5bSDimitry Andric addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 3770284c1978SDimitry Andric } 3771284c1978SDimitry Andric } 3772284c1978SDimitry Andric 377359d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 377459d1ed5bSDimitry Andric GlobalDecl &Result) const { 377559d1ed5bSDimitry Andric auto Res = Manglings.find(MangledName); 377659d1ed5bSDimitry Andric if (Res == Manglings.end()) 377759d1ed5bSDimitry Andric return false; 377859d1ed5bSDimitry Andric Result = Res->getValue(); 377959d1ed5bSDimitry Andric return true; 378059d1ed5bSDimitry Andric } 378159d1ed5bSDimitry Andric 3782ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the 3783ffd1746dSEd Schouten /// current module with the Decls they came from. This is useful for 3784ffd1746dSEd Schouten /// projects using IR gen as a subroutine. 3785ffd1746dSEd Schouten /// 3786ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly 3787ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata 3788ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'. 3789ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() { 379059d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 3791ffd1746dSEd Schouten 379259d1ed5bSDimitry Andric for (auto &I : MangledDeclNames) { 379359d1ed5bSDimitry Andric llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 37940623d748SDimitry Andric // Some mangled names don't necessarily have an associated GlobalValue 37950623d748SDimitry Andric // in this module, e.g. if we mangled it for DebugInfo. 37960623d748SDimitry Andric if (Addr) 379759d1ed5bSDimitry Andric EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 3798ffd1746dSEd Schouten } 3799ffd1746dSEd Schouten } 3800ffd1746dSEd Schouten 3801ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current 3802ffd1746dSEd Schouten /// function. 3803ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() { 3804ffd1746dSEd Schouten if (LocalDeclMap.empty()) return; 3805ffd1746dSEd Schouten 3806ffd1746dSEd Schouten llvm::LLVMContext &Context = getLLVMContext(); 3807ffd1746dSEd Schouten 3808ffd1746dSEd Schouten // Find the unique metadata ID for this name. 3809ffd1746dSEd Schouten unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 3810ffd1746dSEd Schouten 381159d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 3812ffd1746dSEd Schouten 381359d1ed5bSDimitry Andric for (auto &I : LocalDeclMap) { 381459d1ed5bSDimitry Andric const Decl *D = I.first; 38150623d748SDimitry Andric llvm::Value *Addr = I.second.getPointer(); 381659d1ed5bSDimitry Andric if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 3817ffd1746dSEd Schouten llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 381839d628a0SDimitry Andric Alloca->setMetadata( 381939d628a0SDimitry Andric DeclPtrKind, llvm::MDNode::get( 382039d628a0SDimitry Andric Context, llvm::ValueAsMetadata::getConstant(DAddr))); 382159d1ed5bSDimitry Andric } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 3822ffd1746dSEd Schouten GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 3823ffd1746dSEd Schouten EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 3824ffd1746dSEd Schouten } 3825ffd1746dSEd Schouten } 3826ffd1746dSEd Schouten } 3827e580952dSDimitry Andric 3828f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() { 3829f785676fSDimitry Andric llvm::NamedMDNode *IdentMetadata = 3830f785676fSDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.ident"); 3831f785676fSDimitry Andric std::string Version = getClangFullVersion(); 3832f785676fSDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 3833f785676fSDimitry Andric 383439d628a0SDimitry Andric llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 3835f785676fSDimitry Andric IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 3836f785676fSDimitry Andric } 3837f785676fSDimitry Andric 383859d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() { 383939d628a0SDimitry Andric // Warning, new MangledDeclNames may be appended within this loop. 384039d628a0SDimitry Andric // We rely on MapVector insertions adding new elements to the end 384139d628a0SDimitry Andric // of the container. 384239d628a0SDimitry Andric // FIXME: Move this loop into the one target that needs it, and only 384339d628a0SDimitry Andric // loop over those declarations for which we couldn't emit the target 384439d628a0SDimitry Andric // metadata when we emitted the declaration. 384539d628a0SDimitry Andric for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 384639d628a0SDimitry Andric auto Val = *(MangledDeclNames.begin() + I); 384739d628a0SDimitry Andric const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 384839d628a0SDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(Val.second); 384959d1ed5bSDimitry Andric getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 385059d1ed5bSDimitry Andric } 385159d1ed5bSDimitry Andric } 385259d1ed5bSDimitry Andric 3853bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() { 3854bd5abe19SDimitry Andric if (!getCodeGenOpts().CoverageFile.empty()) { 3855bd5abe19SDimitry Andric if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 3856bd5abe19SDimitry Andric llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 3857bd5abe19SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 3858bd5abe19SDimitry Andric llvm::MDString *CoverageFile = 3859bd5abe19SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 3860bd5abe19SDimitry Andric for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 3861bd5abe19SDimitry Andric llvm::MDNode *CU = CUNode->getOperand(i); 386239d628a0SDimitry Andric llvm::Metadata *Elts[] = {CoverageFile, CU}; 386339d628a0SDimitry Andric GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 3864bd5abe19SDimitry Andric } 3865bd5abe19SDimitry Andric } 3866bd5abe19SDimitry Andric } 3867bd5abe19SDimitry Andric } 38683861d79fSDimitry Andric 386939d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { 38703861d79fSDimitry Andric // Sema has checked that all uuid strings are of the form 38713861d79fSDimitry Andric // "12345678-1234-1234-1234-1234567890ab". 38723861d79fSDimitry Andric assert(Uuid.size() == 36); 3873f785676fSDimitry Andric for (unsigned i = 0; i < 36; ++i) { 3874f785676fSDimitry Andric if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 3875f785676fSDimitry Andric else assert(isHexDigit(Uuid[i])); 38763861d79fSDimitry Andric } 38773861d79fSDimitry Andric 387839d628a0SDimitry Andric // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". 3879f785676fSDimitry Andric const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 38803861d79fSDimitry Andric 3881f785676fSDimitry Andric llvm::Constant *Field3[8]; 3882f785676fSDimitry Andric for (unsigned Idx = 0; Idx < 8; ++Idx) 3883f785676fSDimitry Andric Field3[Idx] = llvm::ConstantInt::get( 3884f785676fSDimitry Andric Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 38853861d79fSDimitry Andric 3886f785676fSDimitry Andric llvm::Constant *Fields[4] = { 3887f785676fSDimitry Andric llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 3888f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 3889f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 3890f785676fSDimitry Andric llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 3891f785676fSDimitry Andric }; 3892f785676fSDimitry Andric 3893f785676fSDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 38943861d79fSDimitry Andric } 389559d1ed5bSDimitry Andric 389659d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 389759d1ed5bSDimitry Andric bool ForEH) { 389859d1ed5bSDimitry Andric // Return a bogus pointer if RTTI is disabled, unless it's for EH. 389959d1ed5bSDimitry Andric // FIXME: should we even be calling this method if RTTI is disabled 390059d1ed5bSDimitry Andric // and it's not for EH? 390159d1ed5bSDimitry Andric if (!ForEH && !getLangOpts().RTTI) 390259d1ed5bSDimitry Andric return llvm::Constant::getNullValue(Int8PtrTy); 390359d1ed5bSDimitry Andric 390459d1ed5bSDimitry Andric if (ForEH && Ty->isObjCObjectPointerType() && 390559d1ed5bSDimitry Andric LangOpts.ObjCRuntime.isGNUFamily()) 390659d1ed5bSDimitry Andric return ObjCRuntime->GetEHType(Ty); 390759d1ed5bSDimitry Andric 390859d1ed5bSDimitry Andric return getCXXABI().getAddrOfRTTIDescriptor(Ty); 390959d1ed5bSDimitry Andric } 391059d1ed5bSDimitry Andric 391139d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 391239d628a0SDimitry Andric for (auto RefExpr : D->varlists()) { 391339d628a0SDimitry Andric auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 391439d628a0SDimitry Andric bool PerformInit = 391539d628a0SDimitry Andric VD->getAnyInitializer() && 391639d628a0SDimitry Andric !VD->getAnyInitializer()->isConstantInitializer(getContext(), 391739d628a0SDimitry Andric /*ForRef=*/false); 39180623d748SDimitry Andric 39190623d748SDimitry Andric Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 392033956c43SDimitry Andric if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 39210623d748SDimitry Andric VD, Addr, RefExpr->getLocStart(), PerformInit)) 392239d628a0SDimitry Andric CXXGlobalInits.push_back(InitFunction); 392339d628a0SDimitry Andric } 392439d628a0SDimitry Andric } 39258f0fd8f6SDimitry Andric 39260623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 39270623d748SDimitry Andric llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()]; 39280623d748SDimitry Andric if (InternalId) 39290623d748SDimitry Andric return InternalId; 39300623d748SDimitry Andric 39310623d748SDimitry Andric if (isExternallyVisible(T->getLinkage())) { 39328f0fd8f6SDimitry Andric std::string OutName; 39338f0fd8f6SDimitry Andric llvm::raw_string_ostream Out(OutName); 39340623d748SDimitry Andric getCXXABI().getMangleContext().mangleTypeName(T, Out); 39358f0fd8f6SDimitry Andric 39360623d748SDimitry Andric InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 39370623d748SDimitry Andric } else { 39380623d748SDimitry Andric InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 39390623d748SDimitry Andric llvm::ArrayRef<llvm::Metadata *>()); 39400623d748SDimitry Andric } 39410623d748SDimitry Andric 39420623d748SDimitry Andric return InternalId; 39430623d748SDimitry Andric } 39440623d748SDimitry Andric 39450623d748SDimitry Andric void CodeGenModule::CreateVTableBitSetEntry(llvm::NamedMDNode *BitsetsMD, 39460623d748SDimitry Andric llvm::GlobalVariable *VTable, 39470623d748SDimitry Andric CharUnits Offset, 39480623d748SDimitry Andric const CXXRecordDecl *RD) { 39490623d748SDimitry Andric llvm::Metadata *MD = 39500623d748SDimitry Andric CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 39518f0fd8f6SDimitry Andric llvm::Metadata *BitsetOps[] = { 39520623d748SDimitry Andric MD, llvm::ConstantAsMetadata::get(VTable), 39530623d748SDimitry Andric llvm::ConstantAsMetadata::get( 39540623d748SDimitry Andric llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))}; 39550623d748SDimitry Andric BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps)); 39560623d748SDimitry Andric 39570623d748SDimitry Andric if (CodeGenOpts.SanitizeCfiCrossDso) { 39580623d748SDimitry Andric if (auto TypeId = CreateCfiIdForTypeMetadata(MD)) { 39590623d748SDimitry Andric llvm::Metadata *BitsetOps2[] = { 39600623d748SDimitry Andric llvm::ConstantAsMetadata::get(TypeId), 39618f0fd8f6SDimitry Andric llvm::ConstantAsMetadata::get(VTable), 39628f0fd8f6SDimitry Andric llvm::ConstantAsMetadata::get( 39638f0fd8f6SDimitry Andric llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))}; 39640623d748SDimitry Andric BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps2)); 39650623d748SDimitry Andric } 39660623d748SDimitry Andric } 39670623d748SDimitry Andric } 39680623d748SDimitry Andric 39690623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the 39700623d748SDimitry Andric // passed in function. 39710623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap, 39720623d748SDimitry Andric const FunctionDecl *FD) { 39730623d748SDimitry Andric StringRef TargetCPU = Target.getTargetOpts().CPU; 39740623d748SDimitry Andric if (const auto *TD = FD->getAttr<TargetAttr>()) { 39750623d748SDimitry Andric // If we have a TargetAttr build up the feature map based on that. 39760623d748SDimitry Andric TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); 39770623d748SDimitry Andric 39780623d748SDimitry Andric // Make a copy of the features as passed on the command line into the 39790623d748SDimitry Andric // beginning of the additional features from the function to override. 39800623d748SDimitry Andric ParsedAttr.first.insert(ParsedAttr.first.begin(), 39810623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.begin(), 39820623d748SDimitry Andric Target.getTargetOpts().FeaturesAsWritten.end()); 39830623d748SDimitry Andric 39840623d748SDimitry Andric if (ParsedAttr.second != "") 39850623d748SDimitry Andric TargetCPU = ParsedAttr.second; 39860623d748SDimitry Andric 39870623d748SDimitry Andric // Now populate the feature map, first with the TargetCPU which is either 39880623d748SDimitry Andric // the default or a new one from the target attribute string. Then we'll use 39890623d748SDimitry Andric // the passed in features (FeaturesAsWritten) along with the new ones from 39900623d748SDimitry Andric // the attribute. 39910623d748SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first); 39920623d748SDimitry Andric } else { 39930623d748SDimitry Andric Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, 39940623d748SDimitry Andric Target.getTargetOpts().Features); 39950623d748SDimitry Andric } 39968f0fd8f6SDimitry Andric } 3997