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" 156122f3e6SDimitry Andric #include "CGCUDARuntime.h" 16e580952dSDimitry Andric #include "CGCXXABI.h" 17139f7f9bSDimitry Andric #include "CGCall.h" 18139f7f9bSDimitry Andric #include "CGDebugInfo.h" 19f22ef01cSRoman Divacky #include "CGObjCRuntime.h" 206122f3e6SDimitry Andric #include "CGOpenCLRuntime.h" 2159d1ed5bSDimitry Andric #include "CGOpenMPRuntime.h" 22139f7f9bSDimitry Andric #include "CodeGenFunction.h" 2359d1ed5bSDimitry Andric #include "CodeGenPGO.h" 24139f7f9bSDimitry Andric #include "CodeGenTBAA.h" 2539d628a0SDimitry Andric #include "CoverageMappingGen.h" 26f22ef01cSRoman Divacky #include "TargetInfo.h" 27f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h" 28f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h" 29f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h" 30139f7f9bSDimitry Andric #include "clang/AST/DeclObjC.h" 31ffd1746dSEd Schouten #include "clang/AST/DeclTemplate.h" 322754fe60SDimitry Andric #include "clang/AST/Mangle.h" 33f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h" 34f8254f43SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h" 35dff0c46cSDimitry Andric #include "clang/Basic/Builtins.h" 36139f7f9bSDimitry Andric #include "clang/Basic/CharInfo.h" 37f22ef01cSRoman Divacky #include "clang/Basic/Diagnostic.h" 38139f7f9bSDimitry Andric #include "clang/Basic/Module.h" 39f22ef01cSRoman Divacky #include "clang/Basic/SourceManager.h" 40f22ef01cSRoman Divacky #include "clang/Basic/TargetInfo.h" 41f785676fSDimitry Andric #include "clang/Basic/Version.h" 42139f7f9bSDimitry Andric #include "clang/Frontend/CodeGenOptions.h" 43f785676fSDimitry Andric #include "clang/Sema/SemaDiagnostic.h" 44dff0c46cSDimitry Andric #include "llvm/ADT/APSInt.h" 45f22ef01cSRoman Divacky #include "llvm/ADT/Triple.h" 4659d1ed5bSDimitry Andric #include "llvm/IR/CallSite.h" 47139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h" 48139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h" 49139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h" 50139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h" 51139f7f9bSDimitry Andric #include "llvm/IR/Module.h" 5259d1ed5bSDimitry Andric #include "llvm/ProfileData/InstrProfReader.h" 53139f7f9bSDimitry Andric #include "llvm/Support/ConvertUTF.h" 54f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h" 55139f7f9bSDimitry Andric 56f22ef01cSRoman Divacky using namespace clang; 57f22ef01cSRoman Divacky using namespace CodeGen; 58f22ef01cSRoman Divacky 596122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata"; 606122f3e6SDimitry Andric 6159d1ed5bSDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 62284c1978SDimitry Andric switch (CGM.getTarget().getCXXABI().getKind()) { 63139f7f9bSDimitry Andric case TargetCXXABI::GenericAArch64: 64139f7f9bSDimitry Andric case TargetCXXABI::GenericARM: 65139f7f9bSDimitry Andric case TargetCXXABI::iOS: 6659d1ed5bSDimitry Andric case TargetCXXABI::iOS64: 67139f7f9bSDimitry Andric case TargetCXXABI::GenericItanium: 6859d1ed5bSDimitry Andric return CreateItaniumCXXABI(CGM); 69139f7f9bSDimitry Andric case TargetCXXABI::Microsoft: 7059d1ed5bSDimitry Andric return CreateMicrosoftCXXABI(CGM); 71e580952dSDimitry Andric } 72e580952dSDimitry Andric 73e580952dSDimitry Andric llvm_unreachable("invalid C++ ABI kind"); 74e580952dSDimitry Andric } 75e580952dSDimitry Andric 76f22ef01cSRoman Divacky CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 77284c1978SDimitry Andric llvm::Module &M, const llvm::DataLayout &TD, 7839d628a0SDimitry Andric DiagnosticsEngine &diags, 7939d628a0SDimitry Andric CoverageSourceInfo *CoverageInfo) 80284c1978SDimitry Andric : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M), 81284c1978SDimitry Andric Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()), 8259d1ed5bSDimitry Andric ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(nullptr), 8359d1ed5bSDimitry Andric TheTargetCodeGenInfo(nullptr), Types(*this), VTables(*this), 8459d1ed5bSDimitry Andric ObjCRuntime(nullptr), OpenCLRuntime(nullptr), OpenMPRuntime(nullptr), 8559d1ed5bSDimitry Andric CUDARuntime(nullptr), DebugInfo(nullptr), ARCData(nullptr), 8659d1ed5bSDimitry Andric NoObjCARCExceptionsMetadata(nullptr), RRData(nullptr), PGOReader(nullptr), 8759d1ed5bSDimitry Andric CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr), 8859d1ed5bSDimitry Andric NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr), 8959d1ed5bSDimitry Andric NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr), 9059d1ed5bSDimitry Andric BlockObjectDispose(nullptr), BlockDescriptorType(nullptr), 9159d1ed5bSDimitry Andric GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr), 9239d628a0SDimitry Andric LifetimeEndFn(nullptr), SanitizerMD(new SanitizerMetadata(*this)) { 93dff0c46cSDimitry Andric 94dff0c46cSDimitry Andric // Initialize the type cache. 95dff0c46cSDimitry Andric llvm::LLVMContext &LLVMContext = M.getContext(); 96dff0c46cSDimitry Andric VoidTy = llvm::Type::getVoidTy(LLVMContext); 97dff0c46cSDimitry Andric Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 98dff0c46cSDimitry Andric Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 99dff0c46cSDimitry Andric Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 100dff0c46cSDimitry Andric Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 101dff0c46cSDimitry Andric FloatTy = llvm::Type::getFloatTy(LLVMContext); 102dff0c46cSDimitry Andric DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 103dff0c46cSDimitry Andric PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 104dff0c46cSDimitry Andric PointerAlignInBytes = 105dff0c46cSDimitry Andric C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 106dff0c46cSDimitry Andric IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 107dff0c46cSDimitry Andric IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits); 108dff0c46cSDimitry Andric Int8PtrTy = Int8Ty->getPointerTo(0); 109dff0c46cSDimitry Andric Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 110dff0c46cSDimitry Andric 111139f7f9bSDimitry Andric RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 11239d628a0SDimitry Andric BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC(); 113139f7f9bSDimitry Andric 114dff0c46cSDimitry Andric if (LangOpts.ObjC1) 1153b0f4066SDimitry Andric createObjCRuntime(); 116dff0c46cSDimitry Andric if (LangOpts.OpenCL) 1176122f3e6SDimitry Andric createOpenCLRuntime(); 11859d1ed5bSDimitry Andric if (LangOpts.OpenMP) 11959d1ed5bSDimitry Andric createOpenMPRuntime(); 120dff0c46cSDimitry Andric if (LangOpts.CUDA) 1216122f3e6SDimitry Andric createCUDARuntime(); 122f22ef01cSRoman Divacky 1237ae0e2c9SDimitry Andric // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 12439d628a0SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 1257ae0e2c9SDimitry Andric (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 1267ae0e2c9SDimitry Andric TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(), 12759d1ed5bSDimitry Andric getCXXABI().getMangleContext()); 1282754fe60SDimitry Andric 1293b0f4066SDimitry Andric // If debug info or coverage generation is enabled, create the CGDebugInfo 1303b0f4066SDimitry Andric // object. 1313861d79fSDimitry Andric if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo || 1327ae0e2c9SDimitry Andric CodeGenOpts.EmitGcovArcs || 1333b0f4066SDimitry Andric CodeGenOpts.EmitGcovNotes) 1343b0f4066SDimitry Andric DebugInfo = new CGDebugInfo(*this); 1352754fe60SDimitry Andric 1362754fe60SDimitry Andric Block.GlobalUniqueCount = 0; 1372754fe60SDimitry Andric 138dff0c46cSDimitry Andric if (C.getLangOpts().ObjCAutoRefCount) 13917a519f9SDimitry Andric ARCData = new ARCEntrypoints(); 14017a519f9SDimitry Andric RRData = new RREntrypoints(); 14159d1ed5bSDimitry Andric 14259d1ed5bSDimitry Andric if (!CodeGenOpts.InstrProfileInput.empty()) { 14359d1ed5bSDimitry Andric if (std::error_code EC = llvm::IndexedInstrProfReader::create( 14459d1ed5bSDimitry Andric CodeGenOpts.InstrProfileInput, PGOReader)) { 14559d1ed5bSDimitry Andric unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 14659d1ed5bSDimitry Andric "Could not read profile: %0"); 14759d1ed5bSDimitry Andric getDiags().Report(DiagID) << EC.message(); 14859d1ed5bSDimitry Andric } 14959d1ed5bSDimitry Andric } 15039d628a0SDimitry Andric 15139d628a0SDimitry Andric // If coverage mapping generation is enabled, create the 15239d628a0SDimitry Andric // CoverageMappingModuleGen object. 15339d628a0SDimitry Andric if (CodeGenOpts.CoverageMapping) 15439d628a0SDimitry Andric CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 155f22ef01cSRoman Divacky } 156f22ef01cSRoman Divacky 157f22ef01cSRoman Divacky CodeGenModule::~CodeGenModule() { 1586122f3e6SDimitry Andric delete ObjCRuntime; 1596122f3e6SDimitry Andric delete OpenCLRuntime; 16059d1ed5bSDimitry Andric delete OpenMPRuntime; 1616122f3e6SDimitry Andric delete CUDARuntime; 1626122f3e6SDimitry Andric delete TheTargetCodeGenInfo; 1632754fe60SDimitry Andric delete TBAA; 164f22ef01cSRoman Divacky delete DebugInfo; 16517a519f9SDimitry Andric delete ARCData; 16617a519f9SDimitry Andric delete RRData; 167f22ef01cSRoman Divacky } 168f22ef01cSRoman Divacky 169f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() { 1707ae0e2c9SDimitry Andric // This is just isGNUFamily(), but we want to force implementors of 1717ae0e2c9SDimitry Andric // new ABIs to decide how best to do this. 1727ae0e2c9SDimitry Andric switch (LangOpts.ObjCRuntime.getKind()) { 1737ae0e2c9SDimitry Andric case ObjCRuntime::GNUstep: 1747ae0e2c9SDimitry Andric case ObjCRuntime::GCC: 1757ae0e2c9SDimitry Andric case ObjCRuntime::ObjFW: 1766122f3e6SDimitry Andric ObjCRuntime = CreateGNUObjCRuntime(*this); 1777ae0e2c9SDimitry Andric return; 1787ae0e2c9SDimitry Andric 1797ae0e2c9SDimitry Andric case ObjCRuntime::FragileMacOSX: 1807ae0e2c9SDimitry Andric case ObjCRuntime::MacOSX: 1817ae0e2c9SDimitry Andric case ObjCRuntime::iOS: 1826122f3e6SDimitry Andric ObjCRuntime = CreateMacObjCRuntime(*this); 1837ae0e2c9SDimitry Andric return; 1847ae0e2c9SDimitry Andric } 1857ae0e2c9SDimitry Andric llvm_unreachable("bad runtime kind"); 1866122f3e6SDimitry Andric } 1876122f3e6SDimitry Andric 1886122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() { 1896122f3e6SDimitry Andric OpenCLRuntime = new CGOpenCLRuntime(*this); 1906122f3e6SDimitry Andric } 1916122f3e6SDimitry Andric 19259d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() { 19359d1ed5bSDimitry Andric OpenMPRuntime = new CGOpenMPRuntime(*this); 19459d1ed5bSDimitry Andric } 19559d1ed5bSDimitry Andric 1966122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() { 1976122f3e6SDimitry Andric CUDARuntime = CreateNVCUDARuntime(*this); 198f22ef01cSRoman Divacky } 199f22ef01cSRoman Divacky 20039d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 20139d628a0SDimitry Andric Replacements[Name] = C; 20239d628a0SDimitry Andric } 20339d628a0SDimitry Andric 204f785676fSDimitry Andric void CodeGenModule::applyReplacements() { 205f785676fSDimitry Andric for (ReplacementsTy::iterator I = Replacements.begin(), 206f785676fSDimitry Andric E = Replacements.end(); 207f785676fSDimitry Andric I != E; ++I) { 208f785676fSDimitry Andric StringRef MangledName = I->first(); 209f785676fSDimitry Andric llvm::Constant *Replacement = I->second; 210f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 211f785676fSDimitry Andric if (!Entry) 212f785676fSDimitry Andric continue; 21359d1ed5bSDimitry Andric auto *OldF = cast<llvm::Function>(Entry); 21459d1ed5bSDimitry Andric auto *NewF = dyn_cast<llvm::Function>(Replacement); 215f785676fSDimitry Andric if (!NewF) { 21659d1ed5bSDimitry Andric if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 21759d1ed5bSDimitry Andric NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 21859d1ed5bSDimitry Andric } else { 21959d1ed5bSDimitry Andric auto *CE = cast<llvm::ConstantExpr>(Replacement); 220f785676fSDimitry Andric assert(CE->getOpcode() == llvm::Instruction::BitCast || 221f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::GetElementPtr); 222f785676fSDimitry Andric NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 223f785676fSDimitry Andric } 22459d1ed5bSDimitry Andric } 225f785676fSDimitry Andric 226f785676fSDimitry Andric // Replace old with new, but keep the old order. 227f785676fSDimitry Andric OldF->replaceAllUsesWith(Replacement); 228f785676fSDimitry Andric if (NewF) { 229f785676fSDimitry Andric NewF->removeFromParent(); 230f785676fSDimitry Andric OldF->getParent()->getFunctionList().insertAfter(OldF, NewF); 231f785676fSDimitry Andric } 232f785676fSDimitry Andric OldF->eraseFromParent(); 233f785676fSDimitry Andric } 234f785676fSDimitry Andric } 235f785676fSDimitry Andric 23659d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a 23759d1ed5bSDimitry Andric // linear structure. 23859d1ed5bSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) { 23959d1ed5bSDimitry Andric llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited; 24059d1ed5bSDimitry Andric const llvm::Constant *C = &GA; 24159d1ed5bSDimitry Andric for (;;) { 24259d1ed5bSDimitry Andric C = C->stripPointerCasts(); 24359d1ed5bSDimitry Andric if (auto *GO = dyn_cast<llvm::GlobalObject>(C)) 24459d1ed5bSDimitry Andric return GO; 24559d1ed5bSDimitry Andric // stripPointerCasts will not walk over weak aliases. 24659d1ed5bSDimitry Andric auto *GA2 = dyn_cast<llvm::GlobalAlias>(C); 24759d1ed5bSDimitry Andric if (!GA2) 24859d1ed5bSDimitry Andric return nullptr; 24939d628a0SDimitry Andric if (!Visited.insert(GA2).second) 25059d1ed5bSDimitry Andric return nullptr; 25159d1ed5bSDimitry Andric C = GA2->getAliasee(); 25259d1ed5bSDimitry Andric } 25359d1ed5bSDimitry Andric } 25459d1ed5bSDimitry Andric 255f785676fSDimitry Andric void CodeGenModule::checkAliases() { 25659d1ed5bSDimitry Andric // Check if the constructed aliases are well formed. It is really unfortunate 25759d1ed5bSDimitry Andric // that we have to do this in CodeGen, but we only construct mangled names 25859d1ed5bSDimitry Andric // and aliases during codegen. 259f785676fSDimitry Andric bool Error = false; 26059d1ed5bSDimitry Andric DiagnosticsEngine &Diags = getDiags(); 261f785676fSDimitry Andric for (std::vector<GlobalDecl>::iterator I = Aliases.begin(), 262f785676fSDimitry Andric E = Aliases.end(); I != E; ++I) { 263f785676fSDimitry Andric const GlobalDecl &GD = *I; 26459d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 265f785676fSDimitry Andric const AliasAttr *AA = D->getAttr<AliasAttr>(); 266f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 267f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 26859d1ed5bSDimitry Andric auto *Alias = cast<llvm::GlobalAlias>(Entry); 26959d1ed5bSDimitry Andric const llvm::GlobalValue *GV = getAliasedGlobal(*Alias); 27059d1ed5bSDimitry Andric if (!GV) { 271f785676fSDimitry Andric Error = true; 27259d1ed5bSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 27359d1ed5bSDimitry Andric } else if (GV->isDeclaration()) { 274f785676fSDimitry Andric Error = true; 27559d1ed5bSDimitry Andric Diags.Report(AA->getLocation(), diag::err_alias_to_undefined); 27659d1ed5bSDimitry Andric } 27759d1ed5bSDimitry Andric 27859d1ed5bSDimitry Andric llvm::Constant *Aliasee = Alias->getAliasee(); 27959d1ed5bSDimitry Andric llvm::GlobalValue *AliaseeGV; 28059d1ed5bSDimitry Andric if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 28159d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 28259d1ed5bSDimitry Andric else 28359d1ed5bSDimitry Andric AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 28459d1ed5bSDimitry Andric 28559d1ed5bSDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 28659d1ed5bSDimitry Andric StringRef AliasSection = SA->getName(); 28759d1ed5bSDimitry Andric if (AliasSection != AliaseeGV->getSection()) 28859d1ed5bSDimitry Andric Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 28959d1ed5bSDimitry Andric << AliasSection; 29059d1ed5bSDimitry Andric } 29159d1ed5bSDimitry Andric 29259d1ed5bSDimitry Andric // We have to handle alias to weak aliases in here. LLVM itself disallows 29359d1ed5bSDimitry Andric // this since the object semantics would not match the IL one. For 29459d1ed5bSDimitry Andric // compatibility with gcc we implement it by just pointing the alias 29559d1ed5bSDimitry Andric // to its aliasee's aliasee. We also warn, since the user is probably 29659d1ed5bSDimitry Andric // expecting the link to be weak. 29759d1ed5bSDimitry Andric if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) { 29859d1ed5bSDimitry Andric if (GA->mayBeOverridden()) { 29959d1ed5bSDimitry Andric Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias) 30059d1ed5bSDimitry Andric << GV->getName() << GA->getName(); 30159d1ed5bSDimitry Andric Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 30259d1ed5bSDimitry Andric GA->getAliasee(), Alias->getType()); 30359d1ed5bSDimitry Andric Alias->setAliasee(Aliasee); 30459d1ed5bSDimitry Andric } 305f785676fSDimitry Andric } 306f785676fSDimitry Andric } 307f785676fSDimitry Andric if (!Error) 308f785676fSDimitry Andric return; 309f785676fSDimitry Andric 310f785676fSDimitry Andric for (std::vector<GlobalDecl>::iterator I = Aliases.begin(), 311f785676fSDimitry Andric E = Aliases.end(); I != E; ++I) { 312f785676fSDimitry Andric const GlobalDecl &GD = *I; 313f785676fSDimitry Andric StringRef MangledName = getMangledName(GD); 314f785676fSDimitry Andric llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 31559d1ed5bSDimitry Andric auto *Alias = cast<llvm::GlobalAlias>(Entry); 316f785676fSDimitry Andric Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 317f785676fSDimitry Andric Alias->eraseFromParent(); 318f785676fSDimitry Andric } 319f785676fSDimitry Andric } 320f785676fSDimitry Andric 32159d1ed5bSDimitry Andric void CodeGenModule::clear() { 32259d1ed5bSDimitry Andric DeferredDeclsToEmit.clear(); 32359d1ed5bSDimitry Andric } 32459d1ed5bSDimitry Andric 32559d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 32659d1ed5bSDimitry Andric StringRef MainFile) { 32759d1ed5bSDimitry Andric if (!hasDiagnostics()) 32859d1ed5bSDimitry Andric return; 32959d1ed5bSDimitry Andric if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 33059d1ed5bSDimitry Andric if (MainFile.empty()) 33159d1ed5bSDimitry Andric MainFile = "<stdin>"; 33259d1ed5bSDimitry Andric Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 33359d1ed5bSDimitry Andric } else 33459d1ed5bSDimitry Andric Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing 33559d1ed5bSDimitry Andric << Mismatched; 33659d1ed5bSDimitry Andric } 33759d1ed5bSDimitry Andric 338f22ef01cSRoman Divacky void CodeGenModule::Release() { 339f22ef01cSRoman Divacky EmitDeferred(); 340f785676fSDimitry Andric applyReplacements(); 341f785676fSDimitry Andric checkAliases(); 342f22ef01cSRoman Divacky EmitCXXGlobalInitFunc(); 343f22ef01cSRoman Divacky EmitCXXGlobalDtorFunc(); 344284c1978SDimitry Andric EmitCXXThreadLocalInitFunc(); 3456122f3e6SDimitry Andric if (ObjCRuntime) 3466122f3e6SDimitry Andric if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 347f22ef01cSRoman Divacky AddGlobalCtor(ObjCInitFunction); 34859d1ed5bSDimitry Andric if (PGOReader && PGOStats.hasDiagnostics()) 34959d1ed5bSDimitry Andric PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 350f22ef01cSRoman Divacky EmitCtorList(GlobalCtors, "llvm.global_ctors"); 351f22ef01cSRoman Divacky EmitCtorList(GlobalDtors, "llvm.global_dtors"); 3526122f3e6SDimitry Andric EmitGlobalAnnotations(); 353284c1978SDimitry Andric EmitStaticExternCAliases(); 35439d628a0SDimitry Andric EmitDeferredUnusedCoverageMappings(); 35539d628a0SDimitry Andric if (CoverageMapping) 35639d628a0SDimitry Andric CoverageMapping->emit(); 35759d1ed5bSDimitry Andric emitLLVMUsed(); 358ffd1746dSEd Schouten 359f785676fSDimitry Andric if (CodeGenOpts.Autolink && 360f785676fSDimitry Andric (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 361139f7f9bSDimitry Andric EmitModuleLinkOptions(); 362139f7f9bSDimitry Andric } 363f785676fSDimitry Andric if (CodeGenOpts.DwarfVersion) 364f785676fSDimitry Andric // We actually want the latest version when there are conflicts. 365f785676fSDimitry Andric // We can change from Warning to Latest if such mode is supported. 366f785676fSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version", 367f785676fSDimitry Andric CodeGenOpts.DwarfVersion); 368f785676fSDimitry Andric if (DebugInfo) 36959d1ed5bSDimitry Andric // We support a single version in the linked module. The LLVM 37059d1ed5bSDimitry Andric // parser will drop debug info with a different version number 37159d1ed5bSDimitry Andric // (and warn about it, too). 37259d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 373f785676fSDimitry Andric llvm::DEBUG_METADATA_VERSION); 374139f7f9bSDimitry Andric 37559d1ed5bSDimitry Andric // We need to record the widths of enums and wchar_t, so that we can generate 37659d1ed5bSDimitry Andric // the correct build attributes in the ARM backend. 37759d1ed5bSDimitry Andric llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 37859d1ed5bSDimitry Andric if ( Arch == llvm::Triple::arm 37959d1ed5bSDimitry Andric || Arch == llvm::Triple::armeb 38059d1ed5bSDimitry Andric || Arch == llvm::Triple::thumb 38159d1ed5bSDimitry Andric || Arch == llvm::Triple::thumbeb) { 38259d1ed5bSDimitry Andric // Width of wchar_t in bytes 38359d1ed5bSDimitry Andric uint64_t WCharWidth = 38459d1ed5bSDimitry Andric Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 38559d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 38659d1ed5bSDimitry Andric 38759d1ed5bSDimitry Andric // The minimum width of an enum in bytes 38859d1ed5bSDimitry Andric uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 38959d1ed5bSDimitry Andric getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 39059d1ed5bSDimitry Andric } 39159d1ed5bSDimitry Andric 39239d628a0SDimitry Andric if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 39339d628a0SDimitry Andric llvm::PICLevel::Level PL = llvm::PICLevel::Default; 39439d628a0SDimitry Andric switch (PLevel) { 39539d628a0SDimitry Andric case 0: break; 39639d628a0SDimitry Andric case 1: PL = llvm::PICLevel::Small; break; 39739d628a0SDimitry Andric case 2: PL = llvm::PICLevel::Large; break; 39839d628a0SDimitry Andric default: llvm_unreachable("Invalid PIC Level"); 39939d628a0SDimitry Andric } 40039d628a0SDimitry Andric 40139d628a0SDimitry Andric getModule().setPICLevel(PL); 40239d628a0SDimitry Andric } 40339d628a0SDimitry Andric 4042754fe60SDimitry Andric SimplifyPersonality(); 4052754fe60SDimitry Andric 406ffd1746dSEd Schouten if (getCodeGenOpts().EmitDeclMetadata) 407ffd1746dSEd Schouten EmitDeclMetadata(); 408bd5abe19SDimitry Andric 409bd5abe19SDimitry Andric if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 410bd5abe19SDimitry Andric EmitCoverageFile(); 4116122f3e6SDimitry Andric 4126122f3e6SDimitry Andric if (DebugInfo) 4136122f3e6SDimitry Andric DebugInfo->finalize(); 414f785676fSDimitry Andric 415f785676fSDimitry Andric EmitVersionIdentMetadata(); 41659d1ed5bSDimitry Andric 41759d1ed5bSDimitry Andric EmitTargetMetadata(); 418f22ef01cSRoman Divacky } 419f22ef01cSRoman Divacky 4203b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 4213b0f4066SDimitry Andric // Make sure that this type is translated. 4223b0f4066SDimitry Andric Types.UpdateCompletedType(TD); 4233b0f4066SDimitry Andric } 4243b0f4066SDimitry Andric 4252754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 4262754fe60SDimitry Andric if (!TBAA) 42759d1ed5bSDimitry Andric return nullptr; 4282754fe60SDimitry Andric return TBAA->getTBAAInfo(QTy); 4292754fe60SDimitry Andric } 4302754fe60SDimitry Andric 431dff0c46cSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 432dff0c46cSDimitry Andric if (!TBAA) 43359d1ed5bSDimitry Andric return nullptr; 434dff0c46cSDimitry Andric return TBAA->getTBAAInfoForVTablePtr(); 435dff0c46cSDimitry Andric } 436dff0c46cSDimitry Andric 4373861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 4383861d79fSDimitry Andric if (!TBAA) 43959d1ed5bSDimitry Andric return nullptr; 4403861d79fSDimitry Andric return TBAA->getTBAAStructInfo(QTy); 4413861d79fSDimitry Andric } 4423861d79fSDimitry Andric 443139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) { 444139f7f9bSDimitry Andric if (!TBAA) 44559d1ed5bSDimitry Andric return nullptr; 446139f7f9bSDimitry Andric return TBAA->getTBAAStructTypeInfo(QTy); 447139f7f9bSDimitry Andric } 448139f7f9bSDimitry Andric 449139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy, 450139f7f9bSDimitry Andric llvm::MDNode *AccessN, 451139f7f9bSDimitry Andric uint64_t O) { 452139f7f9bSDimitry Andric if (!TBAA) 45359d1ed5bSDimitry Andric return nullptr; 454139f7f9bSDimitry Andric return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O); 455139f7f9bSDimitry Andric } 456139f7f9bSDimitry Andric 457f785676fSDimitry Andric /// Decorate the instruction with a TBAA tag. For both scalar TBAA 458f785676fSDimitry Andric /// and struct-path aware TBAA, the tag has the same format: 459f785676fSDimitry Andric /// base type, access type and offset. 460284c1978SDimitry Andric /// When ConvertTypeToTag is true, we create a tag based on the scalar type. 4612754fe60SDimitry Andric void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst, 462284c1978SDimitry Andric llvm::MDNode *TBAAInfo, 463284c1978SDimitry Andric bool ConvertTypeToTag) { 464f785676fSDimitry Andric if (ConvertTypeToTag && TBAA) 465284c1978SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, 466284c1978SDimitry Andric TBAA->getTBAAScalarTagInfo(TBAAInfo)); 467284c1978SDimitry Andric else 4682754fe60SDimitry Andric Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 4692754fe60SDimitry Andric } 4702754fe60SDimitry Andric 47159d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) { 47259d1ed5bSDimitry Andric unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 47359d1ed5bSDimitry Andric getDiags().Report(Context.getFullLoc(loc), diagID) << message; 474f22ef01cSRoman Divacky } 475f22ef01cSRoman Divacky 476f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 477f22ef01cSRoman Divacky /// specified stmt yet. 478f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 4796122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 480f22ef01cSRoman Divacky "cannot compile this %0 yet"); 481f22ef01cSRoman Divacky std::string Msg = Type; 482f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 483f22ef01cSRoman Divacky << Msg << S->getSourceRange(); 484f22ef01cSRoman Divacky } 485f22ef01cSRoman Divacky 486f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the 487f22ef01cSRoman Divacky /// specified decl yet. 488f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 4896122f3e6SDimitry Andric unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 490f22ef01cSRoman Divacky "cannot compile this %0 yet"); 491f22ef01cSRoman Divacky std::string Msg = Type; 492f22ef01cSRoman Divacky getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 493f22ef01cSRoman Divacky } 494f22ef01cSRoman Divacky 49517a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 49617a519f9SDimitry Andric return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 49717a519f9SDimitry Andric } 49817a519f9SDimitry Andric 499f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 5002754fe60SDimitry Andric const NamedDecl *D) const { 501f22ef01cSRoman Divacky // Internal definitions always have default visibility. 502f22ef01cSRoman Divacky if (GV->hasLocalLinkage()) { 503f22ef01cSRoman Divacky GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 504f22ef01cSRoman Divacky return; 505f22ef01cSRoman Divacky } 506f22ef01cSRoman Divacky 5072754fe60SDimitry Andric // Set visibility for definitions. 508139f7f9bSDimitry Andric LinkageInfo LV = D->getLinkageAndVisibility(); 509139f7f9bSDimitry Andric if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 510139f7f9bSDimitry Andric GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 511f22ef01cSRoman Divacky } 512f22ef01cSRoman Divacky 5137ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 5147ae0e2c9SDimitry Andric return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 5157ae0e2c9SDimitry Andric .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 5167ae0e2c9SDimitry Andric .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 5177ae0e2c9SDimitry Andric .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 5187ae0e2c9SDimitry Andric .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 5197ae0e2c9SDimitry Andric } 5207ae0e2c9SDimitry Andric 5217ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel( 5227ae0e2c9SDimitry Andric CodeGenOptions::TLSModel M) { 5237ae0e2c9SDimitry Andric switch (M) { 5247ae0e2c9SDimitry Andric case CodeGenOptions::GeneralDynamicTLSModel: 5257ae0e2c9SDimitry Andric return llvm::GlobalVariable::GeneralDynamicTLSModel; 5267ae0e2c9SDimitry Andric case CodeGenOptions::LocalDynamicTLSModel: 5277ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalDynamicTLSModel; 5287ae0e2c9SDimitry Andric case CodeGenOptions::InitialExecTLSModel: 5297ae0e2c9SDimitry Andric return llvm::GlobalVariable::InitialExecTLSModel; 5307ae0e2c9SDimitry Andric case CodeGenOptions::LocalExecTLSModel: 5317ae0e2c9SDimitry Andric return llvm::GlobalVariable::LocalExecTLSModel; 5327ae0e2c9SDimitry Andric } 5337ae0e2c9SDimitry Andric llvm_unreachable("Invalid TLS model!"); 5347ae0e2c9SDimitry Andric } 5357ae0e2c9SDimitry Andric 53639d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 537284c1978SDimitry Andric assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 5387ae0e2c9SDimitry Andric 53939d628a0SDimitry Andric llvm::GlobalValue::ThreadLocalMode TLM; 5403861d79fSDimitry Andric TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel()); 5417ae0e2c9SDimitry Andric 5427ae0e2c9SDimitry Andric // Override the TLS model if it is explicitly specified. 54359d1ed5bSDimitry Andric if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 5447ae0e2c9SDimitry Andric TLM = GetLLVMTLSModel(Attr->getModel()); 5457ae0e2c9SDimitry Andric } 5467ae0e2c9SDimitry Andric 5477ae0e2c9SDimitry Andric GV->setThreadLocalMode(TLM); 5487ae0e2c9SDimitry Andric } 5497ae0e2c9SDimitry Andric 5506122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 55159d1ed5bSDimitry Andric StringRef &FoundStr = MangledDeclNames[GD.getCanonicalDecl()]; 55259d1ed5bSDimitry Andric if (!FoundStr.empty()) 55359d1ed5bSDimitry Andric return FoundStr; 554f22ef01cSRoman Divacky 55559d1ed5bSDimitry Andric const auto *ND = cast<NamedDecl>(GD.getDecl()); 556dff0c46cSDimitry Andric SmallString<256> Buffer; 55759d1ed5bSDimitry Andric StringRef Str; 55859d1ed5bSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 5592754fe60SDimitry Andric llvm::raw_svector_ostream Out(Buffer); 56059d1ed5bSDimitry Andric if (const auto *D = dyn_cast<CXXConstructorDecl>(ND)) 5612754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 56259d1ed5bSDimitry Andric else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND)) 5632754fe60SDimitry Andric getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 564ffd1746dSEd Schouten else 5652754fe60SDimitry Andric getCXXABI().getMangleContext().mangleName(ND, Out); 56659d1ed5bSDimitry Andric Str = Out.str(); 56759d1ed5bSDimitry Andric } else { 56859d1ed5bSDimitry Andric IdentifierInfo *II = ND->getIdentifier(); 56959d1ed5bSDimitry Andric assert(II && "Attempt to mangle unnamed decl."); 57059d1ed5bSDimitry Andric Str = II->getName(); 571ffd1746dSEd Schouten } 572ffd1746dSEd Schouten 57339d628a0SDimitry Andric // Keep the first result in the case of a mangling collision. 57439d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Str, GD)); 57539d628a0SDimitry Andric return FoundStr = Result.first->first(); 57659d1ed5bSDimitry Andric } 57759d1ed5bSDimitry Andric 57859d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 579ffd1746dSEd Schouten const BlockDecl *BD) { 5802754fe60SDimitry Andric MangleContext &MangleCtx = getCXXABI().getMangleContext(); 5812754fe60SDimitry Andric const Decl *D = GD.getDecl(); 58259d1ed5bSDimitry Andric 58359d1ed5bSDimitry Andric SmallString<256> Buffer; 58459d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(Buffer); 58559d1ed5bSDimitry Andric if (!D) 5867ae0e2c9SDimitry Andric MangleCtx.mangleGlobalBlock(BD, 5877ae0e2c9SDimitry Andric dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 58859d1ed5bSDimitry Andric else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 5892754fe60SDimitry Andric MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 59059d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 5912754fe60SDimitry Andric MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 5922754fe60SDimitry Andric else 5932754fe60SDimitry Andric MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 59459d1ed5bSDimitry Andric 59539d628a0SDimitry Andric auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 59639d628a0SDimitry Andric return Result.first->first(); 597f22ef01cSRoman Divacky } 598f22ef01cSRoman Divacky 5996122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 600f22ef01cSRoman Divacky return getModule().getNamedValue(Name); 601f22ef01cSRoman Divacky } 602f22ef01cSRoman Divacky 603f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before 604f22ef01cSRoman Divacky /// main() runs. 60559d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 60659d1ed5bSDimitry Andric llvm::Constant *AssociatedData) { 607f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 60859d1ed5bSDimitry Andric GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 609f22ef01cSRoman Divacky } 610f22ef01cSRoman Divacky 611f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called 612f22ef01cSRoman Divacky /// when the module is unloaded. 613f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) { 614f22ef01cSRoman Divacky // FIXME: Type coercion of void()* types. 61559d1ed5bSDimitry Andric GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 616f22ef01cSRoman Divacky } 617f22ef01cSRoman Divacky 618f22ef01cSRoman Divacky void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 619f22ef01cSRoman Divacky // Ctor function type is void()*. 620bd5abe19SDimitry Andric llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 621f22ef01cSRoman Divacky llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 622f22ef01cSRoman Divacky 62359d1ed5bSDimitry Andric // Get the type of a ctor entry, { i32, void ()*, i8* }. 62459d1ed5bSDimitry Andric llvm::StructType *CtorStructTy = llvm::StructType::get( 62539d628a0SDimitry Andric Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr); 626f22ef01cSRoman Divacky 627f22ef01cSRoman Divacky // Construct the constructor and destructor arrays. 628dff0c46cSDimitry Andric SmallVector<llvm::Constant*, 8> Ctors; 629f22ef01cSRoman Divacky for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 630dff0c46cSDimitry Andric llvm::Constant *S[] = { 63159d1ed5bSDimitry Andric llvm::ConstantInt::get(Int32Ty, I->Priority, false), 63259d1ed5bSDimitry Andric llvm::ConstantExpr::getBitCast(I->Initializer, CtorPFTy), 63359d1ed5bSDimitry Andric (I->AssociatedData 63459d1ed5bSDimitry Andric ? llvm::ConstantExpr::getBitCast(I->AssociatedData, VoidPtrTy) 63559d1ed5bSDimitry Andric : llvm::Constant::getNullValue(VoidPtrTy)) 636dff0c46cSDimitry Andric }; 637f22ef01cSRoman Divacky Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 638f22ef01cSRoman Divacky } 639f22ef01cSRoman Divacky 640f22ef01cSRoman Divacky if (!Ctors.empty()) { 641f22ef01cSRoman Divacky llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 642f22ef01cSRoman Divacky new llvm::GlobalVariable(TheModule, AT, false, 643f22ef01cSRoman Divacky llvm::GlobalValue::AppendingLinkage, 644f22ef01cSRoman Divacky llvm::ConstantArray::get(AT, Ctors), 645f22ef01cSRoman Divacky GlobalName); 646f22ef01cSRoman Divacky } 647f22ef01cSRoman Divacky } 648f22ef01cSRoman Divacky 649f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes 650f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 65159d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 652f785676fSDimitry Andric 653e580952dSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 654f22ef01cSRoman Divacky 65559d1ed5bSDimitry Andric if (isa<CXXDestructorDecl>(D) && 65659d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 65759d1ed5bSDimitry Andric GD.getDtorType())) { 65859d1ed5bSDimitry Andric // Destructor variants in the Microsoft C++ ABI are always internal or 65959d1ed5bSDimitry Andric // linkonce_odr thunks emitted on an as-needed basis. 66059d1ed5bSDimitry Andric return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage 66159d1ed5bSDimitry Andric : llvm::GlobalValue::LinkOnceODRLinkage; 662f22ef01cSRoman Divacky } 663f22ef01cSRoman Divacky 66459d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false); 66559d1ed5bSDimitry Andric } 666f22ef01cSRoman Divacky 66759d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D, 66859d1ed5bSDimitry Andric llvm::Function *F) { 66959d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 670f22ef01cSRoman Divacky } 671f22ef01cSRoman Divacky 672f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 673f22ef01cSRoman Divacky const CGFunctionInfo &Info, 674f22ef01cSRoman Divacky llvm::Function *F) { 675f22ef01cSRoman Divacky unsigned CallingConv; 676f22ef01cSRoman Divacky AttributeListType AttributeList; 677139f7f9bSDimitry Andric ConstructAttributeList(Info, D, AttributeList, CallingConv, false); 678139f7f9bSDimitry Andric F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList)); 679f22ef01cSRoman Divacky F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 680f22ef01cSRoman Divacky } 681f22ef01cSRoman Divacky 6826122f3e6SDimitry Andric /// Determines whether the language options require us to model 6836122f3e6SDimitry Andric /// unwind exceptions. We treat -fexceptions as mandating this 6846122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions 6856122f3e6SDimitry Andric /// enabled. This means, for example, that C with -fexceptions 6866122f3e6SDimitry Andric /// enables this. 687dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) { 6886122f3e6SDimitry Andric // If exceptions are completely disabled, obviously this is false. 689dff0c46cSDimitry Andric if (!LangOpts.Exceptions) return false; 6906122f3e6SDimitry Andric 6916122f3e6SDimitry Andric // If C++ exceptions are enabled, this is true. 692dff0c46cSDimitry Andric if (LangOpts.CXXExceptions) return true; 6936122f3e6SDimitry Andric 6946122f3e6SDimitry Andric // If ObjC exceptions are enabled, this depends on the ABI. 695dff0c46cSDimitry Andric if (LangOpts.ObjCExceptions) { 6967ae0e2c9SDimitry Andric return LangOpts.ObjCRuntime.hasUnwindExceptions(); 6976122f3e6SDimitry Andric } 6986122f3e6SDimitry Andric 6996122f3e6SDimitry Andric return true; 7006122f3e6SDimitry Andric } 7016122f3e6SDimitry Andric 702f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 703f22ef01cSRoman Divacky llvm::Function *F) { 704f785676fSDimitry Andric llvm::AttrBuilder B; 705f785676fSDimitry Andric 706bd5abe19SDimitry Andric if (CodeGenOpts.UnwindTables) 707f785676fSDimitry Andric B.addAttribute(llvm::Attribute::UWTable); 708bd5abe19SDimitry Andric 709dff0c46cSDimitry Andric if (!hasUnwindExceptions(LangOpts)) 710f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoUnwind); 711f22ef01cSRoman Divacky 7126122f3e6SDimitry Andric if (D->hasAttr<NakedAttr>()) { 7136122f3e6SDimitry Andric // Naked implies noinline: we should not be inlining such functions. 714f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Naked); 715f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 71659d1ed5bSDimitry Andric } else if (D->hasAttr<NoDuplicateAttr>()) { 71759d1ed5bSDimitry Andric B.addAttribute(llvm::Attribute::NoDuplicate); 718f785676fSDimitry Andric } else if (D->hasAttr<NoInlineAttr>()) { 719f785676fSDimitry Andric B.addAttribute(llvm::Attribute::NoInline); 72059d1ed5bSDimitry Andric } else if (D->hasAttr<AlwaysInlineAttr>() && 721f785676fSDimitry Andric !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex, 722f785676fSDimitry Andric llvm::Attribute::NoInline)) { 723f785676fSDimitry Andric // (noinline wins over always_inline, and we can't specify both in IR) 724f785676fSDimitry Andric B.addAttribute(llvm::Attribute::AlwaysInline); 7256122f3e6SDimitry Andric } 7262754fe60SDimitry Andric 727f785676fSDimitry Andric if (D->hasAttr<ColdAttr>()) { 72839d628a0SDimitry Andric if (!D->hasAttr<OptimizeNoneAttr>()) 729f785676fSDimitry Andric B.addAttribute(llvm::Attribute::OptimizeForSize); 730f785676fSDimitry Andric B.addAttribute(llvm::Attribute::Cold); 731f785676fSDimitry Andric } 7323861d79fSDimitry Andric 7333861d79fSDimitry Andric if (D->hasAttr<MinSizeAttr>()) 734f785676fSDimitry Andric B.addAttribute(llvm::Attribute::MinSize); 735f22ef01cSRoman Divacky 7363861d79fSDimitry Andric if (LangOpts.getStackProtector() == LangOptions::SSPOn) 737f785676fSDimitry Andric B.addAttribute(llvm::Attribute::StackProtect); 73859d1ed5bSDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 73959d1ed5bSDimitry Andric B.addAttribute(llvm::Attribute::StackProtectStrong); 7403861d79fSDimitry Andric else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 741f785676fSDimitry Andric B.addAttribute(llvm::Attribute::StackProtectReq); 7423861d79fSDimitry Andric 743139f7f9bSDimitry Andric // Add sanitizer attributes if function is not blacklisted. 74439d628a0SDimitry Andric if (!isInSanitizerBlacklist(F, D->getLocation())) { 745139f7f9bSDimitry Andric // When AddressSanitizer is enabled, set SanitizeAddress attribute 746139f7f9bSDimitry Andric // unless __attribute__((no_sanitize_address)) is used. 74739d628a0SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Address) && 74839d628a0SDimitry Andric !D->hasAttr<NoSanitizeAddressAttr>()) 749f785676fSDimitry Andric B.addAttribute(llvm::Attribute::SanitizeAddress); 750139f7f9bSDimitry Andric // Same for ThreadSanitizer and __attribute__((no_sanitize_thread)) 75139d628a0SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Thread) && 75239d628a0SDimitry Andric !D->hasAttr<NoSanitizeThreadAttr>()) 753f785676fSDimitry Andric B.addAttribute(llvm::Attribute::SanitizeThread); 754139f7f9bSDimitry Andric // Same for MemorySanitizer and __attribute__((no_sanitize_memory)) 75539d628a0SDimitry Andric if (LangOpts.Sanitize.has(SanitizerKind::Memory) && 75639d628a0SDimitry Andric !D->hasAttr<NoSanitizeMemoryAttr>()) 757f785676fSDimitry Andric B.addAttribute(llvm::Attribute::SanitizeMemory); 758dff0c46cSDimitry Andric } 759dff0c46cSDimitry Andric 760f785676fSDimitry Andric F->addAttributes(llvm::AttributeSet::FunctionIndex, 761f785676fSDimitry Andric llvm::AttributeSet::get( 762f785676fSDimitry Andric F->getContext(), llvm::AttributeSet::FunctionIndex, B)); 763f785676fSDimitry Andric 76439d628a0SDimitry Andric if (D->hasAttr<OptimizeNoneAttr>()) { 76539d628a0SDimitry Andric // OptimizeNone implies noinline; we should not be inlining such functions. 76639d628a0SDimitry Andric F->addFnAttr(llvm::Attribute::OptimizeNone); 76739d628a0SDimitry Andric F->addFnAttr(llvm::Attribute::NoInline); 76839d628a0SDimitry Andric 76939d628a0SDimitry Andric // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline. 77039d628a0SDimitry Andric assert(!F->hasFnAttribute(llvm::Attribute::OptimizeForSize) && 77139d628a0SDimitry Andric "OptimizeNone and OptimizeForSize on same function!"); 77239d628a0SDimitry Andric assert(!F->hasFnAttribute(llvm::Attribute::MinSize) && 77339d628a0SDimitry Andric "OptimizeNone and MinSize on same function!"); 77439d628a0SDimitry Andric assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 77539d628a0SDimitry Andric "OptimizeNone and AlwaysInline on same function!"); 77639d628a0SDimitry Andric 77739d628a0SDimitry Andric // Attribute 'inlinehint' has no effect on 'optnone' functions. 77839d628a0SDimitry Andric // Explicitly remove it from the set of function attributes. 77939d628a0SDimitry Andric F->removeFnAttr(llvm::Attribute::InlineHint); 78039d628a0SDimitry Andric } 78139d628a0SDimitry Andric 782f785676fSDimitry Andric if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 783f785676fSDimitry Andric F->setUnnamedAddr(true); 78459d1ed5bSDimitry Andric else if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) 785f785676fSDimitry Andric if (MD->isVirtual()) 786f785676fSDimitry Andric F->setUnnamedAddr(true); 787f785676fSDimitry Andric 788e580952dSDimitry Andric unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 789e580952dSDimitry Andric if (alignment) 790e580952dSDimitry Andric F->setAlignment(alignment); 791e580952dSDimitry Andric 792f22ef01cSRoman Divacky // C++ ABI requires 2-byte alignment for member functions. 793f22ef01cSRoman Divacky if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 794f22ef01cSRoman Divacky F->setAlignment(2); 795f22ef01cSRoman Divacky } 796f22ef01cSRoman Divacky 797f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D, 798f22ef01cSRoman Divacky llvm::GlobalValue *GV) { 79959d1ed5bSDimitry Andric if (const auto *ND = dyn_cast<NamedDecl>(D)) 8002754fe60SDimitry Andric setGlobalVisibility(GV, ND); 8012754fe60SDimitry Andric else 8022754fe60SDimitry Andric GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 803f22ef01cSRoman Divacky 804f22ef01cSRoman Divacky if (D->hasAttr<UsedAttr>()) 80559d1ed5bSDimitry Andric addUsedGlobal(GV); 80659d1ed5bSDimitry Andric } 80759d1ed5bSDimitry Andric 80839d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D, 80939d628a0SDimitry Andric llvm::GlobalValue *GV) { 81039d628a0SDimitry Andric SetCommonAttributes(D, GV); 81139d628a0SDimitry Andric 81239d628a0SDimitry Andric // Process the dllexport attribute based on whether the original definition 81339d628a0SDimitry Andric // (not necessarily the aliasee) was exported. 81439d628a0SDimitry Andric if (D->hasAttr<DLLExportAttr>()) 81539d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 81639d628a0SDimitry Andric } 81739d628a0SDimitry Andric 81859d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D, 81959d1ed5bSDimitry Andric llvm::GlobalObject *GO) { 82059d1ed5bSDimitry Andric SetCommonAttributes(D, GO); 821f22ef01cSRoman Divacky 822f22ef01cSRoman Divacky if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 82359d1ed5bSDimitry Andric GO->setSection(SA->getName()); 824f22ef01cSRoman Divacky 82559d1ed5bSDimitry Andric getTargetCodeGenInfo().SetTargetAttributes(D, GO, *this); 826f22ef01cSRoman Divacky } 827f22ef01cSRoman Divacky 828f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 829f22ef01cSRoman Divacky llvm::Function *F, 830f22ef01cSRoman Divacky const CGFunctionInfo &FI) { 831f22ef01cSRoman Divacky SetLLVMFunctionAttributes(D, FI, F); 832f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, F); 833f22ef01cSRoman Divacky 834f22ef01cSRoman Divacky F->setLinkage(llvm::Function::InternalLinkage); 835f22ef01cSRoman Divacky 83659d1ed5bSDimitry Andric setNonAliasAttributes(D, F); 83759d1ed5bSDimitry Andric } 83859d1ed5bSDimitry Andric 83959d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV, 84059d1ed5bSDimitry Andric const NamedDecl *ND) { 84159d1ed5bSDimitry Andric // Set linkage and visibility in case we never see a definition. 84259d1ed5bSDimitry Andric LinkageInfo LV = ND->getLinkageAndVisibility(); 84359d1ed5bSDimitry Andric if (LV.getLinkage() != ExternalLinkage) { 84459d1ed5bSDimitry Andric // Don't set internal linkage on declarations. 84559d1ed5bSDimitry Andric } else { 84659d1ed5bSDimitry Andric if (ND->hasAttr<DLLImportAttr>()) { 84759d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 84859d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 84959d1ed5bSDimitry Andric } else if (ND->hasAttr<DLLExportAttr>()) { 85059d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 85159d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 85259d1ed5bSDimitry Andric } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) { 85359d1ed5bSDimitry Andric // "extern_weak" is overloaded in LLVM; we probably should have 85459d1ed5bSDimitry Andric // separate linkage types for this. 85559d1ed5bSDimitry Andric GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 85659d1ed5bSDimitry Andric } 85759d1ed5bSDimitry Andric 85859d1ed5bSDimitry Andric // Set visibility on a declaration only if it's explicit. 85959d1ed5bSDimitry Andric if (LV.isVisibilityExplicit()) 86059d1ed5bSDimitry Andric GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility())); 86159d1ed5bSDimitry Andric } 862f22ef01cSRoman Divacky } 863f22ef01cSRoman Divacky 86439d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 86539d628a0SDimitry Andric bool IsIncompleteFunction, 86639d628a0SDimitry Andric bool IsThunk) { 8673b0f4066SDimitry Andric if (unsigned IID = F->getIntrinsicID()) { 8683b0f4066SDimitry Andric // If this is an intrinsic function, set the function's attributes 8693b0f4066SDimitry Andric // to the intrinsic's attributes. 8703861d79fSDimitry Andric F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), 8713861d79fSDimitry Andric (llvm::Intrinsic::ID)IID)); 8723b0f4066SDimitry Andric return; 8733b0f4066SDimitry Andric } 8743b0f4066SDimitry Andric 87559d1ed5bSDimitry Andric const auto *FD = cast<FunctionDecl>(GD.getDecl()); 876f22ef01cSRoman Divacky 877f22ef01cSRoman Divacky if (!IsIncompleteFunction) 878dff0c46cSDimitry Andric SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 879f22ef01cSRoman Divacky 88059d1ed5bSDimitry Andric // Add the Returned attribute for "this", except for iOS 5 and earlier 88159d1ed5bSDimitry Andric // where substantial code, including the libstdc++ dylib, was compiled with 88259d1ed5bSDimitry Andric // GCC and does not actually return "this". 88339d628a0SDimitry Andric if (!IsThunk && getCXXABI().HasThisReturn(GD) && 88459d1ed5bSDimitry Andric !(getTarget().getTriple().isiOS() && 88559d1ed5bSDimitry Andric getTarget().getTriple().isOSVersionLT(6))) { 886f785676fSDimitry Andric assert(!F->arg_empty() && 887f785676fSDimitry Andric F->arg_begin()->getType() 888f785676fSDimitry Andric ->canLosslesslyBitCastTo(F->getReturnType()) && 889f785676fSDimitry Andric "unexpected this return"); 890f785676fSDimitry Andric F->addAttribute(1, llvm::Attribute::Returned); 891f785676fSDimitry Andric } 892f785676fSDimitry Andric 893f22ef01cSRoman Divacky // Only a few attributes are set on declarations; these may later be 894f22ef01cSRoman Divacky // overridden by a definition. 895f22ef01cSRoman Divacky 89659d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(F, FD); 8972754fe60SDimitry Andric 89859d1ed5bSDimitry Andric if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) { 89959d1ed5bSDimitry Andric if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) { 90059d1ed5bSDimitry Andric // Don't dllexport/import destructor thunks. 90159d1ed5bSDimitry Andric F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 9022754fe60SDimitry Andric } 903f22ef01cSRoman Divacky } 904f22ef01cSRoman Divacky 905f22ef01cSRoman Divacky if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 906f22ef01cSRoman Divacky F->setSection(SA->getName()); 907f785676fSDimitry Andric 908f785676fSDimitry Andric // A replaceable global allocation function does not act like a builtin by 909f785676fSDimitry Andric // default, only if it is invoked by a new-expression or delete-expression. 910f785676fSDimitry Andric if (FD->isReplaceableGlobalAllocationFunction()) 911f785676fSDimitry Andric F->addAttribute(llvm::AttributeSet::FunctionIndex, 912f785676fSDimitry Andric llvm::Attribute::NoBuiltin); 913f22ef01cSRoman Divacky } 914f22ef01cSRoman Divacky 91559d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 916f22ef01cSRoman Divacky assert(!GV->isDeclaration() && 917f22ef01cSRoman Divacky "Only globals with definition can force usage."); 918f22ef01cSRoman Divacky LLVMUsed.push_back(GV); 919f22ef01cSRoman Divacky } 920f22ef01cSRoman Divacky 92159d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 92259d1ed5bSDimitry Andric assert(!GV->isDeclaration() && 92359d1ed5bSDimitry Andric "Only globals with definition can force usage."); 92459d1ed5bSDimitry Andric LLVMCompilerUsed.push_back(GV); 92559d1ed5bSDimitry Andric } 92659d1ed5bSDimitry Andric 92759d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name, 92859d1ed5bSDimitry Andric std::vector<llvm::WeakVH> &List) { 929f22ef01cSRoman Divacky // Don't create llvm.used if there is no need. 93059d1ed5bSDimitry Andric if (List.empty()) 931f22ef01cSRoman Divacky return; 932f22ef01cSRoman Divacky 93359d1ed5bSDimitry Andric // Convert List to what ConstantArray needs. 934dff0c46cSDimitry Andric SmallVector<llvm::Constant*, 8> UsedArray; 93559d1ed5bSDimitry Andric UsedArray.resize(List.size()); 93659d1ed5bSDimitry Andric for (unsigned i = 0, e = List.size(); i != e; ++i) { 937f22ef01cSRoman Divacky UsedArray[i] = 93859d1ed5bSDimitry Andric llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*List[i]), 93959d1ed5bSDimitry Andric CGM.Int8PtrTy); 940f22ef01cSRoman Divacky } 941f22ef01cSRoman Divacky 942f22ef01cSRoman Divacky if (UsedArray.empty()) 943f22ef01cSRoman Divacky return; 94459d1ed5bSDimitry Andric llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 945f22ef01cSRoman Divacky 94659d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 94759d1ed5bSDimitry Andric CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 94859d1ed5bSDimitry Andric llvm::ConstantArray::get(ATy, UsedArray), Name); 949f22ef01cSRoman Divacky 950f22ef01cSRoman Divacky GV->setSection("llvm.metadata"); 951f22ef01cSRoman Divacky } 952f22ef01cSRoman Divacky 95359d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() { 95459d1ed5bSDimitry Andric emitUsed(*this, "llvm.used", LLVMUsed); 95559d1ed5bSDimitry Andric emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 95659d1ed5bSDimitry Andric } 95759d1ed5bSDimitry Andric 958f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 95939d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 960f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 961f785676fSDimitry Andric } 962f785676fSDimitry Andric 963f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 964f785676fSDimitry Andric llvm::SmallString<32> Opt; 965f785676fSDimitry Andric getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 96639d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 967f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 968f785676fSDimitry Andric } 969f785676fSDimitry Andric 970f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) { 971f785676fSDimitry Andric llvm::SmallString<24> Opt; 972f785676fSDimitry Andric getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 97339d628a0SDimitry Andric auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 974f785676fSDimitry Andric LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 975f785676fSDimitry Andric } 976f785676fSDimitry Andric 977139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules 978139f7f9bSDimitry Andric /// it depends on, using a postorder walk. 97939d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 98039d628a0SDimitry Andric SmallVectorImpl<llvm::Metadata *> &Metadata, 981139f7f9bSDimitry Andric llvm::SmallPtrSet<Module *, 16> &Visited) { 982139f7f9bSDimitry Andric // Import this module's parent. 98339d628a0SDimitry Andric if (Mod->Parent && Visited.insert(Mod->Parent).second) { 984f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 985139f7f9bSDimitry Andric } 986139f7f9bSDimitry Andric 987139f7f9bSDimitry Andric // Import this module's dependencies. 988139f7f9bSDimitry Andric for (unsigned I = Mod->Imports.size(); I > 0; --I) { 98939d628a0SDimitry Andric if (Visited.insert(Mod->Imports[I - 1]).second) 990f785676fSDimitry Andric addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 991139f7f9bSDimitry Andric } 992139f7f9bSDimitry Andric 993139f7f9bSDimitry Andric // Add linker options to link against the libraries/frameworks 994139f7f9bSDimitry Andric // described by this module. 995f785676fSDimitry Andric llvm::LLVMContext &Context = CGM.getLLVMContext(); 996139f7f9bSDimitry Andric for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 997f785676fSDimitry Andric // Link against a framework. Frameworks are currently Darwin only, so we 998f785676fSDimitry Andric // don't to ask TargetCodeGenInfo for the spelling of the linker option. 999139f7f9bSDimitry Andric if (Mod->LinkLibraries[I-1].IsFramework) { 100039d628a0SDimitry Andric llvm::Metadata *Args[2] = { 1001139f7f9bSDimitry Andric llvm::MDString::get(Context, "-framework"), 100239d628a0SDimitry Andric llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 1003139f7f9bSDimitry Andric 1004139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, Args)); 1005139f7f9bSDimitry Andric continue; 1006139f7f9bSDimitry Andric } 1007139f7f9bSDimitry Andric 1008139f7f9bSDimitry Andric // Link against a library. 1009f785676fSDimitry Andric llvm::SmallString<24> Opt; 1010f785676fSDimitry Andric CGM.getTargetCodeGenInfo().getDependentLibraryOption( 1011f785676fSDimitry Andric Mod->LinkLibraries[I-1].Library, Opt); 101239d628a0SDimitry Andric auto *OptString = llvm::MDString::get(Context, Opt); 1013139f7f9bSDimitry Andric Metadata.push_back(llvm::MDNode::get(Context, OptString)); 1014139f7f9bSDimitry Andric } 1015139f7f9bSDimitry Andric } 1016139f7f9bSDimitry Andric 1017139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() { 1018139f7f9bSDimitry Andric // Collect the set of all of the modules we want to visit to emit link 1019139f7f9bSDimitry Andric // options, which is essentially the imported modules and all of their 1020139f7f9bSDimitry Andric // non-explicit child modules. 1021139f7f9bSDimitry Andric llvm::SetVector<clang::Module *> LinkModules; 1022139f7f9bSDimitry Andric llvm::SmallPtrSet<clang::Module *, 16> Visited; 1023139f7f9bSDimitry Andric SmallVector<clang::Module *, 16> Stack; 1024139f7f9bSDimitry Andric 1025139f7f9bSDimitry Andric // Seed the stack with imported modules. 1026139f7f9bSDimitry Andric for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(), 1027139f7f9bSDimitry Andric MEnd = ImportedModules.end(); 1028139f7f9bSDimitry Andric M != MEnd; ++M) { 102939d628a0SDimitry Andric if (Visited.insert(*M).second) 1030139f7f9bSDimitry Andric Stack.push_back(*M); 1031139f7f9bSDimitry Andric } 1032139f7f9bSDimitry Andric 1033139f7f9bSDimitry Andric // Find all of the modules to import, making a little effort to prune 1034139f7f9bSDimitry Andric // non-leaf modules. 1035139f7f9bSDimitry Andric while (!Stack.empty()) { 1036f785676fSDimitry Andric clang::Module *Mod = Stack.pop_back_val(); 1037139f7f9bSDimitry Andric 1038139f7f9bSDimitry Andric bool AnyChildren = false; 1039139f7f9bSDimitry Andric 1040139f7f9bSDimitry Andric // Visit the submodules of this module. 1041139f7f9bSDimitry Andric for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 1042139f7f9bSDimitry Andric SubEnd = Mod->submodule_end(); 1043139f7f9bSDimitry Andric Sub != SubEnd; ++Sub) { 1044139f7f9bSDimitry Andric // Skip explicit children; they need to be explicitly imported to be 1045139f7f9bSDimitry Andric // linked against. 1046139f7f9bSDimitry Andric if ((*Sub)->IsExplicit) 1047139f7f9bSDimitry Andric continue; 1048139f7f9bSDimitry Andric 104939d628a0SDimitry Andric if (Visited.insert(*Sub).second) { 1050139f7f9bSDimitry Andric Stack.push_back(*Sub); 1051139f7f9bSDimitry Andric AnyChildren = true; 1052139f7f9bSDimitry Andric } 1053139f7f9bSDimitry Andric } 1054139f7f9bSDimitry Andric 1055139f7f9bSDimitry Andric // We didn't find any children, so add this module to the list of 1056139f7f9bSDimitry Andric // modules to link against. 1057139f7f9bSDimitry Andric if (!AnyChildren) { 1058139f7f9bSDimitry Andric LinkModules.insert(Mod); 1059139f7f9bSDimitry Andric } 1060139f7f9bSDimitry Andric } 1061139f7f9bSDimitry Andric 1062139f7f9bSDimitry Andric // Add link options for all of the imported modules in reverse topological 1063f785676fSDimitry Andric // order. We don't do anything to try to order import link flags with respect 1064f785676fSDimitry Andric // to linker options inserted by things like #pragma comment(). 106539d628a0SDimitry Andric SmallVector<llvm::Metadata *, 16> MetadataArgs; 1066139f7f9bSDimitry Andric Visited.clear(); 1067139f7f9bSDimitry Andric for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(), 1068139f7f9bSDimitry Andric MEnd = LinkModules.end(); 1069139f7f9bSDimitry Andric M != MEnd; ++M) { 107039d628a0SDimitry Andric if (Visited.insert(*M).second) 1071f785676fSDimitry Andric addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited); 1072139f7f9bSDimitry Andric } 1073139f7f9bSDimitry Andric std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 1074f785676fSDimitry Andric LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 1075139f7f9bSDimitry Andric 1076139f7f9bSDimitry Andric // Add the linker options metadata flag. 1077139f7f9bSDimitry Andric getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options", 1078f785676fSDimitry Andric llvm::MDNode::get(getLLVMContext(), 1079f785676fSDimitry Andric LinkerOptionsMetadata)); 1080139f7f9bSDimitry Andric } 1081139f7f9bSDimitry Andric 1082f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() { 1083f22ef01cSRoman Divacky // Emit code for any potentially referenced deferred decls. Since a 1084f22ef01cSRoman Divacky // previously unused static decl may become used during the generation of code 1085f22ef01cSRoman Divacky // for a static function, iterate until no changes are made. 1086f22ef01cSRoman Divacky 1087139f7f9bSDimitry Andric while (true) { 1088f22ef01cSRoman Divacky if (!DeferredVTables.empty()) { 1089139f7f9bSDimitry Andric EmitDeferredVTables(); 1090139f7f9bSDimitry Andric 1091139f7f9bSDimitry Andric // Emitting a v-table doesn't directly cause more v-tables to 1092139f7f9bSDimitry Andric // become deferred, although it can cause functions to be 1093139f7f9bSDimitry Andric // emitted that then need those v-tables. 1094139f7f9bSDimitry Andric assert(DeferredVTables.empty()); 1095f22ef01cSRoman Divacky } 1096f22ef01cSRoman Divacky 1097139f7f9bSDimitry Andric // Stop if we're out of both deferred v-tables and deferred declarations. 1098139f7f9bSDimitry Andric if (DeferredDeclsToEmit.empty()) break; 1099139f7f9bSDimitry Andric 110059d1ed5bSDimitry Andric DeferredGlobal &G = DeferredDeclsToEmit.back(); 110159d1ed5bSDimitry Andric GlobalDecl D = G.GD; 110259d1ed5bSDimitry Andric llvm::GlobalValue *GV = G.GV; 1103f22ef01cSRoman Divacky DeferredDeclsToEmit.pop_back(); 1104f22ef01cSRoman Divacky 110539d628a0SDimitry Andric assert(!GV || GV == GetGlobalValue(getMangledName(D))); 110639d628a0SDimitry Andric if (!GV) 110739d628a0SDimitry Andric GV = GetGlobalValue(getMangledName(D)); 110839d628a0SDimitry Andric 110939d628a0SDimitry Andric 1110f22ef01cSRoman Divacky // Check to see if we've already emitted this. This is necessary 1111f22ef01cSRoman Divacky // for a couple of reasons: first, decls can end up in the 1112f22ef01cSRoman Divacky // deferred-decls queue multiple times, and second, decls can end 1113f22ef01cSRoman Divacky // up with definitions in unusual ways (e.g. by an extern inline 1114f22ef01cSRoman Divacky // function acquiring a strong function redefinition). Just 1115f22ef01cSRoman Divacky // ignore these cases. 111639d628a0SDimitry Andric if (GV && !GV->isDeclaration()) 1117f22ef01cSRoman Divacky continue; 1118f22ef01cSRoman Divacky 1119f22ef01cSRoman Divacky // Otherwise, emit the definition and move on to the next one. 112059d1ed5bSDimitry Andric EmitGlobalDefinition(D, GV); 1121f22ef01cSRoman Divacky } 1122f22ef01cSRoman Divacky } 1123f22ef01cSRoman Divacky 11246122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() { 11256122f3e6SDimitry Andric if (Annotations.empty()) 11266122f3e6SDimitry Andric return; 11276122f3e6SDimitry Andric 11286122f3e6SDimitry Andric // Create a new global variable for the ConstantStruct in the Module. 11296122f3e6SDimitry Andric llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 11306122f3e6SDimitry Andric Annotations[0]->getType(), Annotations.size()), Annotations); 113159d1ed5bSDimitry Andric auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 113259d1ed5bSDimitry Andric llvm::GlobalValue::AppendingLinkage, 113359d1ed5bSDimitry Andric Array, "llvm.global.annotations"); 11346122f3e6SDimitry Andric gv->setSection(AnnotationSection); 11356122f3e6SDimitry Andric } 11366122f3e6SDimitry Andric 1137139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 1138f785676fSDimitry Andric llvm::Constant *&AStr = AnnotationStrings[Str]; 1139f785676fSDimitry Andric if (AStr) 1140f785676fSDimitry Andric return AStr; 11416122f3e6SDimitry Andric 11426122f3e6SDimitry Andric // Not found yet, create a new global. 1143dff0c46cSDimitry Andric llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 114459d1ed5bSDimitry Andric auto *gv = 114559d1ed5bSDimitry Andric new llvm::GlobalVariable(getModule(), s->getType(), true, 114659d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, s, ".str"); 11476122f3e6SDimitry Andric gv->setSection(AnnotationSection); 11486122f3e6SDimitry Andric gv->setUnnamedAddr(true); 1149f785676fSDimitry Andric AStr = gv; 11506122f3e6SDimitry Andric return gv; 11516122f3e6SDimitry Andric } 11526122f3e6SDimitry Andric 11536122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 11546122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 11556122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(Loc); 11566122f3e6SDimitry Andric if (PLoc.isValid()) 11576122f3e6SDimitry Andric return EmitAnnotationString(PLoc.getFilename()); 11586122f3e6SDimitry Andric return EmitAnnotationString(SM.getBufferName(Loc)); 11596122f3e6SDimitry Andric } 11606122f3e6SDimitry Andric 11616122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 11626122f3e6SDimitry Andric SourceManager &SM = getContext().getSourceManager(); 11636122f3e6SDimitry Andric PresumedLoc PLoc = SM.getPresumedLoc(L); 11646122f3e6SDimitry Andric unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 11656122f3e6SDimitry Andric SM.getExpansionLineNumber(L); 11666122f3e6SDimitry Andric return llvm::ConstantInt::get(Int32Ty, LineNo); 11676122f3e6SDimitry Andric } 11686122f3e6SDimitry Andric 1169f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 1170f22ef01cSRoman Divacky const AnnotateAttr *AA, 11716122f3e6SDimitry Andric SourceLocation L) { 11726122f3e6SDimitry Andric // Get the globals for file name, annotation, and the line number. 11736122f3e6SDimitry Andric llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 11746122f3e6SDimitry Andric *UnitGV = EmitAnnotationUnit(L), 11756122f3e6SDimitry Andric *LineNoCst = EmitAnnotationLineNo(L); 1176f22ef01cSRoman Divacky 1177f22ef01cSRoman Divacky // Create the ConstantStruct for the global annotation. 1178f22ef01cSRoman Divacky llvm::Constant *Fields[4] = { 11796122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 11806122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 11816122f3e6SDimitry Andric llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 11826122f3e6SDimitry Andric LineNoCst 1183f22ef01cSRoman Divacky }; 118417a519f9SDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 1185f22ef01cSRoman Divacky } 1186f22ef01cSRoman Divacky 11876122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 11886122f3e6SDimitry Andric llvm::GlobalValue *GV) { 11896122f3e6SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 11906122f3e6SDimitry Andric // Get the struct elements for these annotations. 119159d1ed5bSDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 119259d1ed5bSDimitry Andric Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 11936122f3e6SDimitry Andric } 11946122f3e6SDimitry Andric 119539d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn, 119639d628a0SDimitry Andric SourceLocation Loc) const { 119739d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 119839d628a0SDimitry Andric // Blacklist by function name. 119939d628a0SDimitry Andric if (SanitizerBL.isBlacklistedFunction(Fn->getName())) 120039d628a0SDimitry Andric return true; 120139d628a0SDimitry Andric // Blacklist by location. 120239d628a0SDimitry Andric if (!Loc.isInvalid()) 120339d628a0SDimitry Andric return SanitizerBL.isBlacklistedLocation(Loc); 120439d628a0SDimitry Andric // If location is unknown, this may be a compiler-generated function. Assume 120539d628a0SDimitry Andric // it's located in the main file. 120639d628a0SDimitry Andric auto &SM = Context.getSourceManager(); 120739d628a0SDimitry Andric if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 120839d628a0SDimitry Andric return SanitizerBL.isBlacklistedFile(MainFile->getName()); 120939d628a0SDimitry Andric } 121039d628a0SDimitry Andric return false; 121139d628a0SDimitry Andric } 121239d628a0SDimitry Andric 121339d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 121439d628a0SDimitry Andric SourceLocation Loc, QualType Ty, 121539d628a0SDimitry Andric StringRef Category) const { 121639d628a0SDimitry Andric // For now globals can be blacklisted only in ASan. 121739d628a0SDimitry Andric if (!LangOpts.Sanitize.has(SanitizerKind::Address)) 121839d628a0SDimitry Andric return false; 121939d628a0SDimitry Andric const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 122039d628a0SDimitry Andric if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category)) 122139d628a0SDimitry Andric return true; 122239d628a0SDimitry Andric if (SanitizerBL.isBlacklistedLocation(Loc, Category)) 122339d628a0SDimitry Andric return true; 122439d628a0SDimitry Andric // Check global type. 122539d628a0SDimitry Andric if (!Ty.isNull()) { 122639d628a0SDimitry Andric // Drill down the array types: if global variable of a fixed type is 122739d628a0SDimitry Andric // blacklisted, we also don't instrument arrays of them. 122839d628a0SDimitry Andric while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 122939d628a0SDimitry Andric Ty = AT->getElementType(); 123039d628a0SDimitry Andric Ty = Ty.getCanonicalType().getUnqualifiedType(); 123139d628a0SDimitry Andric // We allow to blacklist only record types (classes, structs etc.) 123239d628a0SDimitry Andric if (Ty->isRecordType()) { 123339d628a0SDimitry Andric std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 123439d628a0SDimitry Andric if (SanitizerBL.isBlacklistedType(TypeStr, Category)) 123539d628a0SDimitry Andric return true; 123639d628a0SDimitry Andric } 123739d628a0SDimitry Andric } 123839d628a0SDimitry Andric return false; 123939d628a0SDimitry Andric } 124039d628a0SDimitry Andric 124139d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 1242e580952dSDimitry Andric // Never defer when EmitAllDecls is specified. 1243dff0c46cSDimitry Andric if (LangOpts.EmitAllDecls) 124439d628a0SDimitry Andric return true; 124539d628a0SDimitry Andric 124639d628a0SDimitry Andric return getContext().DeclMustBeEmitted(Global); 124739d628a0SDimitry Andric } 124839d628a0SDimitry Andric 124939d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 125039d628a0SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) 125139d628a0SDimitry Andric if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 125239d628a0SDimitry Andric // Implicit template instantiations may change linkage if they are later 125339d628a0SDimitry Andric // explicitly instantiated, so they should not be emitted eagerly. 1254f22ef01cSRoman Divacky return false; 1255f22ef01cSRoman Divacky 125639d628a0SDimitry Andric return true; 1257f22ef01cSRoman Divacky } 1258f22ef01cSRoman Divacky 12593861d79fSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor( 12603861d79fSDimitry Andric const CXXUuidofExpr* E) { 12613861d79fSDimitry Andric // Sema has verified that IIDSource has a __declspec(uuid()), and that its 12623861d79fSDimitry Andric // well-formed. 1263f785676fSDimitry Andric StringRef Uuid = E->getUuidAsStringRef(Context); 1264f785676fSDimitry Andric std::string Name = "_GUID_" + Uuid.lower(); 1265f785676fSDimitry Andric std::replace(Name.begin(), Name.end(), '-', '_'); 12663861d79fSDimitry Andric 12673861d79fSDimitry Andric // Look for an existing global. 12683861d79fSDimitry Andric if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 12693861d79fSDimitry Andric return GV; 12703861d79fSDimitry Andric 127139d628a0SDimitry Andric llvm::Constant *Init = EmitUuidofInitializer(Uuid); 12723861d79fSDimitry Andric assert(Init && "failed to initialize as constant"); 12733861d79fSDimitry Andric 127459d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 1275f785676fSDimitry Andric getModule(), Init->getType(), 1276f785676fSDimitry Andric /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 12773861d79fSDimitry Andric return GV; 12783861d79fSDimitry Andric } 12793861d79fSDimitry Andric 1280f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 1281f22ef01cSRoman Divacky const AliasAttr *AA = VD->getAttr<AliasAttr>(); 1282f22ef01cSRoman Divacky assert(AA && "No alias?"); 1283f22ef01cSRoman Divacky 12846122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 1285f22ef01cSRoman Divacky 1286f22ef01cSRoman Divacky // See if there is already something with the target's name in the module. 1287f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 12883861d79fSDimitry Andric if (Entry) { 12893861d79fSDimitry Andric unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 12903861d79fSDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 12913861d79fSDimitry Andric } 1292f22ef01cSRoman Divacky 1293f22ef01cSRoman Divacky llvm::Constant *Aliasee; 1294f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 12953861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 12963861d79fSDimitry Andric GlobalDecl(cast<FunctionDecl>(VD)), 12972754fe60SDimitry Andric /*ForVTable=*/false); 1298f22ef01cSRoman Divacky else 1299f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 130059d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 130159d1ed5bSDimitry Andric nullptr); 13023861d79fSDimitry Andric 130359d1ed5bSDimitry Andric auto *F = cast<llvm::GlobalValue>(Aliasee); 1304f22ef01cSRoman Divacky F->setLinkage(llvm::Function::ExternalWeakLinkage); 1305f22ef01cSRoman Divacky WeakRefReferences.insert(F); 1306f22ef01cSRoman Divacky 1307f22ef01cSRoman Divacky return Aliasee; 1308f22ef01cSRoman Divacky } 1309f22ef01cSRoman Divacky 1310f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) { 131159d1ed5bSDimitry Andric const auto *Global = cast<ValueDecl>(GD.getDecl()); 1312f22ef01cSRoman Divacky 1313f22ef01cSRoman Divacky // Weak references don't produce any output by themselves. 1314f22ef01cSRoman Divacky if (Global->hasAttr<WeakRefAttr>()) 1315f22ef01cSRoman Divacky return; 1316f22ef01cSRoman Divacky 1317f22ef01cSRoman Divacky // If this is an alias definition (which otherwise looks like a declaration) 1318f22ef01cSRoman Divacky // emit it now. 1319f22ef01cSRoman Divacky if (Global->hasAttr<AliasAttr>()) 1320f22ef01cSRoman Divacky return EmitAliasDefinition(GD); 1321f22ef01cSRoman Divacky 13226122f3e6SDimitry Andric // If this is CUDA, be selective about which declarations we emit. 1323dff0c46cSDimitry Andric if (LangOpts.CUDA) { 13246122f3e6SDimitry Andric if (CodeGenOpts.CUDAIsDevice) { 13256122f3e6SDimitry Andric if (!Global->hasAttr<CUDADeviceAttr>() && 13266122f3e6SDimitry Andric !Global->hasAttr<CUDAGlobalAttr>() && 13276122f3e6SDimitry Andric !Global->hasAttr<CUDAConstantAttr>() && 13286122f3e6SDimitry Andric !Global->hasAttr<CUDASharedAttr>()) 13296122f3e6SDimitry Andric return; 13306122f3e6SDimitry Andric } else { 13316122f3e6SDimitry Andric if (!Global->hasAttr<CUDAHostAttr>() && ( 13326122f3e6SDimitry Andric Global->hasAttr<CUDADeviceAttr>() || 13336122f3e6SDimitry Andric Global->hasAttr<CUDAConstantAttr>() || 13346122f3e6SDimitry Andric Global->hasAttr<CUDASharedAttr>())) 13356122f3e6SDimitry Andric return; 1336e580952dSDimitry Andric } 1337e580952dSDimitry Andric } 1338e580952dSDimitry Andric 13396122f3e6SDimitry Andric // Ignore declarations, they will be emitted on their first use. 134059d1ed5bSDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 1341f22ef01cSRoman Divacky // Forward declarations are emitted lazily on first use. 13426122f3e6SDimitry Andric if (!FD->doesThisDeclarationHaveABody()) { 13436122f3e6SDimitry Andric if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 1344f22ef01cSRoman Divacky return; 13456122f3e6SDimitry Andric 13466122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 134759d1ed5bSDimitry Andric 134859d1ed5bSDimitry Andric // Compute the function info and LLVM type. 134959d1ed5bSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 135059d1ed5bSDimitry Andric llvm::Type *Ty = getTypes().GetFunctionType(FI); 135159d1ed5bSDimitry Andric 135259d1ed5bSDimitry Andric GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 135359d1ed5bSDimitry Andric /*DontDefer=*/false); 13546122f3e6SDimitry Andric return; 13556122f3e6SDimitry Andric } 1356f22ef01cSRoman Divacky } else { 135759d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(Global); 1358f22ef01cSRoman Divacky assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 1359f22ef01cSRoman Divacky 136059d1ed5bSDimitry Andric if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 136159d1ed5bSDimitry Andric !Context.isMSStaticDataMemberInlineDefinition(VD)) 1362f22ef01cSRoman Divacky return; 1363f22ef01cSRoman Divacky } 1364f22ef01cSRoman Divacky 136539d628a0SDimitry Andric // Defer code generation to first use when possible, e.g. if this is an inline 136639d628a0SDimitry Andric // function. If the global must always be emitted, do it eagerly if possible 136739d628a0SDimitry Andric // to benefit from cache locality. 136839d628a0SDimitry Andric if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 1369f22ef01cSRoman Divacky // Emit the definition if it can't be deferred. 1370f22ef01cSRoman Divacky EmitGlobalDefinition(GD); 1371f22ef01cSRoman Divacky return; 1372f22ef01cSRoman Divacky } 1373f22ef01cSRoman Divacky 1374e580952dSDimitry Andric // If we're deferring emission of a C++ variable with an 1375e580952dSDimitry Andric // initializer, remember the order in which it appeared in the file. 1376dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 1377e580952dSDimitry Andric cast<VarDecl>(Global)->hasInit()) { 1378e580952dSDimitry Andric DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 137959d1ed5bSDimitry Andric CXXGlobalInits.push_back(nullptr); 1380e580952dSDimitry Andric } 1381e580952dSDimitry Andric 13826122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 138339d628a0SDimitry Andric if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) { 138439d628a0SDimitry Andric // The value has already been used and should therefore be emitted. 138559d1ed5bSDimitry Andric addDeferredDeclToEmit(GV, GD); 138639d628a0SDimitry Andric } else if (MustBeEmitted(Global)) { 138739d628a0SDimitry Andric // The value must be emitted, but cannot be emitted eagerly. 138839d628a0SDimitry Andric assert(!MayBeEmittedEagerly(Global)); 138939d628a0SDimitry Andric addDeferredDeclToEmit(/*GV=*/nullptr, GD); 139039d628a0SDimitry Andric } else { 1391f22ef01cSRoman Divacky // Otherwise, remember that we saw a deferred decl with this name. The 1392f22ef01cSRoman Divacky // first use of the mangled name will cause it to move into 1393f22ef01cSRoman Divacky // DeferredDeclsToEmit. 1394f22ef01cSRoman Divacky DeferredDecls[MangledName] = GD; 1395f22ef01cSRoman Divacky } 1396f22ef01cSRoman Divacky } 1397f22ef01cSRoman Divacky 1398f8254f43SDimitry Andric namespace { 1399f8254f43SDimitry Andric struct FunctionIsDirectlyRecursive : 1400f8254f43SDimitry Andric public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 1401f8254f43SDimitry Andric const StringRef Name; 1402dff0c46cSDimitry Andric const Builtin::Context &BI; 1403f8254f43SDimitry Andric bool Result; 1404dff0c46cSDimitry Andric FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 1405dff0c46cSDimitry Andric Name(N), BI(C), Result(false) { 1406f8254f43SDimitry Andric } 1407f8254f43SDimitry Andric typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 1408f8254f43SDimitry Andric 1409f8254f43SDimitry Andric bool TraverseCallExpr(CallExpr *E) { 1410dff0c46cSDimitry Andric const FunctionDecl *FD = E->getDirectCallee(); 1411dff0c46cSDimitry Andric if (!FD) 1412f8254f43SDimitry Andric return true; 1413dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1414dff0c46cSDimitry Andric if (Attr && Name == Attr->getLabel()) { 1415dff0c46cSDimitry Andric Result = true; 1416dff0c46cSDimitry Andric return false; 1417dff0c46cSDimitry Andric } 1418dff0c46cSDimitry Andric unsigned BuiltinID = FD->getBuiltinID(); 1419dff0c46cSDimitry Andric if (!BuiltinID) 1420f8254f43SDimitry Andric return true; 1421dff0c46cSDimitry Andric StringRef BuiltinName = BI.GetName(BuiltinID); 1422dff0c46cSDimitry Andric if (BuiltinName.startswith("__builtin_") && 1423dff0c46cSDimitry Andric Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 1424f8254f43SDimitry Andric Result = true; 1425f8254f43SDimitry Andric return false; 1426f8254f43SDimitry Andric } 1427f8254f43SDimitry Andric return true; 1428f8254f43SDimitry Andric } 1429f8254f43SDimitry Andric }; 1430f8254f43SDimitry Andric } 1431f8254f43SDimitry Andric 1432dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another 1433dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin, 1434dff0c46cSDimitry Andric // ends up pointing to itself. 1435f8254f43SDimitry Andric bool 1436dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 1437dff0c46cSDimitry Andric StringRef Name; 1438dff0c46cSDimitry Andric if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 1439dff0c46cSDimitry Andric // asm labels are a special kind of mangling we have to support. 1440dff0c46cSDimitry Andric AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 1441dff0c46cSDimitry Andric if (!Attr) 1442f8254f43SDimitry Andric return false; 1443dff0c46cSDimitry Andric Name = Attr->getLabel(); 1444dff0c46cSDimitry Andric } else { 1445dff0c46cSDimitry Andric Name = FD->getName(); 1446dff0c46cSDimitry Andric } 1447f8254f43SDimitry Andric 1448dff0c46cSDimitry Andric FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 1449dff0c46cSDimitry Andric Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 1450f8254f43SDimitry Andric return Walker.Result; 1451f8254f43SDimitry Andric } 1452f8254f43SDimitry Andric 1453f8254f43SDimitry Andric bool 1454f785676fSDimitry Andric CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 1455f785676fSDimitry Andric if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 1456f8254f43SDimitry Andric return true; 145759d1ed5bSDimitry Andric const auto *F = cast<FunctionDecl>(GD.getDecl()); 145859d1ed5bSDimitry Andric if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 1459f8254f43SDimitry Andric return false; 1460f8254f43SDimitry Andric // PR9614. Avoid cases where the source code is lying to us. An available 1461f8254f43SDimitry Andric // externally function should have an equivalent function somewhere else, 1462f8254f43SDimitry Andric // but a function that calls itself is clearly not equivalent to the real 1463f8254f43SDimitry Andric // implementation. 1464f8254f43SDimitry Andric // This happens in glibc's btowc and in some configure checks. 1465dff0c46cSDimitry Andric return !isTriviallyRecursive(F); 1466f8254f43SDimitry Andric } 1467f8254f43SDimitry Andric 1468f785676fSDimitry Andric /// If the type for the method's class was generated by 1469f785676fSDimitry Andric /// CGDebugInfo::createContextChain(), the cache contains only a 1470f785676fSDimitry Andric /// limited DIType without any declarations. Since EmitFunctionStart() 1471f785676fSDimitry Andric /// needs to find the canonical declaration for each method, we need 1472f785676fSDimitry Andric /// to construct the complete type prior to emitting the method. 1473f785676fSDimitry Andric void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) { 1474f785676fSDimitry Andric if (!D->isInstance()) 1475f785676fSDimitry Andric return; 1476f785676fSDimitry Andric 1477f785676fSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 1478f785676fSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) { 147959d1ed5bSDimitry Andric const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext())); 1480f785676fSDimitry Andric DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation()); 1481f785676fSDimitry Andric } 1482f785676fSDimitry Andric } 1483f785676fSDimitry Andric 148459d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 148559d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 1486f22ef01cSRoman Divacky 1487f22ef01cSRoman Divacky PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 1488f22ef01cSRoman Divacky Context.getSourceManager(), 1489f22ef01cSRoman Divacky "Generating code for declaration"); 1490f22ef01cSRoman Divacky 1491f785676fSDimitry Andric if (isa<FunctionDecl>(D)) { 1492ffd1746dSEd Schouten // At -O0, don't generate IR for functions with available_externally 1493ffd1746dSEd Schouten // linkage. 1494f785676fSDimitry Andric if (!shouldEmitFunction(GD)) 1495ffd1746dSEd Schouten return; 1496ffd1746dSEd Schouten 149759d1ed5bSDimitry Andric if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 1498f785676fSDimitry Andric CompleteDIClassType(Method); 1499bd5abe19SDimitry Andric // Make sure to emit the definition(s) before we emit the thunks. 1500bd5abe19SDimitry Andric // This is necessary for the generation of certain thunks. 150159d1ed5bSDimitry Andric if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) 150239d628a0SDimitry Andric ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType())); 150359d1ed5bSDimitry Andric else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method)) 150439d628a0SDimitry Andric ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType())); 1505bd5abe19SDimitry Andric else 150659d1ed5bSDimitry Andric EmitGlobalFunctionDefinition(GD, GV); 1507bd5abe19SDimitry Andric 1508f22ef01cSRoman Divacky if (Method->isVirtual()) 1509f22ef01cSRoman Divacky getVTables().EmitThunks(GD); 1510f22ef01cSRoman Divacky 1511bd5abe19SDimitry Andric return; 1512ffd1746dSEd Schouten } 1513f22ef01cSRoman Divacky 151459d1ed5bSDimitry Andric return EmitGlobalFunctionDefinition(GD, GV); 1515ffd1746dSEd Schouten } 1516f22ef01cSRoman Divacky 151759d1ed5bSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 1518f22ef01cSRoman Divacky return EmitGlobalVarDefinition(VD); 1519f22ef01cSRoman Divacky 15206122f3e6SDimitry Andric llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 1521f22ef01cSRoman Divacky } 1522f22ef01cSRoman Divacky 1523f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 1524f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there 1525f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 1526f22ef01cSRoman Divacky /// bitcasted to the right type. 1527f22ef01cSRoman Divacky /// 1528f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 1529f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created. 1530f22ef01cSRoman Divacky llvm::Constant * 15316122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 15326122f3e6SDimitry Andric llvm::Type *Ty, 1533f785676fSDimitry Andric GlobalDecl GD, bool ForVTable, 153439d628a0SDimitry Andric bool DontDefer, bool IsThunk, 1535139f7f9bSDimitry Andric llvm::AttributeSet ExtraAttrs) { 1536f785676fSDimitry Andric const Decl *D = GD.getDecl(); 1537f785676fSDimitry Andric 1538f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 1539f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1540f22ef01cSRoman Divacky if (Entry) { 15413861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 1542f785676fSDimitry Andric const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 1543f22ef01cSRoman Divacky if (FD && !FD->hasAttr<WeakAttr>()) 1544f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 1545f22ef01cSRoman Divacky } 1546f22ef01cSRoman Divacky 154739d628a0SDimitry Andric // Handle dropped DLL attributes. 154839d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 154939d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 155039d628a0SDimitry Andric 1551f22ef01cSRoman Divacky if (Entry->getType()->getElementType() == Ty) 1552f22ef01cSRoman Divacky return Entry; 1553f22ef01cSRoman Divacky 1554f22ef01cSRoman Divacky // Make sure the result is of the correct type. 155517a519f9SDimitry Andric return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 1556f22ef01cSRoman Divacky } 1557f22ef01cSRoman Divacky 1558f22ef01cSRoman Divacky // This function doesn't have a complete type (for example, the return 1559f22ef01cSRoman Divacky // type is an incomplete struct). Use a fake type instead, and make 1560f22ef01cSRoman Divacky // sure not to try to set attributes. 1561f22ef01cSRoman Divacky bool IsIncompleteFunction = false; 1562f22ef01cSRoman Divacky 15636122f3e6SDimitry Andric llvm::FunctionType *FTy; 1564f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(Ty)) { 1565f22ef01cSRoman Divacky FTy = cast<llvm::FunctionType>(Ty); 1566f22ef01cSRoman Divacky } else { 1567bd5abe19SDimitry Andric FTy = llvm::FunctionType::get(VoidTy, false); 1568f22ef01cSRoman Divacky IsIncompleteFunction = true; 1569f22ef01cSRoman Divacky } 1570ffd1746dSEd Schouten 1571f22ef01cSRoman Divacky llvm::Function *F = llvm::Function::Create(FTy, 1572f22ef01cSRoman Divacky llvm::Function::ExternalLinkage, 1573f22ef01cSRoman Divacky MangledName, &getModule()); 1574f22ef01cSRoman Divacky assert(F->getName() == MangledName && "name was uniqued!"); 1575f785676fSDimitry Andric if (D) 157639d628a0SDimitry Andric SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 1577139f7f9bSDimitry Andric if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) { 1578139f7f9bSDimitry Andric llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex); 1579139f7f9bSDimitry Andric F->addAttributes(llvm::AttributeSet::FunctionIndex, 1580139f7f9bSDimitry Andric llvm::AttributeSet::get(VMContext, 1581139f7f9bSDimitry Andric llvm::AttributeSet::FunctionIndex, 1582139f7f9bSDimitry Andric B)); 1583139f7f9bSDimitry Andric } 1584f22ef01cSRoman Divacky 158559d1ed5bSDimitry Andric if (!DontDefer) { 158659d1ed5bSDimitry Andric // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 158759d1ed5bSDimitry Andric // each other bottoming out with the base dtor. Therefore we emit non-base 158859d1ed5bSDimitry Andric // dtors on usage, even if there is no dtor definition in the TU. 158959d1ed5bSDimitry Andric if (D && isa<CXXDestructorDecl>(D) && 159059d1ed5bSDimitry Andric getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 159159d1ed5bSDimitry Andric GD.getDtorType())) 159259d1ed5bSDimitry Andric addDeferredDeclToEmit(F, GD); 159359d1ed5bSDimitry Andric 1594f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 1595f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 1596f22ef01cSRoman Divacky // of the file. 159759d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 1598f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 159959d1ed5bSDimitry Andric // Move the potentially referenced deferred decl to the 160059d1ed5bSDimitry Andric // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 160159d1ed5bSDimitry Andric // don't need it anymore). 160259d1ed5bSDimitry Andric addDeferredDeclToEmit(F, DDI->second); 1603f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 16042754fe60SDimitry Andric 160559d1ed5bSDimitry Andric // Otherwise, if this is a sized deallocation function, emit a weak 160659d1ed5bSDimitry Andric // definition 1607f785676fSDimitry Andric // for it at the end of the translation unit. 1608f785676fSDimitry Andric } else if (D && cast<FunctionDecl>(D) 1609f785676fSDimitry Andric ->getCorrespondingUnsizedGlobalDeallocationFunction()) { 161059d1ed5bSDimitry Andric addDeferredDeclToEmit(F, GD); 1611f785676fSDimitry Andric 16122754fe60SDimitry Andric // Otherwise, there are cases we have to worry about where we're 16132754fe60SDimitry Andric // using a declaration for which we must emit a definition but where 16142754fe60SDimitry Andric // we might not find a top-level definition: 16152754fe60SDimitry Andric // - member functions defined inline in their classes 16162754fe60SDimitry Andric // - friend functions defined inline in some class 16172754fe60SDimitry Andric // - special member functions with implicit definitions 16182754fe60SDimitry Andric // If we ever change our AST traversal to walk into class methods, 16192754fe60SDimitry Andric // this will be unnecessary. 16202754fe60SDimitry Andric // 162159d1ed5bSDimitry Andric // We also don't emit a definition for a function if it's going to be an 162239d628a0SDimitry Andric // entry in a vtable, unless it's already marked as used. 1623f785676fSDimitry Andric } else if (getLangOpts().CPlusPlus && D) { 16242754fe60SDimitry Andric // Look for a declaration that's lexically in a record. 162539d628a0SDimitry Andric for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 162639d628a0SDimitry Andric FD = FD->getPreviousDecl()) { 16272754fe60SDimitry Andric if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 162839d628a0SDimitry Andric if (FD->doesThisDeclarationHaveABody()) { 162959d1ed5bSDimitry Andric addDeferredDeclToEmit(F, GD.getWithDecl(FD)); 16302754fe60SDimitry Andric break; 1631f22ef01cSRoman Divacky } 1632f22ef01cSRoman Divacky } 163339d628a0SDimitry Andric } 1634f22ef01cSRoman Divacky } 163559d1ed5bSDimitry Andric } 1636f22ef01cSRoman Divacky 1637f22ef01cSRoman Divacky // Make sure the result is of the requested type. 1638f22ef01cSRoman Divacky if (!IsIncompleteFunction) { 1639f22ef01cSRoman Divacky assert(F->getType()->getElementType() == Ty); 1640f22ef01cSRoman Divacky return F; 1641f22ef01cSRoman Divacky } 1642f22ef01cSRoman Divacky 164317a519f9SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 1644f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(F, PTy); 1645f22ef01cSRoman Divacky } 1646f22ef01cSRoman Divacky 1647f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function. If Ty is 1648f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to 1649f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function). 1650f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 16516122f3e6SDimitry Andric llvm::Type *Ty, 165259d1ed5bSDimitry Andric bool ForVTable, 165359d1ed5bSDimitry Andric bool DontDefer) { 1654f22ef01cSRoman Divacky // If there was no specific requested type, just convert it now. 1655f22ef01cSRoman Divacky if (!Ty) 1656f22ef01cSRoman Divacky Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 1657ffd1746dSEd Schouten 16586122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 165959d1ed5bSDimitry Andric return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer); 1660f22ef01cSRoman Divacky } 1661f22ef01cSRoman Divacky 1662f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified 1663f22ef01cSRoman Divacky /// type and name. 1664f22ef01cSRoman Divacky llvm::Constant * 16656122f3e6SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 16666122f3e6SDimitry Andric StringRef Name, 1667139f7f9bSDimitry Andric llvm::AttributeSet ExtraAttrs) { 166859d1ed5bSDimitry Andric llvm::Constant *C = 166959d1ed5bSDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 167039d628a0SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 167159d1ed5bSDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) 1672139f7f9bSDimitry Andric if (F->empty()) 1673139f7f9bSDimitry Andric F->setCallingConv(getRuntimeCC()); 1674139f7f9bSDimitry Andric return C; 1675f22ef01cSRoman Divacky } 1676f22ef01cSRoman Divacky 167739d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified 167839d628a0SDimitry Andric /// type and name. 167939d628a0SDimitry Andric llvm::Constant * 168039d628a0SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, 168139d628a0SDimitry Andric StringRef Name, 168239d628a0SDimitry Andric llvm::AttributeSet ExtraAttrs) { 168339d628a0SDimitry Andric llvm::Constant *C = 168439d628a0SDimitry Andric GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 168539d628a0SDimitry Andric /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); 168639d628a0SDimitry Andric if (auto *F = dyn_cast<llvm::Function>(C)) 168739d628a0SDimitry Andric if (F->empty()) 168839d628a0SDimitry Andric F->setCallingConv(getBuiltinCC()); 168939d628a0SDimitry Andric return C; 169039d628a0SDimitry Andric } 169139d628a0SDimitry Andric 1692dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted 1693dff0c46cSDimitry Andric /// as a constant. 1694dff0c46cSDimitry Andric /// 1695dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs 1696dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is 1697dff0c46cSDimitry Andric /// not written to during its construction. 1698dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 1699dff0c46cSDimitry Andric if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 1700f22ef01cSRoman Divacky return false; 1701bd5abe19SDimitry Andric 1702dff0c46cSDimitry Andric if (Context.getLangOpts().CPlusPlus) { 1703dff0c46cSDimitry Andric if (const CXXRecordDecl *Record 1704dff0c46cSDimitry Andric = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 1705dff0c46cSDimitry Andric return ExcludeCtor && !Record->hasMutableFields() && 1706dff0c46cSDimitry Andric Record->hasTrivialDestructor(); 1707f22ef01cSRoman Divacky } 1708bd5abe19SDimitry Andric 1709f22ef01cSRoman Divacky return true; 1710f22ef01cSRoman Divacky } 1711f22ef01cSRoman Divacky 1712f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 1713f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type. If there 1714f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially 1715f22ef01cSRoman Divacky /// bitcasted to the right type. 1716f22ef01cSRoman Divacky /// 1717f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this. This is used 1718f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created. 1719f22ef01cSRoman Divacky llvm::Constant * 17206122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 17216122f3e6SDimitry Andric llvm::PointerType *Ty, 172259d1ed5bSDimitry Andric const VarDecl *D) { 1723f22ef01cSRoman Divacky // Lookup the entry, lazily creating it if necessary. 1724f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1725f22ef01cSRoman Divacky if (Entry) { 17263861d79fSDimitry Andric if (WeakRefReferences.erase(Entry)) { 1727f22ef01cSRoman Divacky if (D && !D->hasAttr<WeakAttr>()) 1728f22ef01cSRoman Divacky Entry->setLinkage(llvm::Function::ExternalLinkage); 1729f22ef01cSRoman Divacky } 1730f22ef01cSRoman Divacky 173139d628a0SDimitry Andric // Handle dropped DLL attributes. 173239d628a0SDimitry Andric if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 173339d628a0SDimitry Andric Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 173439d628a0SDimitry Andric 1735f22ef01cSRoman Divacky if (Entry->getType() == Ty) 1736f22ef01cSRoman Divacky return Entry; 1737f22ef01cSRoman Divacky 1738f22ef01cSRoman Divacky // Make sure the result is of the correct type. 1739f785676fSDimitry Andric if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 1740f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 1741f785676fSDimitry Andric 1742f22ef01cSRoman Divacky return llvm::ConstantExpr::getBitCast(Entry, Ty); 1743f22ef01cSRoman Divacky } 1744f22ef01cSRoman Divacky 174559d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace()); 174659d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 174759d1ed5bSDimitry Andric getModule(), Ty->getElementType(), false, 174859d1ed5bSDimitry Andric llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 174959d1ed5bSDimitry Andric llvm::GlobalVariable::NotThreadLocal, AddrSpace); 175059d1ed5bSDimitry Andric 1751f22ef01cSRoman Divacky // This is the first use or definition of a mangled name. If there is a 1752f22ef01cSRoman Divacky // deferred decl with this name, remember that we need to emit it at the end 1753f22ef01cSRoman Divacky // of the file. 175459d1ed5bSDimitry Andric auto DDI = DeferredDecls.find(MangledName); 1755f22ef01cSRoman Divacky if (DDI != DeferredDecls.end()) { 1756f22ef01cSRoman Divacky // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 1757f22ef01cSRoman Divacky // list, and remove it from DeferredDecls (since we don't need it anymore). 175859d1ed5bSDimitry Andric addDeferredDeclToEmit(GV, DDI->second); 1759f22ef01cSRoman Divacky DeferredDecls.erase(DDI); 1760f22ef01cSRoman Divacky } 1761f22ef01cSRoman Divacky 1762f22ef01cSRoman Divacky // Handle things which are present even on external declarations. 1763f22ef01cSRoman Divacky if (D) { 1764f22ef01cSRoman Divacky // FIXME: This code is overly simple and should be merged with other global 1765f22ef01cSRoman Divacky // handling. 1766dff0c46cSDimitry Andric GV->setConstant(isTypeConstant(D->getType(), false)); 1767f22ef01cSRoman Divacky 176859d1ed5bSDimitry Andric setLinkageAndVisibilityForGV(GV, D); 17692754fe60SDimitry Andric 1770284c1978SDimitry Andric if (D->getTLSKind()) { 1771284c1978SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 1772284c1978SDimitry Andric CXXThreadLocals.push_back(std::make_pair(D, GV)); 17737ae0e2c9SDimitry Andric setTLSMode(GV, *D); 1774f22ef01cSRoman Divacky } 1775f785676fSDimitry Andric 1776f785676fSDimitry Andric // If required by the ABI, treat declarations of static data members with 1777f785676fSDimitry Andric // inline initializers as definitions. 177859d1ed5bSDimitry Andric if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 1779f785676fSDimitry Andric EmitGlobalVarDefinition(D); 1780284c1978SDimitry Andric } 1781f22ef01cSRoman Divacky 178259d1ed5bSDimitry Andric // Handle XCore specific ABI requirements. 178359d1ed5bSDimitry Andric if (getTarget().getTriple().getArch() == llvm::Triple::xcore && 178459d1ed5bSDimitry Andric D->getLanguageLinkage() == CLanguageLinkage && 178559d1ed5bSDimitry Andric D->getType().isConstant(Context) && 178659d1ed5bSDimitry Andric isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 178759d1ed5bSDimitry Andric GV->setSection(".cp.rodata"); 178859d1ed5bSDimitry Andric } 178959d1ed5bSDimitry Andric 17907ae0e2c9SDimitry Andric if (AddrSpace != Ty->getAddressSpace()) 1791f785676fSDimitry Andric return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty); 1792f785676fSDimitry Andric 1793f22ef01cSRoman Divacky return GV; 1794f22ef01cSRoman Divacky } 1795f22ef01cSRoman Divacky 1796f22ef01cSRoman Divacky 17972754fe60SDimitry Andric llvm::GlobalVariable * 17986122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 17996122f3e6SDimitry Andric llvm::Type *Ty, 18002754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage) { 18012754fe60SDimitry Andric llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 180259d1ed5bSDimitry Andric llvm::GlobalVariable *OldGV = nullptr; 18032754fe60SDimitry Andric 18042754fe60SDimitry Andric if (GV) { 18052754fe60SDimitry Andric // Check if the variable has the right type. 18062754fe60SDimitry Andric if (GV->getType()->getElementType() == Ty) 18072754fe60SDimitry Andric return GV; 18082754fe60SDimitry Andric 18092754fe60SDimitry Andric // Because C++ name mangling, the only way we can end up with an already 18102754fe60SDimitry Andric // existing global with the same name is if it has been declared extern "C". 18112754fe60SDimitry Andric assert(GV->isDeclaration() && "Declaration has wrong type!"); 18122754fe60SDimitry Andric OldGV = GV; 18132754fe60SDimitry Andric } 18142754fe60SDimitry Andric 18152754fe60SDimitry Andric // Create a new variable. 18162754fe60SDimitry Andric GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 181759d1ed5bSDimitry Andric Linkage, nullptr, Name); 18182754fe60SDimitry Andric 18192754fe60SDimitry Andric if (OldGV) { 18202754fe60SDimitry Andric // Replace occurrences of the old variable if needed. 18212754fe60SDimitry Andric GV->takeName(OldGV); 18222754fe60SDimitry Andric 18232754fe60SDimitry Andric if (!OldGV->use_empty()) { 18242754fe60SDimitry Andric llvm::Constant *NewPtrForOldDecl = 18252754fe60SDimitry Andric llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 18262754fe60SDimitry Andric OldGV->replaceAllUsesWith(NewPtrForOldDecl); 18272754fe60SDimitry Andric } 18282754fe60SDimitry Andric 18292754fe60SDimitry Andric OldGV->eraseFromParent(); 18302754fe60SDimitry Andric } 18312754fe60SDimitry Andric 18322754fe60SDimitry Andric return GV; 18332754fe60SDimitry Andric } 18342754fe60SDimitry Andric 1835f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 1836f22ef01cSRoman Divacky /// given global variable. If Ty is non-null and if the global doesn't exist, 1837cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the 1838f22ef01cSRoman Divacky /// normal requested type would be. 1839f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 18406122f3e6SDimitry Andric llvm::Type *Ty) { 1841f22ef01cSRoman Divacky assert(D->hasGlobalStorage() && "Not a global variable"); 1842f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 184359d1ed5bSDimitry Andric if (!Ty) 1844f22ef01cSRoman Divacky Ty = getTypes().ConvertTypeForMem(ASTTy); 1845f22ef01cSRoman Divacky 18466122f3e6SDimitry Andric llvm::PointerType *PTy = 18473b0f4066SDimitry Andric llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 1848f22ef01cSRoman Divacky 18496122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 1850f22ef01cSRoman Divacky return GetOrCreateLLVMGlobal(MangledName, PTy, D); 1851f22ef01cSRoman Divacky } 1852f22ef01cSRoman Divacky 1853f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the 1854f22ef01cSRoman Divacky /// specified type and name. 1855f22ef01cSRoman Divacky llvm::Constant * 18566122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 18576122f3e6SDimitry Andric StringRef Name) { 185859d1ed5bSDimitry Andric return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr); 1859f22ef01cSRoman Divacky } 1860f22ef01cSRoman Divacky 1861f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 1862f22ef01cSRoman Divacky assert(!D->getInit() && "Cannot emit definite definitions here!"); 1863f22ef01cSRoman Divacky 186439d628a0SDimitry Andric if (!MustBeEmitted(D)) { 1865f22ef01cSRoman Divacky // If we have not seen a reference to this variable yet, place it 1866f22ef01cSRoman Divacky // into the deferred declarations table to be emitted if needed 1867f22ef01cSRoman Divacky // later. 18686122f3e6SDimitry Andric StringRef MangledName = getMangledName(D); 1869f22ef01cSRoman Divacky if (!GetGlobalValue(MangledName)) { 1870f22ef01cSRoman Divacky DeferredDecls[MangledName] = D; 1871f22ef01cSRoman Divacky return; 1872f22ef01cSRoman Divacky } 1873f22ef01cSRoman Divacky } 1874f22ef01cSRoman Divacky 1875f22ef01cSRoman Divacky // The tentative definition is the only definition. 1876f22ef01cSRoman Divacky EmitGlobalVarDefinition(D); 1877f22ef01cSRoman Divacky } 1878f22ef01cSRoman Divacky 18796122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 18802754fe60SDimitry Andric return Context.toCharUnitsFromBits( 18813861d79fSDimitry Andric TheDataLayout.getTypeStoreSizeInBits(Ty)); 1882f22ef01cSRoman Divacky } 1883f22ef01cSRoman Divacky 18847ae0e2c9SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D, 18857ae0e2c9SDimitry Andric unsigned AddrSpace) { 18867ae0e2c9SDimitry Andric if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) { 18877ae0e2c9SDimitry Andric if (D->hasAttr<CUDAConstantAttr>()) 18887ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant); 18897ae0e2c9SDimitry Andric else if (D->hasAttr<CUDASharedAttr>()) 18907ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared); 18917ae0e2c9SDimitry Andric else 18927ae0e2c9SDimitry Andric AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device); 18937ae0e2c9SDimitry Andric } 18947ae0e2c9SDimitry Andric 18957ae0e2c9SDimitry Andric return AddrSpace; 18967ae0e2c9SDimitry Andric } 18977ae0e2c9SDimitry Andric 1898284c1978SDimitry Andric template<typename SomeDecl> 1899284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 1900284c1978SDimitry Andric llvm::GlobalValue *GV) { 1901284c1978SDimitry Andric if (!getLangOpts().CPlusPlus) 1902284c1978SDimitry Andric return; 1903284c1978SDimitry Andric 1904284c1978SDimitry Andric // Must have 'used' attribute, or else inline assembly can't rely on 1905284c1978SDimitry Andric // the name existing. 1906284c1978SDimitry Andric if (!D->template hasAttr<UsedAttr>()) 1907284c1978SDimitry Andric return; 1908284c1978SDimitry Andric 1909284c1978SDimitry Andric // Must have internal linkage and an ordinary name. 1910f785676fSDimitry Andric if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 1911284c1978SDimitry Andric return; 1912284c1978SDimitry Andric 1913284c1978SDimitry Andric // Must be in an extern "C" context. Entities declared directly within 1914284c1978SDimitry Andric // a record are not extern "C" even if the record is in such a context. 1915f785676fSDimitry Andric const SomeDecl *First = D->getFirstDecl(); 1916284c1978SDimitry Andric if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 1917284c1978SDimitry Andric return; 1918284c1978SDimitry Andric 1919284c1978SDimitry Andric // OK, this is an internal linkage entity inside an extern "C" linkage 1920284c1978SDimitry Andric // specification. Make a note of that so we can give it the "expected" 1921284c1978SDimitry Andric // mangled name if nothing else is using that name. 1922284c1978SDimitry Andric std::pair<StaticExternCMap::iterator, bool> R = 1923284c1978SDimitry Andric StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 1924284c1978SDimitry Andric 1925284c1978SDimitry Andric // If we have multiple internal linkage entities with the same name 1926284c1978SDimitry Andric // in extern "C" regions, none of them gets that name. 1927284c1978SDimitry Andric if (!R.second) 192859d1ed5bSDimitry Andric R.first->second = nullptr; 1929284c1978SDimitry Andric } 1930284c1978SDimitry Andric 193139d628a0SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 193239d628a0SDimitry Andric if (!CGM.supportsCOMDAT()) 193339d628a0SDimitry Andric return false; 193439d628a0SDimitry Andric 193539d628a0SDimitry Andric if (D.hasAttr<SelectAnyAttr>()) 193639d628a0SDimitry Andric return true; 193739d628a0SDimitry Andric 193839d628a0SDimitry Andric GVALinkage Linkage; 193939d628a0SDimitry Andric if (auto *VD = dyn_cast<VarDecl>(&D)) 194039d628a0SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 194139d628a0SDimitry Andric else 194239d628a0SDimitry Andric Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 194339d628a0SDimitry Andric 194439d628a0SDimitry Andric switch (Linkage) { 194539d628a0SDimitry Andric case GVA_Internal: 194639d628a0SDimitry Andric case GVA_AvailableExternally: 194739d628a0SDimitry Andric case GVA_StrongExternal: 194839d628a0SDimitry Andric return false; 194939d628a0SDimitry Andric case GVA_DiscardableODR: 195039d628a0SDimitry Andric case GVA_StrongODR: 195139d628a0SDimitry Andric return true; 195239d628a0SDimitry Andric } 195339d628a0SDimitry Andric llvm_unreachable("No such linkage"); 195439d628a0SDimitry Andric } 195539d628a0SDimitry Andric 1956f22ef01cSRoman Divacky void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 195759d1ed5bSDimitry Andric llvm::Constant *Init = nullptr; 1958f22ef01cSRoman Divacky QualType ASTTy = D->getType(); 1959dff0c46cSDimitry Andric CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1960dff0c46cSDimitry Andric bool NeedsGlobalCtor = false; 1961dff0c46cSDimitry Andric bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 1962f22ef01cSRoman Divacky 1963dff0c46cSDimitry Andric const VarDecl *InitDecl; 1964dff0c46cSDimitry Andric const Expr *InitExpr = D->getAnyInitializer(InitDecl); 1965f22ef01cSRoman Divacky 1966f22ef01cSRoman Divacky if (!InitExpr) { 1967f22ef01cSRoman Divacky // This is a tentative definition; tentative definitions are 1968f22ef01cSRoman Divacky // implicitly initialized with { 0 }. 1969f22ef01cSRoman Divacky // 1970f22ef01cSRoman Divacky // Note that tentative definitions are only emitted at the end of 1971f22ef01cSRoman Divacky // a translation unit, so they should never have incomplete 1972f22ef01cSRoman Divacky // type. In addition, EmitTentativeDefinition makes sure that we 1973f22ef01cSRoman Divacky // never attempt to emit a tentative definition if a real one 1974f22ef01cSRoman Divacky // exists. A use may still exists, however, so we still may need 1975f22ef01cSRoman Divacky // to do a RAUW. 1976f22ef01cSRoman Divacky assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1977f22ef01cSRoman Divacky Init = EmitNullConstant(D->getType()); 1978f22ef01cSRoman Divacky } else { 19797ae0e2c9SDimitry Andric initializedGlobalDecl = GlobalDecl(D); 1980dff0c46cSDimitry Andric Init = EmitConstantInit(*InitDecl); 1981f785676fSDimitry Andric 1982f22ef01cSRoman Divacky if (!Init) { 1983f22ef01cSRoman Divacky QualType T = InitExpr->getType(); 1984f22ef01cSRoman Divacky if (D->getType()->isReferenceType()) 1985f22ef01cSRoman Divacky T = D->getType(); 1986f22ef01cSRoman Divacky 1987dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus) { 1988f22ef01cSRoman Divacky Init = EmitNullConstant(T); 1989dff0c46cSDimitry Andric NeedsGlobalCtor = true; 1990f22ef01cSRoman Divacky } else { 1991f22ef01cSRoman Divacky ErrorUnsupported(D, "static initializer"); 1992f22ef01cSRoman Divacky Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1993f22ef01cSRoman Divacky } 1994e580952dSDimitry Andric } else { 1995e580952dSDimitry Andric // We don't need an initializer, so remove the entry for the delayed 1996dff0c46cSDimitry Andric // initializer position (just in case this entry was delayed) if we 1997dff0c46cSDimitry Andric // also don't need to register a destructor. 1998dff0c46cSDimitry Andric if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 1999e580952dSDimitry Andric DelayedCXXInitPosition.erase(D); 2000f22ef01cSRoman Divacky } 2001f22ef01cSRoman Divacky } 2002f22ef01cSRoman Divacky 20036122f3e6SDimitry Andric llvm::Type* InitType = Init->getType(); 2004f22ef01cSRoman Divacky llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 2005f22ef01cSRoman Divacky 2006f22ef01cSRoman Divacky // Strip off a bitcast if we got one back. 200759d1ed5bSDimitry Andric if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 2008f22ef01cSRoman Divacky assert(CE->getOpcode() == llvm::Instruction::BitCast || 2009f785676fSDimitry Andric CE->getOpcode() == llvm::Instruction::AddrSpaceCast || 2010f785676fSDimitry Andric // All zero index gep. 2011f22ef01cSRoman Divacky CE->getOpcode() == llvm::Instruction::GetElementPtr); 2012f22ef01cSRoman Divacky Entry = CE->getOperand(0); 2013f22ef01cSRoman Divacky } 2014f22ef01cSRoman Divacky 2015f22ef01cSRoman Divacky // Entry is now either a Function or GlobalVariable. 201659d1ed5bSDimitry Andric auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 2017f22ef01cSRoman Divacky 2018f22ef01cSRoman Divacky // We have a definition after a declaration with the wrong type. 2019f22ef01cSRoman Divacky // We must make a new GlobalVariable* and update everything that used OldGV 2020f22ef01cSRoman Divacky // (a declaration or tentative definition) with the new GlobalVariable* 2021f22ef01cSRoman Divacky // (which will be a definition). 2022f22ef01cSRoman Divacky // 2023f22ef01cSRoman Divacky // This happens if there is a prototype for a global (e.g. 2024f22ef01cSRoman Divacky // "extern int x[];") and then a definition of a different type (e.g. 2025f22ef01cSRoman Divacky // "int x[10];"). This also happens when an initializer has a different type 2026f22ef01cSRoman Divacky // from the type of the global (this happens with unions). 202759d1ed5bSDimitry Andric if (!GV || 2028f22ef01cSRoman Divacky GV->getType()->getElementType() != InitType || 20293b0f4066SDimitry Andric GV->getType()->getAddressSpace() != 20307ae0e2c9SDimitry Andric GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) { 2031f22ef01cSRoman Divacky 2032f22ef01cSRoman Divacky // Move the old entry aside so that we'll create a new one. 20336122f3e6SDimitry Andric Entry->setName(StringRef()); 2034f22ef01cSRoman Divacky 2035f22ef01cSRoman Divacky // Make a new global with the correct type, this is now guaranteed to work. 2036f22ef01cSRoman Divacky GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 2037f22ef01cSRoman Divacky 2038f22ef01cSRoman Divacky // Replace all uses of the old global with the new global 2039f22ef01cSRoman Divacky llvm::Constant *NewPtrForOldDecl = 2040f22ef01cSRoman Divacky llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 2041f22ef01cSRoman Divacky Entry->replaceAllUsesWith(NewPtrForOldDecl); 2042f22ef01cSRoman Divacky 2043f22ef01cSRoman Divacky // Erase the old global, since it is no longer used. 2044f22ef01cSRoman Divacky cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 2045f22ef01cSRoman Divacky } 2046f22ef01cSRoman Divacky 2047284c1978SDimitry Andric MaybeHandleStaticInExternC(D, GV); 2048284c1978SDimitry Andric 20496122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 20506122f3e6SDimitry Andric AddGlobalAnnotations(D, GV); 2051f22ef01cSRoman Divacky 2052f22ef01cSRoman Divacky GV->setInitializer(Init); 2053f22ef01cSRoman Divacky 2054f22ef01cSRoman Divacky // If it is safe to mark the global 'constant', do so now. 2055dff0c46cSDimitry Andric GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 2056dff0c46cSDimitry Andric isTypeConstant(D->getType(), true)); 2057f22ef01cSRoman Divacky 205839d628a0SDimitry Andric // If it is in a read-only section, mark it 'constant'. 205939d628a0SDimitry Andric if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 206039d628a0SDimitry Andric const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 206139d628a0SDimitry Andric if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 206239d628a0SDimitry Andric GV->setConstant(true); 206339d628a0SDimitry Andric } 206439d628a0SDimitry Andric 2065f22ef01cSRoman Divacky GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 2066f22ef01cSRoman Divacky 2067f22ef01cSRoman Divacky // Set the llvm linkage type as appropriate. 20682754fe60SDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 206959d1ed5bSDimitry Andric getLLVMLinkageVarDefinition(D, GV->isConstant()); 2070f785676fSDimitry Andric 207159d1ed5bSDimitry Andric // On Darwin, the backing variable for a C++11 thread_local variable always 207259d1ed5bSDimitry Andric // has internal linkage; all accesses should just be calls to the 207359d1ed5bSDimitry Andric // Itanium-specified entry point, which has the normal linkage of the 207459d1ed5bSDimitry Andric // variable. 207539d628a0SDimitry Andric if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic && 207659d1ed5bSDimitry Andric Context.getTargetInfo().getTriple().isMacOSX()) 207759d1ed5bSDimitry Andric Linkage = llvm::GlobalValue::InternalLinkage; 207859d1ed5bSDimitry Andric 207959d1ed5bSDimitry Andric GV->setLinkage(Linkage); 208059d1ed5bSDimitry Andric if (D->hasAttr<DLLImportAttr>()) 208159d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 208259d1ed5bSDimitry Andric else if (D->hasAttr<DLLExportAttr>()) 208359d1ed5bSDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 208439d628a0SDimitry Andric else 208539d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 2086f785676fSDimitry Andric 20872754fe60SDimitry Andric if (Linkage == llvm::GlobalVariable::CommonLinkage) 2088f22ef01cSRoman Divacky // common vars aren't constant even if declared const. 2089f22ef01cSRoman Divacky GV->setConstant(false); 2090f22ef01cSRoman Divacky 209159d1ed5bSDimitry Andric setNonAliasAttributes(D, GV); 2092f22ef01cSRoman Divacky 209339d628a0SDimitry Andric if (D->getTLSKind() && !GV->isThreadLocal()) { 209439d628a0SDimitry Andric if (D->getTLSKind() == VarDecl::TLS_Dynamic) 209539d628a0SDimitry Andric CXXThreadLocals.push_back(std::make_pair(D, GV)); 209639d628a0SDimitry Andric setTLSMode(GV, *D); 209739d628a0SDimitry Andric } 209839d628a0SDimitry Andric 209939d628a0SDimitry Andric if (shouldBeInCOMDAT(*this, *D)) 210039d628a0SDimitry Andric GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 210139d628a0SDimitry Andric 21022754fe60SDimitry Andric // Emit the initializer function if necessary. 2103dff0c46cSDimitry Andric if (NeedsGlobalCtor || NeedsGlobalDtor) 2104dff0c46cSDimitry Andric EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 21052754fe60SDimitry Andric 210639d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 21073861d79fSDimitry Andric 2108f22ef01cSRoman Divacky // Emit global variable debug information. 21096122f3e6SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 21103861d79fSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 2111f22ef01cSRoman Divacky DI->EmitGlobalVariable(GV, D); 2112f22ef01cSRoman Divacky } 2113f22ef01cSRoman Divacky 211439d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context, 211539d628a0SDimitry Andric const VarDecl *D, bool NoCommon) { 211659d1ed5bSDimitry Andric // Don't give variables common linkage if -fno-common was specified unless it 211759d1ed5bSDimitry Andric // was overridden by a NoCommon attribute. 211859d1ed5bSDimitry Andric if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 211959d1ed5bSDimitry Andric return true; 212059d1ed5bSDimitry Andric 212159d1ed5bSDimitry Andric // C11 6.9.2/2: 212259d1ed5bSDimitry Andric // A declaration of an identifier for an object that has file scope without 212359d1ed5bSDimitry Andric // an initializer, and without a storage-class specifier or with the 212459d1ed5bSDimitry Andric // storage-class specifier static, constitutes a tentative definition. 212559d1ed5bSDimitry Andric if (D->getInit() || D->hasExternalStorage()) 212659d1ed5bSDimitry Andric return true; 212759d1ed5bSDimitry Andric 212859d1ed5bSDimitry Andric // A variable cannot be both common and exist in a section. 212959d1ed5bSDimitry Andric if (D->hasAttr<SectionAttr>()) 213059d1ed5bSDimitry Andric return true; 213159d1ed5bSDimitry Andric 213259d1ed5bSDimitry Andric // Thread local vars aren't considered common linkage. 213359d1ed5bSDimitry Andric if (D->getTLSKind()) 213459d1ed5bSDimitry Andric return true; 213559d1ed5bSDimitry Andric 213659d1ed5bSDimitry Andric // Tentative definitions marked with WeakImportAttr are true definitions. 213759d1ed5bSDimitry Andric if (D->hasAttr<WeakImportAttr>()) 213859d1ed5bSDimitry Andric return true; 213959d1ed5bSDimitry Andric 214039d628a0SDimitry Andric // Declarations with a required alignment do not have common linakge in MSVC 214139d628a0SDimitry Andric // mode. 214239d628a0SDimitry Andric if (Context.getLangOpts().MSVCCompat && 214339d628a0SDimitry Andric (Context.isAlignmentRequired(D->getType()) || D->hasAttr<AlignedAttr>())) 214439d628a0SDimitry Andric return true; 214539d628a0SDimitry Andric 214659d1ed5bSDimitry Andric return false; 214759d1ed5bSDimitry Andric } 214859d1ed5bSDimitry Andric 214959d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 215059d1ed5bSDimitry Andric const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 21512754fe60SDimitry Andric if (Linkage == GVA_Internal) 21522754fe60SDimitry Andric return llvm::Function::InternalLinkage; 215359d1ed5bSDimitry Andric 215459d1ed5bSDimitry Andric if (D->hasAttr<WeakAttr>()) { 215559d1ed5bSDimitry Andric if (IsConstantVariable) 215659d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 215759d1ed5bSDimitry Andric else 215859d1ed5bSDimitry Andric return llvm::GlobalVariable::WeakAnyLinkage; 215959d1ed5bSDimitry Andric } 216059d1ed5bSDimitry Andric 216159d1ed5bSDimitry Andric // We are guaranteed to have a strong definition somewhere else, 216259d1ed5bSDimitry Andric // so we can use available_externally linkage. 216359d1ed5bSDimitry Andric if (Linkage == GVA_AvailableExternally) 216459d1ed5bSDimitry Andric return llvm::Function::AvailableExternallyLinkage; 216559d1ed5bSDimitry Andric 216659d1ed5bSDimitry Andric // Note that Apple's kernel linker doesn't support symbol 216759d1ed5bSDimitry Andric // coalescing, so we need to avoid linkonce and weak linkages there. 216859d1ed5bSDimitry Andric // Normally, this means we just map to internal, but for explicit 216959d1ed5bSDimitry Andric // instantiations we'll map to external. 217059d1ed5bSDimitry Andric 217159d1ed5bSDimitry Andric // In C++, the compiler has to emit a definition in every translation unit 217259d1ed5bSDimitry Andric // that references the function. We should use linkonce_odr because 217359d1ed5bSDimitry Andric // a) if all references in this translation unit are optimized away, we 217459d1ed5bSDimitry Andric // don't need to codegen it. b) if the function persists, it needs to be 217559d1ed5bSDimitry Andric // merged with other definitions. c) C++ has the ODR, so we know the 217659d1ed5bSDimitry Andric // definition is dependable. 217759d1ed5bSDimitry Andric if (Linkage == GVA_DiscardableODR) 217859d1ed5bSDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 217959d1ed5bSDimitry Andric : llvm::Function::InternalLinkage; 218059d1ed5bSDimitry Andric 218159d1ed5bSDimitry Andric // An explicit instantiation of a template has weak linkage, since 218259d1ed5bSDimitry Andric // explicit instantiations can occur in multiple translation units 218359d1ed5bSDimitry Andric // and must all be equivalent. However, we are not allowed to 218459d1ed5bSDimitry Andric // throw away these explicit instantiations. 218559d1ed5bSDimitry Andric if (Linkage == GVA_StrongODR) 218659d1ed5bSDimitry Andric return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage 218759d1ed5bSDimitry Andric : llvm::Function::ExternalLinkage; 218859d1ed5bSDimitry Andric 218959d1ed5bSDimitry Andric // C++ doesn't have tentative definitions and thus cannot have common 219059d1ed5bSDimitry Andric // linkage. 219159d1ed5bSDimitry Andric if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 219239d628a0SDimitry Andric !isVarDeclStrongDefinition(Context, cast<VarDecl>(D), 219339d628a0SDimitry Andric CodeGenOpts.NoCommon)) 219459d1ed5bSDimitry Andric return llvm::GlobalVariable::CommonLinkage; 219559d1ed5bSDimitry Andric 2196f785676fSDimitry Andric // selectany symbols are externally visible, so use weak instead of 2197f785676fSDimitry Andric // linkonce. MSVC optimizes away references to const selectany globals, so 2198f785676fSDimitry Andric // all definitions should be the same and ODR linkage should be used. 2199f785676fSDimitry Andric // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 220059d1ed5bSDimitry Andric if (D->hasAttr<SelectAnyAttr>()) 2201f785676fSDimitry Andric return llvm::GlobalVariable::WeakODRLinkage; 220259d1ed5bSDimitry Andric 220359d1ed5bSDimitry Andric // Otherwise, we have strong external linkage. 220459d1ed5bSDimitry Andric assert(Linkage == GVA_StrongExternal); 22052754fe60SDimitry Andric return llvm::GlobalVariable::ExternalLinkage; 22062754fe60SDimitry Andric } 22072754fe60SDimitry Andric 220859d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 220959d1ed5bSDimitry Andric const VarDecl *VD, bool IsConstant) { 221059d1ed5bSDimitry Andric GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 221159d1ed5bSDimitry Andric return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 221259d1ed5bSDimitry Andric } 221359d1ed5bSDimitry Andric 2214139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type. 2215139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites 2216139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 2217139f7f9bSDimitry Andric llvm::Function *newFn) { 2218139f7f9bSDimitry Andric // Fast path. 2219139f7f9bSDimitry Andric if (old->use_empty()) return; 2220139f7f9bSDimitry Andric 2221139f7f9bSDimitry Andric llvm::Type *newRetTy = newFn->getReturnType(); 2222139f7f9bSDimitry Andric SmallVector<llvm::Value*, 4> newArgs; 2223139f7f9bSDimitry Andric 2224139f7f9bSDimitry Andric for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 2225139f7f9bSDimitry Andric ui != ue; ) { 2226139f7f9bSDimitry Andric llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 222759d1ed5bSDimitry Andric llvm::User *user = use->getUser(); 2228139f7f9bSDimitry Andric 2229139f7f9bSDimitry Andric // Recognize and replace uses of bitcasts. Most calls to 2230139f7f9bSDimitry Andric // unprototyped functions will use bitcasts. 223159d1ed5bSDimitry Andric if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 2232139f7f9bSDimitry Andric if (bitcast->getOpcode() == llvm::Instruction::BitCast) 2233139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(bitcast, newFn); 2234139f7f9bSDimitry Andric continue; 2235139f7f9bSDimitry Andric } 2236139f7f9bSDimitry Andric 2237139f7f9bSDimitry Andric // Recognize calls to the function. 2238139f7f9bSDimitry Andric llvm::CallSite callSite(user); 2239139f7f9bSDimitry Andric if (!callSite) continue; 224059d1ed5bSDimitry Andric if (!callSite.isCallee(&*use)) continue; 2241139f7f9bSDimitry Andric 2242139f7f9bSDimitry Andric // If the return types don't match exactly, then we can't 2243139f7f9bSDimitry Andric // transform this call unless it's dead. 2244139f7f9bSDimitry Andric if (callSite->getType() != newRetTy && !callSite->use_empty()) 2245139f7f9bSDimitry Andric continue; 2246139f7f9bSDimitry Andric 2247139f7f9bSDimitry Andric // Get the call site's attribute list. 2248139f7f9bSDimitry Andric SmallVector<llvm::AttributeSet, 8> newAttrs; 2249139f7f9bSDimitry Andric llvm::AttributeSet oldAttrs = callSite.getAttributes(); 2250139f7f9bSDimitry Andric 2251139f7f9bSDimitry Andric // Collect any return attributes from the call. 2252139f7f9bSDimitry Andric if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex)) 2253139f7f9bSDimitry Andric newAttrs.push_back( 2254139f7f9bSDimitry Andric llvm::AttributeSet::get(newFn->getContext(), 2255139f7f9bSDimitry Andric oldAttrs.getRetAttributes())); 2256139f7f9bSDimitry Andric 2257139f7f9bSDimitry Andric // If the function was passed too few arguments, don't transform. 2258139f7f9bSDimitry Andric unsigned newNumArgs = newFn->arg_size(); 2259139f7f9bSDimitry Andric if (callSite.arg_size() < newNumArgs) continue; 2260139f7f9bSDimitry Andric 2261139f7f9bSDimitry Andric // If extra arguments were passed, we silently drop them. 2262139f7f9bSDimitry Andric // If any of the types mismatch, we don't transform. 2263139f7f9bSDimitry Andric unsigned argNo = 0; 2264139f7f9bSDimitry Andric bool dontTransform = false; 2265139f7f9bSDimitry Andric for (llvm::Function::arg_iterator ai = newFn->arg_begin(), 2266139f7f9bSDimitry Andric ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) { 2267139f7f9bSDimitry Andric if (callSite.getArgument(argNo)->getType() != ai->getType()) { 2268139f7f9bSDimitry Andric dontTransform = true; 2269139f7f9bSDimitry Andric break; 2270139f7f9bSDimitry Andric } 2271139f7f9bSDimitry Andric 2272139f7f9bSDimitry Andric // Add any parameter attributes. 2273139f7f9bSDimitry Andric if (oldAttrs.hasAttributes(argNo + 1)) 2274139f7f9bSDimitry Andric newAttrs. 2275139f7f9bSDimitry Andric push_back(llvm:: 2276139f7f9bSDimitry Andric AttributeSet::get(newFn->getContext(), 2277139f7f9bSDimitry Andric oldAttrs.getParamAttributes(argNo + 1))); 2278139f7f9bSDimitry Andric } 2279139f7f9bSDimitry Andric if (dontTransform) 2280139f7f9bSDimitry Andric continue; 2281139f7f9bSDimitry Andric 2282139f7f9bSDimitry Andric if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) 2283139f7f9bSDimitry Andric newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(), 2284139f7f9bSDimitry Andric oldAttrs.getFnAttributes())); 2285139f7f9bSDimitry Andric 2286139f7f9bSDimitry Andric // Okay, we can transform this. Create the new call instruction and copy 2287139f7f9bSDimitry Andric // over the required information. 2288139f7f9bSDimitry Andric newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo); 2289139f7f9bSDimitry Andric 2290139f7f9bSDimitry Andric llvm::CallSite newCall; 2291139f7f9bSDimitry Andric if (callSite.isCall()) { 2292139f7f9bSDimitry Andric newCall = llvm::CallInst::Create(newFn, newArgs, "", 2293139f7f9bSDimitry Andric callSite.getInstruction()); 2294139f7f9bSDimitry Andric } else { 229559d1ed5bSDimitry Andric auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction()); 2296139f7f9bSDimitry Andric newCall = llvm::InvokeInst::Create(newFn, 2297139f7f9bSDimitry Andric oldInvoke->getNormalDest(), 2298139f7f9bSDimitry Andric oldInvoke->getUnwindDest(), 2299139f7f9bSDimitry Andric newArgs, "", 2300139f7f9bSDimitry Andric callSite.getInstruction()); 2301139f7f9bSDimitry Andric } 2302139f7f9bSDimitry Andric newArgs.clear(); // for the next iteration 2303139f7f9bSDimitry Andric 2304139f7f9bSDimitry Andric if (!newCall->getType()->isVoidTy()) 2305139f7f9bSDimitry Andric newCall->takeName(callSite.getInstruction()); 2306139f7f9bSDimitry Andric newCall.setAttributes( 2307139f7f9bSDimitry Andric llvm::AttributeSet::get(newFn->getContext(), newAttrs)); 2308139f7f9bSDimitry Andric newCall.setCallingConv(callSite.getCallingConv()); 2309139f7f9bSDimitry Andric 2310139f7f9bSDimitry Andric // Finally, remove the old call, replacing any uses with the new one. 2311139f7f9bSDimitry Andric if (!callSite->use_empty()) 2312139f7f9bSDimitry Andric callSite->replaceAllUsesWith(newCall.getInstruction()); 2313139f7f9bSDimitry Andric 2314139f7f9bSDimitry Andric // Copy debug location attached to CI. 2315139f7f9bSDimitry Andric if (!callSite->getDebugLoc().isUnknown()) 2316139f7f9bSDimitry Andric newCall->setDebugLoc(callSite->getDebugLoc()); 2317139f7f9bSDimitry Andric callSite->eraseFromParent(); 2318139f7f9bSDimitry Andric } 2319139f7f9bSDimitry Andric } 2320139f7f9bSDimitry Andric 2321f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 2322f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}". If there are 2323f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to 2324f22ef01cSRoman Divacky /// call the new function directly. 2325f22ef01cSRoman Divacky /// 2326f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to 2327f22ef01cSRoman Divacky /// functions to be able to inline them. If there is a bitcast in the way, it 2328f22ef01cSRoman Divacky /// won't inline them. Instcombine normally deletes these calls, but it isn't 2329f22ef01cSRoman Divacky /// run at -O0. 2330f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 2331f22ef01cSRoman Divacky llvm::Function *NewFn) { 2332f22ef01cSRoman Divacky // If we're redefining a global as a function, don't transform it. 2333139f7f9bSDimitry Andric if (!isa<llvm::Function>(Old)) return; 2334f22ef01cSRoman Divacky 2335139f7f9bSDimitry Andric replaceUsesOfNonProtoConstant(Old, NewFn); 2336f22ef01cSRoman Divacky } 2337f22ef01cSRoman Divacky 2338dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 2339dff0c46cSDimitry Andric TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 2340dff0c46cSDimitry Andric // If we have a definition, this might be a deferred decl. If the 2341dff0c46cSDimitry Andric // instantiation is explicit, make sure we emit it at the end. 2342dff0c46cSDimitry Andric if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 2343dff0c46cSDimitry Andric GetAddrOfGlobalVar(VD); 2344139f7f9bSDimitry Andric 2345139f7f9bSDimitry Andric EmitTopLevelDecl(VD); 2346dff0c46cSDimitry Andric } 2347f22ef01cSRoman Divacky 234859d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 234959d1ed5bSDimitry Andric llvm::GlobalValue *GV) { 235059d1ed5bSDimitry Andric const auto *D = cast<FunctionDecl>(GD.getDecl()); 23513b0f4066SDimitry Andric 23523b0f4066SDimitry Andric // Compute the function info and LLVM type. 2353dff0c46cSDimitry Andric const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2354dff0c46cSDimitry Andric llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 23553b0f4066SDimitry Andric 2356f22ef01cSRoman Divacky // Get or create the prototype for the function. 235759d1ed5bSDimitry Andric if (!GV) { 235859d1ed5bSDimitry Andric llvm::Constant *C = 235959d1ed5bSDimitry Andric GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true); 2360f22ef01cSRoman Divacky 2361f22ef01cSRoman Divacky // Strip off a bitcast if we got one back. 236259d1ed5bSDimitry Andric if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) { 2363f22ef01cSRoman Divacky assert(CE->getOpcode() == llvm::Instruction::BitCast); 236459d1ed5bSDimitry Andric GV = cast<llvm::GlobalValue>(CE->getOperand(0)); 236559d1ed5bSDimitry Andric } else { 236659d1ed5bSDimitry Andric GV = cast<llvm::GlobalValue>(C); 236759d1ed5bSDimitry Andric } 2368f22ef01cSRoman Divacky } 2369f22ef01cSRoman Divacky 237059d1ed5bSDimitry Andric if (!GV->isDeclaration()) { 2371f785676fSDimitry Andric getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name); 237239d628a0SDimitry Andric GlobalDecl OldGD = Manglings.lookup(GV->getName()); 237339d628a0SDimitry Andric if (auto *Prev = OldGD.getDecl()) 237439d628a0SDimitry Andric getDiags().Report(Prev->getLocation(), diag::note_previous_definition); 2375f785676fSDimitry Andric return; 2376f785676fSDimitry Andric } 2377f22ef01cSRoman Divacky 237859d1ed5bSDimitry Andric if (GV->getType()->getElementType() != Ty) { 2379f22ef01cSRoman Divacky // If the types mismatch then we have to rewrite the definition. 238059d1ed5bSDimitry Andric assert(GV->isDeclaration() && "Shouldn't replace non-declaration"); 2381f22ef01cSRoman Divacky 2382f22ef01cSRoman Divacky // F is the Function* for the one with the wrong type, we must make a new 2383f22ef01cSRoman Divacky // Function* and update everything that used F (a declaration) with the new 2384f22ef01cSRoman Divacky // Function* (which will be a definition). 2385f22ef01cSRoman Divacky // 2386f22ef01cSRoman Divacky // This happens if there is a prototype for a function 2387f22ef01cSRoman Divacky // (e.g. "int f()") and then a definition of a different type 2388f22ef01cSRoman Divacky // (e.g. "int f(int x)"). Move the old function aside so that it 2389f22ef01cSRoman Divacky // doesn't interfere with GetAddrOfFunction. 239059d1ed5bSDimitry Andric GV->setName(StringRef()); 239159d1ed5bSDimitry Andric auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 2392f22ef01cSRoman Divacky 2393139f7f9bSDimitry Andric // This might be an implementation of a function without a 2394139f7f9bSDimitry Andric // prototype, in which case, try to do special replacement of 2395139f7f9bSDimitry Andric // calls which match the new prototype. The really key thing here 2396139f7f9bSDimitry Andric // is that we also potentially drop arguments from the call site 2397139f7f9bSDimitry Andric // so as to make a direct call, which makes the inliner happier 2398139f7f9bSDimitry Andric // and suppresses a number of optimizer warnings (!) about 2399139f7f9bSDimitry Andric // dropping arguments. 240059d1ed5bSDimitry Andric if (!GV->use_empty()) { 240159d1ed5bSDimitry Andric ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn); 240259d1ed5bSDimitry Andric GV->removeDeadConstantUsers(); 2403f22ef01cSRoman Divacky } 2404f22ef01cSRoman Divacky 2405f22ef01cSRoman Divacky // Replace uses of F with the Function we will endow with a body. 240659d1ed5bSDimitry Andric if (!GV->use_empty()) { 2407f22ef01cSRoman Divacky llvm::Constant *NewPtrForOldDecl = 240859d1ed5bSDimitry Andric llvm::ConstantExpr::getBitCast(NewFn, GV->getType()); 240959d1ed5bSDimitry Andric GV->replaceAllUsesWith(NewPtrForOldDecl); 2410f22ef01cSRoman Divacky } 2411f22ef01cSRoman Divacky 2412f22ef01cSRoman Divacky // Ok, delete the old function now, which is dead. 241359d1ed5bSDimitry Andric GV->eraseFromParent(); 2414f22ef01cSRoman Divacky 241559d1ed5bSDimitry Andric GV = NewFn; 2416f22ef01cSRoman Divacky } 2417f22ef01cSRoman Divacky 24182754fe60SDimitry Andric // We need to set linkage and visibility on the function before 24192754fe60SDimitry Andric // generating code for it because various parts of IR generation 24202754fe60SDimitry Andric // want to propagate this information down (e.g. to local static 24212754fe60SDimitry Andric // declarations). 242259d1ed5bSDimitry Andric auto *Fn = cast<llvm::Function>(GV); 2423f785676fSDimitry Andric setFunctionLinkage(GD, Fn); 242439d628a0SDimitry Andric if (D->hasAttr<DLLImportAttr>()) 242539d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 242639d628a0SDimitry Andric else if (D->hasAttr<DLLExportAttr>()) 242739d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 242839d628a0SDimitry Andric else 242939d628a0SDimitry Andric GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 2430f22ef01cSRoman Divacky 243159d1ed5bSDimitry Andric // FIXME: this is redundant with part of setFunctionDefinitionAttributes 24322754fe60SDimitry Andric setGlobalVisibility(Fn, D); 24332754fe60SDimitry Andric 2434284c1978SDimitry Andric MaybeHandleStaticInExternC(D, Fn); 2435284c1978SDimitry Andric 243639d628a0SDimitry Andric if (shouldBeInCOMDAT(*this, *D)) 243739d628a0SDimitry Andric Fn->setComdat(TheModule.getOrInsertComdat(Fn->getName())); 243839d628a0SDimitry Andric 24393b0f4066SDimitry Andric CodeGenFunction(*this).GenerateCode(D, Fn, FI); 2440f22ef01cSRoman Divacky 244159d1ed5bSDimitry Andric setFunctionDefinitionAttributes(D, Fn); 2442f22ef01cSRoman Divacky SetLLVMFunctionAttributesForDefinition(D, Fn); 2443f22ef01cSRoman Divacky 2444f22ef01cSRoman Divacky if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 2445f22ef01cSRoman Divacky AddGlobalCtor(Fn, CA->getPriority()); 2446f22ef01cSRoman Divacky if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 2447f22ef01cSRoman Divacky AddGlobalDtor(Fn, DA->getPriority()); 24486122f3e6SDimitry Andric if (D->hasAttr<AnnotateAttr>()) 24496122f3e6SDimitry Andric AddGlobalAnnotations(D, Fn); 2450f22ef01cSRoman Divacky } 2451f22ef01cSRoman Divacky 2452f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 245359d1ed5bSDimitry Andric const auto *D = cast<ValueDecl>(GD.getDecl()); 2454f22ef01cSRoman Divacky const AliasAttr *AA = D->getAttr<AliasAttr>(); 2455f22ef01cSRoman Divacky assert(AA && "Not an alias?"); 2456f22ef01cSRoman Divacky 24576122f3e6SDimitry Andric StringRef MangledName = getMangledName(GD); 2458f22ef01cSRoman Divacky 2459f22ef01cSRoman Divacky // If there is a definition in the module, then it wins over the alias. 2460f22ef01cSRoman Divacky // This is dubious, but allow it to be safe. Just ignore the alias. 2461f22ef01cSRoman Divacky llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 2462f22ef01cSRoman Divacky if (Entry && !Entry->isDeclaration()) 2463f22ef01cSRoman Divacky return; 2464f22ef01cSRoman Divacky 2465f785676fSDimitry Andric Aliases.push_back(GD); 2466f785676fSDimitry Andric 24676122f3e6SDimitry Andric llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 2468f22ef01cSRoman Divacky 2469f22ef01cSRoman Divacky // Create a reference to the named value. This ensures that it is emitted 2470f22ef01cSRoman Divacky // if a deferred decl. 2471f22ef01cSRoman Divacky llvm::Constant *Aliasee; 2472f22ef01cSRoman Divacky if (isa<llvm::FunctionType>(DeclTy)) 24733861d79fSDimitry Andric Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 24742754fe60SDimitry Andric /*ForVTable=*/false); 2475f22ef01cSRoman Divacky else 2476f22ef01cSRoman Divacky Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 247759d1ed5bSDimitry Andric llvm::PointerType::getUnqual(DeclTy), 247839d628a0SDimitry Andric /*D=*/nullptr); 2479f22ef01cSRoman Divacky 2480f22ef01cSRoman Divacky // Create the new alias itself, but don't set a name yet. 248159d1ed5bSDimitry Andric auto *GA = llvm::GlobalAlias::create( 248259d1ed5bSDimitry Andric cast<llvm::PointerType>(Aliasee->getType())->getElementType(), 0, 248359d1ed5bSDimitry Andric llvm::Function::ExternalLinkage, "", Aliasee, &getModule()); 2484f22ef01cSRoman Divacky 2485f22ef01cSRoman Divacky if (Entry) { 248659d1ed5bSDimitry Andric if (GA->getAliasee() == Entry) { 248759d1ed5bSDimitry Andric Diags.Report(AA->getLocation(), diag::err_cyclic_alias); 248859d1ed5bSDimitry Andric return; 248959d1ed5bSDimitry Andric } 249059d1ed5bSDimitry Andric 2491f22ef01cSRoman Divacky assert(Entry->isDeclaration()); 2492f22ef01cSRoman Divacky 2493f22ef01cSRoman Divacky // If there is a declaration in the module, then we had an extern followed 2494f22ef01cSRoman Divacky // by the alias, as in: 2495f22ef01cSRoman Divacky // extern int test6(); 2496f22ef01cSRoman Divacky // ... 2497f22ef01cSRoman Divacky // int test6() __attribute__((alias("test7"))); 2498f22ef01cSRoman Divacky // 2499f22ef01cSRoman Divacky // Remove it and replace uses of it with the alias. 2500f22ef01cSRoman Divacky GA->takeName(Entry); 2501f22ef01cSRoman Divacky 2502f22ef01cSRoman Divacky Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 2503f22ef01cSRoman Divacky Entry->getType())); 2504f22ef01cSRoman Divacky Entry->eraseFromParent(); 2505f22ef01cSRoman Divacky } else { 2506ffd1746dSEd Schouten GA->setName(MangledName); 2507f22ef01cSRoman Divacky } 2508f22ef01cSRoman Divacky 2509f22ef01cSRoman Divacky // Set attributes which are particular to an alias; this is a 2510f22ef01cSRoman Divacky // specialization of the attributes which may be set on a global 2511f22ef01cSRoman Divacky // variable/function. 251239d628a0SDimitry Andric if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 25133b0f4066SDimitry Andric D->isWeakImported()) { 2514f22ef01cSRoman Divacky GA->setLinkage(llvm::Function::WeakAnyLinkage); 2515f22ef01cSRoman Divacky } 2516f22ef01cSRoman Divacky 251739d628a0SDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(D)) 251839d628a0SDimitry Andric if (VD->getTLSKind()) 251939d628a0SDimitry Andric setTLSMode(GA, *VD); 252039d628a0SDimitry Andric 252139d628a0SDimitry Andric setAliasAttributes(D, GA); 2522f22ef01cSRoman Divacky } 2523f22ef01cSRoman Divacky 252417a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 25256122f3e6SDimitry Andric ArrayRef<llvm::Type*> Tys) { 252617a519f9SDimitry Andric return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 252717a519f9SDimitry Andric Tys); 2528f22ef01cSRoman Divacky } 2529f22ef01cSRoman Divacky 2530f22ef01cSRoman Divacky static llvm::StringMapEntry<llvm::Constant*> & 2531f22ef01cSRoman Divacky GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2532f22ef01cSRoman Divacky const StringLiteral *Literal, 2533f22ef01cSRoman Divacky bool TargetIsLSB, 2534f22ef01cSRoman Divacky bool &IsUTF16, 2535f22ef01cSRoman Divacky unsigned &StringLength) { 25366122f3e6SDimitry Andric StringRef String = Literal->getString(); 2537e580952dSDimitry Andric unsigned NumBytes = String.size(); 2538f22ef01cSRoman Divacky 2539f22ef01cSRoman Divacky // Check for simple case. 2540f22ef01cSRoman Divacky if (!Literal->containsNonAsciiOrNull()) { 2541f22ef01cSRoman Divacky StringLength = NumBytes; 254239d628a0SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 2543f22ef01cSRoman Divacky } 2544f22ef01cSRoman Divacky 2545dff0c46cSDimitry Andric // Otherwise, convert the UTF8 literals into a string of shorts. 2546dff0c46cSDimitry Andric IsUTF16 = true; 2547dff0c46cSDimitry Andric 2548dff0c46cSDimitry Andric SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 25493861d79fSDimitry Andric const UTF8 *FromPtr = (const UTF8 *)String.data(); 2550f22ef01cSRoman Divacky UTF16 *ToPtr = &ToBuf[0]; 2551f22ef01cSRoman Divacky 25522754fe60SDimitry Andric (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 2553f22ef01cSRoman Divacky &ToPtr, ToPtr + NumBytes, 2554f22ef01cSRoman Divacky strictConversion); 2555f22ef01cSRoman Divacky 2556f22ef01cSRoman Divacky // ConvertUTF8toUTF16 returns the length in ToPtr. 2557f22ef01cSRoman Divacky StringLength = ToPtr - &ToBuf[0]; 2558f22ef01cSRoman Divacky 2559dff0c46cSDimitry Andric // Add an explicit null. 2560dff0c46cSDimitry Andric *ToPtr = 0; 256139d628a0SDimitry Andric return *Map.insert(std::make_pair( 256239d628a0SDimitry Andric StringRef(reinterpret_cast<const char *>(ToBuf.data()), 256339d628a0SDimitry Andric (StringLength + 1) * 2), 256439d628a0SDimitry Andric nullptr)).first; 2565f22ef01cSRoman Divacky } 2566f22ef01cSRoman Divacky 2567bd5abe19SDimitry Andric static llvm::StringMapEntry<llvm::Constant*> & 2568bd5abe19SDimitry Andric GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map, 2569bd5abe19SDimitry Andric const StringLiteral *Literal, 2570dff0c46cSDimitry Andric unsigned &StringLength) { 25716122f3e6SDimitry Andric StringRef String = Literal->getString(); 2572bd5abe19SDimitry Andric StringLength = String.size(); 257339d628a0SDimitry Andric return *Map.insert(std::make_pair(String, nullptr)).first; 2574bd5abe19SDimitry Andric } 2575bd5abe19SDimitry Andric 2576f22ef01cSRoman Divacky llvm::Constant * 2577f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 2578f22ef01cSRoman Divacky unsigned StringLength = 0; 2579f22ef01cSRoman Divacky bool isUTF16 = false; 2580f22ef01cSRoman Divacky llvm::StringMapEntry<llvm::Constant*> &Entry = 2581f22ef01cSRoman Divacky GetConstantCFStringEntry(CFConstantStringMap, Literal, 25823861d79fSDimitry Andric getDataLayout().isLittleEndian(), 2583f22ef01cSRoman Divacky isUTF16, StringLength); 2584f22ef01cSRoman Divacky 258539d628a0SDimitry Andric if (auto *C = Entry.second) 2586f22ef01cSRoman Divacky return C; 2587f22ef01cSRoman Divacky 2588dff0c46cSDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2589f22ef01cSRoman Divacky llvm::Constant *Zeros[] = { Zero, Zero }; 2590284c1978SDimitry Andric llvm::Value *V; 2591f22ef01cSRoman Divacky 2592f22ef01cSRoman Divacky // If we don't already have it, get __CFConstantStringClassReference. 2593f22ef01cSRoman Divacky if (!CFConstantStringClassRef) { 25946122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 2595f22ef01cSRoman Divacky Ty = llvm::ArrayType::get(Ty, 0); 2596f22ef01cSRoman Divacky llvm::Constant *GV = CreateRuntimeVariable(Ty, 2597f22ef01cSRoman Divacky "__CFConstantStringClassReference"); 2598f22ef01cSRoman Divacky // Decay array -> ptr 2599284c1978SDimitry Andric V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2600284c1978SDimitry Andric CFConstantStringClassRef = V; 2601f22ef01cSRoman Divacky } 2602284c1978SDimitry Andric else 2603284c1978SDimitry Andric V = CFConstantStringClassRef; 2604f22ef01cSRoman Divacky 2605f22ef01cSRoman Divacky QualType CFTy = getContext().getCFConstantStringType(); 2606f22ef01cSRoman Divacky 260759d1ed5bSDimitry Andric auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 2608f22ef01cSRoman Divacky 2609dff0c46cSDimitry Andric llvm::Constant *Fields[4]; 2610f22ef01cSRoman Divacky 2611f22ef01cSRoman Divacky // Class pointer. 2612284c1978SDimitry Andric Fields[0] = cast<llvm::ConstantExpr>(V); 2613f22ef01cSRoman Divacky 2614f22ef01cSRoman Divacky // Flags. 26156122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2616f22ef01cSRoman Divacky Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 2617f22ef01cSRoman Divacky llvm::ConstantInt::get(Ty, 0x07C8); 2618f22ef01cSRoman Divacky 2619f22ef01cSRoman Divacky // String pointer. 262059d1ed5bSDimitry Andric llvm::Constant *C = nullptr; 2621dff0c46cSDimitry Andric if (isUTF16) { 262239d628a0SDimitry Andric ArrayRef<uint16_t> Arr = llvm::makeArrayRef<uint16_t>( 262339d628a0SDimitry Andric reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 262439d628a0SDimitry Andric Entry.first().size() / 2); 2625dff0c46cSDimitry Andric C = llvm::ConstantDataArray::get(VMContext, Arr); 2626dff0c46cSDimitry Andric } else { 262739d628a0SDimitry Andric C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 2628dff0c46cSDimitry Andric } 2629f22ef01cSRoman Divacky 2630dff0c46cSDimitry Andric // Note: -fwritable-strings doesn't make the backing store strings of 2631dff0c46cSDimitry Andric // CFStrings writable. (See <rdar://problem/10657500>) 263259d1ed5bSDimitry Andric auto *GV = 2633dff0c46cSDimitry Andric new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 263459d1ed5bSDimitry Andric llvm::GlobalValue::PrivateLinkage, C, ".str"); 26352754fe60SDimitry Andric GV->setUnnamedAddr(true); 2636284c1978SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 2637284c1978SDimitry Andric // of the string is via this class initializer. 263859d1ed5bSDimitry Andric // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without 263959d1ed5bSDimitry Andric // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing 264059d1ed5bSDimitry Andric // that changes the section it ends in, which surprises ld64. 2641f22ef01cSRoman Divacky if (isUTF16) { 2642f22ef01cSRoman Divacky CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 2643f22ef01cSRoman Divacky GV->setAlignment(Align.getQuantity()); 264459d1ed5bSDimitry Andric GV->setSection("__TEXT,__ustring"); 26453b0f4066SDimitry Andric } else { 26463b0f4066SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 26473b0f4066SDimitry Andric GV->setAlignment(Align.getQuantity()); 264859d1ed5bSDimitry Andric GV->setSection("__TEXT,__cstring,cstring_literals"); 2649f22ef01cSRoman Divacky } 2650dff0c46cSDimitry Andric 2651dff0c46cSDimitry Andric // String. 26526122f3e6SDimitry Andric Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2653f22ef01cSRoman Divacky 2654dff0c46cSDimitry Andric if (isUTF16) 2655dff0c46cSDimitry Andric // Cast the UTF16 string to the correct type. 2656dff0c46cSDimitry Andric Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 2657dff0c46cSDimitry Andric 2658f22ef01cSRoman Divacky // String length. 2659f22ef01cSRoman Divacky Ty = getTypes().ConvertType(getContext().LongTy); 2660f22ef01cSRoman Divacky Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 2661f22ef01cSRoman Divacky 2662f22ef01cSRoman Divacky // The struct. 2663f22ef01cSRoman Divacky C = llvm::ConstantStruct::get(STy, Fields); 2664f22ef01cSRoman Divacky GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2665f22ef01cSRoman Divacky llvm::GlobalVariable::PrivateLinkage, C, 2666f22ef01cSRoman Divacky "_unnamed_cfstring_"); 266759d1ed5bSDimitry Andric GV->setSection("__DATA,__cfstring"); 266839d628a0SDimitry Andric Entry.second = GV; 2669f22ef01cSRoman Divacky 2670f22ef01cSRoman Divacky return GV; 2671f22ef01cSRoman Divacky } 2672f22ef01cSRoman Divacky 2673f22ef01cSRoman Divacky llvm::Constant * 26742754fe60SDimitry Andric CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 2675f22ef01cSRoman Divacky unsigned StringLength = 0; 2676f22ef01cSRoman Divacky llvm::StringMapEntry<llvm::Constant*> &Entry = 2677bd5abe19SDimitry Andric GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 2678f22ef01cSRoman Divacky 267939d628a0SDimitry Andric if (auto *C = Entry.second) 2680f22ef01cSRoman Divacky return C; 2681f22ef01cSRoman Divacky 2682dff0c46cSDimitry Andric llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 2683f22ef01cSRoman Divacky llvm::Constant *Zeros[] = { Zero, Zero }; 2684284c1978SDimitry Andric llvm::Value *V; 2685f22ef01cSRoman Divacky // If we don't already have it, get _NSConstantStringClassReference. 26862754fe60SDimitry Andric if (!ConstantStringClassRef) { 2687dff0c46cSDimitry Andric std::string StringClass(getLangOpts().ObjCConstantStringClass); 26886122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 26892754fe60SDimitry Andric llvm::Constant *GV; 26907ae0e2c9SDimitry Andric if (LangOpts.ObjCRuntime.isNonFragile()) { 2691bd5abe19SDimitry Andric std::string str = 2692bd5abe19SDimitry Andric StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 2693bd5abe19SDimitry Andric : "OBJC_CLASS_$_" + StringClass; 2694bd5abe19SDimitry Andric GV = getObjCRuntime().GetClassGlobal(str); 2695bd5abe19SDimitry Andric // Make sure the result is of the correct type. 26966122f3e6SDimitry Andric llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 2697284c1978SDimitry Andric V = llvm::ConstantExpr::getBitCast(GV, PTy); 2698284c1978SDimitry Andric ConstantStringClassRef = V; 2699bd5abe19SDimitry Andric } else { 2700bd5abe19SDimitry Andric std::string str = 2701bd5abe19SDimitry Andric StringClass.empty() ? "_NSConstantStringClassReference" 2702bd5abe19SDimitry Andric : "_" + StringClass + "ClassReference"; 27036122f3e6SDimitry Andric llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 2704bd5abe19SDimitry Andric GV = CreateRuntimeVariable(PTy, str); 2705f22ef01cSRoman Divacky // Decay array -> ptr 2706284c1978SDimitry Andric V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2707284c1978SDimitry Andric ConstantStringClassRef = V; 2708f22ef01cSRoman Divacky } 2709bd5abe19SDimitry Andric } 2710284c1978SDimitry Andric else 2711284c1978SDimitry Andric V = ConstantStringClassRef; 2712f22ef01cSRoman Divacky 27136122f3e6SDimitry Andric if (!NSConstantStringType) { 27146122f3e6SDimitry Andric // Construct the type for a constant NSString. 271559d1ed5bSDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString"); 27166122f3e6SDimitry Andric D->startDefinition(); 2717f22ef01cSRoman Divacky 27186122f3e6SDimitry Andric QualType FieldTypes[3]; 27196122f3e6SDimitry Andric 27206122f3e6SDimitry Andric // const int *isa; 27216122f3e6SDimitry Andric FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 27226122f3e6SDimitry Andric // const char *str; 27236122f3e6SDimitry Andric FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 27246122f3e6SDimitry Andric // unsigned int length; 27256122f3e6SDimitry Andric FieldTypes[2] = Context.UnsignedIntTy; 27266122f3e6SDimitry Andric 27276122f3e6SDimitry Andric // Create fields 27286122f3e6SDimitry Andric for (unsigned i = 0; i < 3; ++i) { 27296122f3e6SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, D, 27306122f3e6SDimitry Andric SourceLocation(), 273159d1ed5bSDimitry Andric SourceLocation(), nullptr, 273259d1ed5bSDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 273359d1ed5bSDimitry Andric /*BitWidth=*/nullptr, 27346122f3e6SDimitry Andric /*Mutable=*/false, 27357ae0e2c9SDimitry Andric ICIS_NoInit); 27366122f3e6SDimitry Andric Field->setAccess(AS_public); 27376122f3e6SDimitry Andric D->addDecl(Field); 27386122f3e6SDimitry Andric } 27396122f3e6SDimitry Andric 27406122f3e6SDimitry Andric D->completeDefinition(); 27416122f3e6SDimitry Andric QualType NSTy = Context.getTagDeclType(D); 27426122f3e6SDimitry Andric NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 27436122f3e6SDimitry Andric } 2744f22ef01cSRoman Divacky 2745dff0c46cSDimitry Andric llvm::Constant *Fields[3]; 2746f22ef01cSRoman Divacky 2747f22ef01cSRoman Divacky // Class pointer. 2748284c1978SDimitry Andric Fields[0] = cast<llvm::ConstantExpr>(V); 2749f22ef01cSRoman Divacky 2750f22ef01cSRoman Divacky // String pointer. 2751dff0c46cSDimitry Andric llvm::Constant *C = 275239d628a0SDimitry Andric llvm::ConstantDataArray::getString(VMContext, Entry.first()); 2753f22ef01cSRoman Divacky 2754f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes Linkage; 2755f22ef01cSRoman Divacky bool isConstant; 2756f22ef01cSRoman Divacky Linkage = llvm::GlobalValue::PrivateLinkage; 2757dff0c46cSDimitry Andric isConstant = !LangOpts.WritableStrings; 2758f22ef01cSRoman Divacky 275959d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant, 276059d1ed5bSDimitry Andric Linkage, C, ".str"); 27612754fe60SDimitry Andric GV->setUnnamedAddr(true); 2762284c1978SDimitry Andric // Don't enforce the target's minimum global alignment, since the only use 2763284c1978SDimitry Andric // of the string is via this class initializer. 27643b0f4066SDimitry Andric CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 27653b0f4066SDimitry Andric GV->setAlignment(Align.getQuantity()); 27666122f3e6SDimitry Andric Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 2767f22ef01cSRoman Divacky 2768f22ef01cSRoman Divacky // String length. 27696122f3e6SDimitry Andric llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 2770f22ef01cSRoman Divacky Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 2771f22ef01cSRoman Divacky 2772f22ef01cSRoman Divacky // The struct. 27736122f3e6SDimitry Andric C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 2774f22ef01cSRoman Divacky GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 2775f22ef01cSRoman Divacky llvm::GlobalVariable::PrivateLinkage, C, 2776f22ef01cSRoman Divacky "_unnamed_nsstring_"); 277759d1ed5bSDimitry Andric const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip"; 277859d1ed5bSDimitry Andric const char *NSStringNonFragileABISection = 277959d1ed5bSDimitry Andric "__DATA,__objc_stringobj,regular,no_dead_strip"; 2780f22ef01cSRoman Divacky // FIXME. Fix section. 278159d1ed5bSDimitry Andric GV->setSection(LangOpts.ObjCRuntime.isNonFragile() 278259d1ed5bSDimitry Andric ? NSStringNonFragileABISection 278359d1ed5bSDimitry Andric : NSStringSection); 278439d628a0SDimitry Andric Entry.second = GV; 2785f22ef01cSRoman Divacky 2786f22ef01cSRoman Divacky return GV; 2787f22ef01cSRoman Divacky } 2788f22ef01cSRoman Divacky 27896122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() { 27906122f3e6SDimitry Andric if (ObjCFastEnumerationStateType.isNull()) { 279159d1ed5bSDimitry Andric RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 27926122f3e6SDimitry Andric D->startDefinition(); 27936122f3e6SDimitry Andric 27946122f3e6SDimitry Andric QualType FieldTypes[] = { 27956122f3e6SDimitry Andric Context.UnsignedLongTy, 27966122f3e6SDimitry Andric Context.getPointerType(Context.getObjCIdType()), 27976122f3e6SDimitry Andric Context.getPointerType(Context.UnsignedLongTy), 27986122f3e6SDimitry Andric Context.getConstantArrayType(Context.UnsignedLongTy, 27996122f3e6SDimitry Andric llvm::APInt(32, 5), ArrayType::Normal, 0) 28006122f3e6SDimitry Andric }; 28016122f3e6SDimitry Andric 28026122f3e6SDimitry Andric for (size_t i = 0; i < 4; ++i) { 28036122f3e6SDimitry Andric FieldDecl *Field = FieldDecl::Create(Context, 28046122f3e6SDimitry Andric D, 28056122f3e6SDimitry Andric SourceLocation(), 280659d1ed5bSDimitry Andric SourceLocation(), nullptr, 280759d1ed5bSDimitry Andric FieldTypes[i], /*TInfo=*/nullptr, 280859d1ed5bSDimitry Andric /*BitWidth=*/nullptr, 28096122f3e6SDimitry Andric /*Mutable=*/false, 28107ae0e2c9SDimitry Andric ICIS_NoInit); 28116122f3e6SDimitry Andric Field->setAccess(AS_public); 28126122f3e6SDimitry Andric D->addDecl(Field); 28136122f3e6SDimitry Andric } 28146122f3e6SDimitry Andric 28156122f3e6SDimitry Andric D->completeDefinition(); 28166122f3e6SDimitry Andric ObjCFastEnumerationStateType = Context.getTagDeclType(D); 28176122f3e6SDimitry Andric } 28186122f3e6SDimitry Andric 28196122f3e6SDimitry Andric return ObjCFastEnumerationStateType; 28206122f3e6SDimitry Andric } 28216122f3e6SDimitry Andric 2822dff0c46cSDimitry Andric llvm::Constant * 2823dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 2824dff0c46cSDimitry Andric assert(!E->getType()->isPointerType() && "Strings are always arrays"); 2825f22ef01cSRoman Divacky 2826dff0c46cSDimitry Andric // Don't emit it as the address of the string, emit the string data itself 2827dff0c46cSDimitry Andric // as an inline array. 2828dff0c46cSDimitry Andric if (E->getCharByteWidth() == 1) { 2829dff0c46cSDimitry Andric SmallString<64> Str(E->getString()); 2830f22ef01cSRoman Divacky 2831dff0c46cSDimitry Andric // Resize the string to the right size, which is indicated by its type. 2832dff0c46cSDimitry Andric const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 2833dff0c46cSDimitry Andric Str.resize(CAT->getSize().getZExtValue()); 2834dff0c46cSDimitry Andric return llvm::ConstantDataArray::getString(VMContext, Str, false); 28356122f3e6SDimitry Andric } 2836f22ef01cSRoman Divacky 283759d1ed5bSDimitry Andric auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 2838dff0c46cSDimitry Andric llvm::Type *ElemTy = AType->getElementType(); 2839dff0c46cSDimitry Andric unsigned NumElements = AType->getNumElements(); 2840f22ef01cSRoman Divacky 2841dff0c46cSDimitry Andric // Wide strings have either 2-byte or 4-byte elements. 2842dff0c46cSDimitry Andric if (ElemTy->getPrimitiveSizeInBits() == 16) { 2843dff0c46cSDimitry Andric SmallVector<uint16_t, 32> Elements; 2844dff0c46cSDimitry Andric Elements.reserve(NumElements); 2845dff0c46cSDimitry Andric 2846dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2847dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 2848dff0c46cSDimitry Andric Elements.resize(NumElements); 2849dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 2850dff0c46cSDimitry Andric } 2851dff0c46cSDimitry Andric 2852dff0c46cSDimitry Andric assert(ElemTy->getPrimitiveSizeInBits() == 32); 2853dff0c46cSDimitry Andric SmallVector<uint32_t, 32> Elements; 2854dff0c46cSDimitry Andric Elements.reserve(NumElements); 2855dff0c46cSDimitry Andric 2856dff0c46cSDimitry Andric for(unsigned i = 0, e = E->getLength(); i != e; ++i) 2857dff0c46cSDimitry Andric Elements.push_back(E->getCodeUnit(i)); 2858dff0c46cSDimitry Andric Elements.resize(NumElements); 2859dff0c46cSDimitry Andric return llvm::ConstantDataArray::get(VMContext, Elements); 2860f22ef01cSRoman Divacky } 2861f22ef01cSRoman Divacky 286259d1ed5bSDimitry Andric static llvm::GlobalVariable * 286359d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 286459d1ed5bSDimitry Andric CodeGenModule &CGM, StringRef GlobalName, 286559d1ed5bSDimitry Andric unsigned Alignment) { 286659d1ed5bSDimitry Andric // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 286759d1ed5bSDimitry Andric unsigned AddrSpace = 0; 286859d1ed5bSDimitry Andric if (CGM.getLangOpts().OpenCL) 286959d1ed5bSDimitry Andric AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant); 2870dff0c46cSDimitry Andric 287159d1ed5bSDimitry Andric // Create a global variable for this string 287259d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 287359d1ed5bSDimitry Andric CGM.getModule(), C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, 287459d1ed5bSDimitry Andric GlobalName, nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 287559d1ed5bSDimitry Andric GV->setAlignment(Alignment); 287659d1ed5bSDimitry Andric GV->setUnnamedAddr(true); 287759d1ed5bSDimitry Andric return GV; 2878f22ef01cSRoman Divacky } 2879dff0c46cSDimitry Andric 288059d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 288159d1ed5bSDimitry Andric /// constant array for the given string literal. 288259d1ed5bSDimitry Andric llvm::GlobalVariable * 288339d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 288439d628a0SDimitry Andric StringRef Name) { 288559d1ed5bSDimitry Andric auto Alignment = 288659d1ed5bSDimitry Andric getContext().getAlignOfGlobalVarInChars(S->getType()).getQuantity(); 2887dff0c46cSDimitry Andric 288859d1ed5bSDimitry Andric llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 288959d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 289059d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 289159d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 289259d1ed5bSDimitry Andric if (auto GV = *Entry) { 289359d1ed5bSDimitry Andric if (Alignment > GV->getAlignment()) 289459d1ed5bSDimitry Andric GV->setAlignment(Alignment); 289559d1ed5bSDimitry Andric return GV; 289659d1ed5bSDimitry Andric } 289759d1ed5bSDimitry Andric } 289859d1ed5bSDimitry Andric 289959d1ed5bSDimitry Andric SmallString<256> MangledNameBuffer; 290059d1ed5bSDimitry Andric StringRef GlobalVariableName; 290159d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes LT; 290259d1ed5bSDimitry Andric 290359d1ed5bSDimitry Andric // Mangle the string literal if the ABI allows for it. However, we cannot 290459d1ed5bSDimitry Andric // do this if we are compiling with ASan or -fwritable-strings because they 290559d1ed5bSDimitry Andric // rely on strings having normal linkage. 290639d628a0SDimitry Andric if (!LangOpts.WritableStrings && 290739d628a0SDimitry Andric !LangOpts.Sanitize.has(SanitizerKind::Address) && 290859d1ed5bSDimitry Andric getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) { 290959d1ed5bSDimitry Andric llvm::raw_svector_ostream Out(MangledNameBuffer); 291059d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 291159d1ed5bSDimitry Andric Out.flush(); 291259d1ed5bSDimitry Andric 291359d1ed5bSDimitry Andric LT = llvm::GlobalValue::LinkOnceODRLinkage; 291459d1ed5bSDimitry Andric GlobalVariableName = MangledNameBuffer; 291559d1ed5bSDimitry Andric } else { 291659d1ed5bSDimitry Andric LT = llvm::GlobalValue::PrivateLinkage; 291739d628a0SDimitry Andric GlobalVariableName = Name; 291859d1ed5bSDimitry Andric } 291959d1ed5bSDimitry Andric 292059d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 292159d1ed5bSDimitry Andric if (Entry) 292259d1ed5bSDimitry Andric *Entry = GV; 292359d1ed5bSDimitry Andric 292439d628a0SDimitry Andric SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 292539d628a0SDimitry Andric QualType()); 2926dff0c46cSDimitry Andric return GV; 2927f22ef01cSRoman Divacky } 2928f22ef01cSRoman Divacky 2929f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 2930f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node. 293159d1ed5bSDimitry Andric llvm::GlobalVariable * 2932f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 2933f22ef01cSRoman Divacky std::string Str; 2934f22ef01cSRoman Divacky getContext().getObjCEncodingForType(E->getEncodedType(), Str); 2935f22ef01cSRoman Divacky 2936f22ef01cSRoman Divacky return GetAddrOfConstantCString(Str); 2937f22ef01cSRoman Divacky } 2938f22ef01cSRoman Divacky 293959d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing 294059d1ed5bSDimitry Andric /// the literal and a terminating '\0' character. 294159d1ed5bSDimitry Andric /// The result has pointer to array type. 294259d1ed5bSDimitry Andric llvm::GlobalVariable *CodeGenModule::GetAddrOfConstantCString( 294359d1ed5bSDimitry Andric const std::string &Str, const char *GlobalName, unsigned Alignment) { 294459d1ed5bSDimitry Andric StringRef StrWithNull(Str.c_str(), Str.size() + 1); 294559d1ed5bSDimitry Andric if (Alignment == 0) { 294659d1ed5bSDimitry Andric Alignment = getContext() 294759d1ed5bSDimitry Andric .getAlignOfGlobalVarInChars(getContext().CharTy) 294859d1ed5bSDimitry Andric .getQuantity(); 2949f22ef01cSRoman Divacky } 2950f22ef01cSRoman Divacky 295159d1ed5bSDimitry Andric llvm::Constant *C = 295259d1ed5bSDimitry Andric llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 295359d1ed5bSDimitry Andric 295459d1ed5bSDimitry Andric // Don't share any string literals if strings aren't constant. 295559d1ed5bSDimitry Andric llvm::GlobalVariable **Entry = nullptr; 295659d1ed5bSDimitry Andric if (!LangOpts.WritableStrings) { 295759d1ed5bSDimitry Andric Entry = &ConstantStringMap[C]; 295859d1ed5bSDimitry Andric if (auto GV = *Entry) { 295959d1ed5bSDimitry Andric if (Alignment > GV->getAlignment()) 296059d1ed5bSDimitry Andric GV->setAlignment(Alignment); 296159d1ed5bSDimitry Andric return GV; 296259d1ed5bSDimitry Andric } 296359d1ed5bSDimitry Andric } 296459d1ed5bSDimitry Andric 2965f22ef01cSRoman Divacky // Get the default prefix if a name wasn't specified. 2966f22ef01cSRoman Divacky if (!GlobalName) 2967f22ef01cSRoman Divacky GlobalName = ".str"; 2968f22ef01cSRoman Divacky // Create a global variable for this. 296959d1ed5bSDimitry Andric auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 297059d1ed5bSDimitry Andric GlobalName, Alignment); 297159d1ed5bSDimitry Andric if (Entry) 297259d1ed5bSDimitry Andric *Entry = GV; 29736122f3e6SDimitry Andric return GV; 2974f22ef01cSRoman Divacky } 2975f22ef01cSRoman Divacky 2976f785676fSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary( 2977f785676fSDimitry Andric const MaterializeTemporaryExpr *E, const Expr *Init) { 2978f785676fSDimitry Andric assert((E->getStorageDuration() == SD_Static || 2979f785676fSDimitry Andric E->getStorageDuration() == SD_Thread) && "not a global temporary"); 298059d1ed5bSDimitry Andric const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 2981f785676fSDimitry Andric 2982f785676fSDimitry Andric // If we're not materializing a subobject of the temporary, keep the 2983f785676fSDimitry Andric // cv-qualifiers from the type of the MaterializeTemporaryExpr. 2984f785676fSDimitry Andric QualType MaterializedType = Init->getType(); 2985f785676fSDimitry Andric if (Init == E->GetTemporaryExpr()) 2986f785676fSDimitry Andric MaterializedType = E->getType(); 2987f785676fSDimitry Andric 2988f785676fSDimitry Andric llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E]; 2989f785676fSDimitry Andric if (Slot) 2990f785676fSDimitry Andric return Slot; 2991f785676fSDimitry Andric 2992f785676fSDimitry Andric // FIXME: If an externally-visible declaration extends multiple temporaries, 2993f785676fSDimitry Andric // we need to give each temporary the same name in every translation unit (and 2994f785676fSDimitry Andric // we also need to make the temporaries externally-visible). 2995f785676fSDimitry Andric SmallString<256> Name; 2996f785676fSDimitry Andric llvm::raw_svector_ostream Out(Name); 299759d1ed5bSDimitry Andric getCXXABI().getMangleContext().mangleReferenceTemporary( 299859d1ed5bSDimitry Andric VD, E->getManglingNumber(), Out); 2999f785676fSDimitry Andric Out.flush(); 3000f785676fSDimitry Andric 300159d1ed5bSDimitry Andric APValue *Value = nullptr; 3002f785676fSDimitry Andric if (E->getStorageDuration() == SD_Static) { 3003f785676fSDimitry Andric // We might have a cached constant initializer for this temporary. Note 3004f785676fSDimitry Andric // that this might have a different value from the value computed by 3005f785676fSDimitry Andric // evaluating the initializer if the surrounding constant expression 3006f785676fSDimitry Andric // modifies the temporary. 3007f785676fSDimitry Andric Value = getContext().getMaterializedTemporaryValue(E, false); 3008f785676fSDimitry Andric if (Value && Value->isUninit()) 300959d1ed5bSDimitry Andric Value = nullptr; 3010f785676fSDimitry Andric } 3011f785676fSDimitry Andric 3012f785676fSDimitry Andric // Try evaluating it now, it might have a constant initializer. 3013f785676fSDimitry Andric Expr::EvalResult EvalResult; 3014f785676fSDimitry Andric if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 3015f785676fSDimitry Andric !EvalResult.hasSideEffects()) 3016f785676fSDimitry Andric Value = &EvalResult.Val; 3017f785676fSDimitry Andric 301859d1ed5bSDimitry Andric llvm::Constant *InitialValue = nullptr; 3019f785676fSDimitry Andric bool Constant = false; 3020f785676fSDimitry Andric llvm::Type *Type; 3021f785676fSDimitry Andric if (Value) { 3022f785676fSDimitry Andric // The temporary has a constant initializer, use it. 302359d1ed5bSDimitry Andric InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr); 3024f785676fSDimitry Andric Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 3025f785676fSDimitry Andric Type = InitialValue->getType(); 3026f785676fSDimitry Andric } else { 3027f785676fSDimitry Andric // No initializer, the initialization will be provided when we 3028f785676fSDimitry Andric // initialize the declaration which performed lifetime extension. 3029f785676fSDimitry Andric Type = getTypes().ConvertTypeForMem(MaterializedType); 3030f785676fSDimitry Andric } 3031f785676fSDimitry Andric 3032f785676fSDimitry Andric // Create a global variable for this lifetime-extended temporary. 303359d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes Linkage = 303459d1ed5bSDimitry Andric getLLVMLinkageVarDefinition(VD, Constant); 303559d1ed5bSDimitry Andric // There is no need for this temporary to have global linkage if the global 303659d1ed5bSDimitry Andric // variable has external linkage. 303759d1ed5bSDimitry Andric if (Linkage == llvm::GlobalVariable::ExternalLinkage) 303859d1ed5bSDimitry Andric Linkage = llvm::GlobalVariable::PrivateLinkage; 303959d1ed5bSDimitry Andric unsigned AddrSpace = GetGlobalVarAddressSpace( 304059d1ed5bSDimitry Andric VD, getContext().getTargetAddressSpace(MaterializedType)); 304159d1ed5bSDimitry Andric auto *GV = new llvm::GlobalVariable( 304259d1ed5bSDimitry Andric getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 304359d1ed5bSDimitry Andric /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, 304459d1ed5bSDimitry Andric AddrSpace); 304559d1ed5bSDimitry Andric setGlobalVisibility(GV, VD); 3046f785676fSDimitry Andric GV->setAlignment( 3047f785676fSDimitry Andric getContext().getTypeAlignInChars(MaterializedType).getQuantity()); 3048f785676fSDimitry Andric if (VD->getTLSKind()) 3049f785676fSDimitry Andric setTLSMode(GV, *VD); 3050f785676fSDimitry Andric Slot = GV; 3051f785676fSDimitry Andric return GV; 3052f785676fSDimitry Andric } 3053f785676fSDimitry Andric 3054f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized 3055f22ef01cSRoman Divacky /// properties for an implementation. 3056f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const 3057f22ef01cSRoman Divacky ObjCImplementationDecl *D) { 305859d1ed5bSDimitry Andric for (const auto *PID : D->property_impls()) { 3059f22ef01cSRoman Divacky // Dynamic is just for type-checking. 3060f22ef01cSRoman Divacky if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 3061f22ef01cSRoman Divacky ObjCPropertyDecl *PD = PID->getPropertyDecl(); 3062f22ef01cSRoman Divacky 3063f22ef01cSRoman Divacky // Determine which methods need to be implemented, some may have 30643861d79fSDimitry Andric // been overridden. Note that ::isPropertyAccessor is not the method 3065f22ef01cSRoman Divacky // we want, that just indicates if the decl came from a 3066f22ef01cSRoman Divacky // property. What we want to know is if the method is defined in 3067f22ef01cSRoman Divacky // this implementation. 3068f22ef01cSRoman Divacky if (!D->getInstanceMethod(PD->getGetterName())) 3069f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCGetter( 3070f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3071f22ef01cSRoman Divacky if (!PD->isReadOnly() && 3072f22ef01cSRoman Divacky !D->getInstanceMethod(PD->getSetterName())) 3073f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCSetter( 3074f22ef01cSRoman Divacky const_cast<ObjCImplementationDecl *>(D), PID); 3075f22ef01cSRoman Divacky } 3076f22ef01cSRoman Divacky } 3077f22ef01cSRoman Divacky } 3078f22ef01cSRoman Divacky 30793b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) { 30806122f3e6SDimitry Andric const ObjCInterfaceDecl *iface = impl->getClassInterface(); 30816122f3e6SDimitry Andric for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 30823b0f4066SDimitry Andric ivar; ivar = ivar->getNextIvar()) 30833b0f4066SDimitry Andric if (ivar->getType().isDestructedType()) 30843b0f4066SDimitry Andric return true; 30853b0f4066SDimitry Andric 30863b0f4066SDimitry Andric return false; 30873b0f4066SDimitry Andric } 30883b0f4066SDimitry Andric 308939d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM, 309039d628a0SDimitry Andric ObjCImplementationDecl *D) { 309139d628a0SDimitry Andric CodeGenFunction CGF(CGM); 309239d628a0SDimitry Andric for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 309339d628a0SDimitry Andric E = D->init_end(); B != E; ++B) { 309439d628a0SDimitry Andric CXXCtorInitializer *CtorInitExp = *B; 309539d628a0SDimitry Andric Expr *Init = CtorInitExp->getInit(); 309639d628a0SDimitry Andric if (!CGF.isTrivialInitializer(Init)) 309739d628a0SDimitry Andric return false; 309839d628a0SDimitry Andric } 309939d628a0SDimitry Andric return true; 310039d628a0SDimitry Andric } 310139d628a0SDimitry Andric 3102f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization 3103f22ef01cSRoman Divacky /// for an implementation. 3104f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 31053b0f4066SDimitry Andric // We might need a .cxx_destruct even if we don't have any ivar initializers. 31063b0f4066SDimitry Andric if (needsDestructMethod(D)) { 3107f22ef01cSRoman Divacky IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 3108f22ef01cSRoman Divacky Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 31093b0f4066SDimitry Andric ObjCMethodDecl *DTORMethod = 31103b0f4066SDimitry Andric ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 311159d1ed5bSDimitry Andric cxxSelector, getContext().VoidTy, nullptr, D, 31126122f3e6SDimitry Andric /*isInstance=*/true, /*isVariadic=*/false, 31133861d79fSDimitry Andric /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true, 31146122f3e6SDimitry Andric /*isDefined=*/false, ObjCMethodDecl::Required); 3115f22ef01cSRoman Divacky D->addInstanceMethod(DTORMethod); 3116f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 31173861d79fSDimitry Andric D->setHasDestructors(true); 31183b0f4066SDimitry Andric } 3119f22ef01cSRoman Divacky 31203b0f4066SDimitry Andric // If the implementation doesn't have any ivar initializers, we don't need 31213b0f4066SDimitry Andric // a .cxx_construct. 312239d628a0SDimitry Andric if (D->getNumIvarInitializers() == 0 || 312339d628a0SDimitry Andric AllTrivialInitializers(*this, D)) 31243b0f4066SDimitry Andric return; 31253b0f4066SDimitry Andric 31263b0f4066SDimitry Andric IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 31273b0f4066SDimitry Andric Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 3128f22ef01cSRoman Divacky // The constructor returns 'self'. 3129f22ef01cSRoman Divacky ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 3130f22ef01cSRoman Divacky D->getLocation(), 31316122f3e6SDimitry Andric D->getLocation(), 31326122f3e6SDimitry Andric cxxSelector, 313359d1ed5bSDimitry Andric getContext().getObjCIdType(), 313459d1ed5bSDimitry Andric nullptr, D, /*isInstance=*/true, 31356122f3e6SDimitry Andric /*isVariadic=*/false, 31363861d79fSDimitry Andric /*isPropertyAccessor=*/true, 31376122f3e6SDimitry Andric /*isImplicitlyDeclared=*/true, 31386122f3e6SDimitry Andric /*isDefined=*/false, 3139f22ef01cSRoman Divacky ObjCMethodDecl::Required); 3140f22ef01cSRoman Divacky D->addInstanceMethod(CTORMethod); 3141f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 31423861d79fSDimitry Andric D->setHasNonZeroConstructors(true); 3143f22ef01cSRoman Divacky } 3144f22ef01cSRoman Divacky 3145f22ef01cSRoman Divacky /// EmitNamespace - Emit all declarations in a namespace. 3146f22ef01cSRoman Divacky void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 314759d1ed5bSDimitry Andric for (auto *I : ND->decls()) { 314859d1ed5bSDimitry Andric if (const auto *VD = dyn_cast<VarDecl>(I)) 3149f785676fSDimitry Andric if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization && 3150f785676fSDimitry Andric VD->getTemplateSpecializationKind() != TSK_Undeclared) 3151f785676fSDimitry Andric continue; 315259d1ed5bSDimitry Andric EmitTopLevelDecl(I); 3153f22ef01cSRoman Divacky } 3154f785676fSDimitry Andric } 3155f22ef01cSRoman Divacky 3156f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec. 3157f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 3158f22ef01cSRoman Divacky if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 3159f22ef01cSRoman Divacky LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 3160f22ef01cSRoman Divacky ErrorUnsupported(LSD, "linkage spec"); 3161f22ef01cSRoman Divacky return; 3162f22ef01cSRoman Divacky } 3163f22ef01cSRoman Divacky 316459d1ed5bSDimitry Andric for (auto *I : LSD->decls()) { 31653861d79fSDimitry Andric // Meta-data for ObjC class includes references to implemented methods. 31663861d79fSDimitry Andric // Generate class's method definitions first. 316759d1ed5bSDimitry Andric if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 316859d1ed5bSDimitry Andric for (auto *M : OID->methods()) 316959d1ed5bSDimitry Andric EmitTopLevelDecl(M); 31703861d79fSDimitry Andric } 317159d1ed5bSDimitry Andric EmitTopLevelDecl(I); 3172f22ef01cSRoman Divacky } 31733861d79fSDimitry Andric } 3174f22ef01cSRoman Divacky 3175f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration. 3176f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) { 3177f22ef01cSRoman Divacky // Ignore dependent declarations. 3178f22ef01cSRoman Divacky if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 3179f22ef01cSRoman Divacky return; 3180f22ef01cSRoman Divacky 3181f22ef01cSRoman Divacky switch (D->getKind()) { 3182f22ef01cSRoman Divacky case Decl::CXXConversion: 3183f22ef01cSRoman Divacky case Decl::CXXMethod: 3184f22ef01cSRoman Divacky case Decl::Function: 3185f22ef01cSRoman Divacky // Skip function templates 31863b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 31873b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3188f22ef01cSRoman Divacky return; 3189f22ef01cSRoman Divacky 3190f22ef01cSRoman Divacky EmitGlobal(cast<FunctionDecl>(D)); 319139d628a0SDimitry Andric // Always provide some coverage mapping 319239d628a0SDimitry Andric // even for the functions that aren't emitted. 319339d628a0SDimitry Andric AddDeferredUnusedCoverageMapping(D); 3194f22ef01cSRoman Divacky break; 3195f22ef01cSRoman Divacky 3196f22ef01cSRoman Divacky case Decl::Var: 3197f785676fSDimitry Andric // Skip variable templates 3198f785676fSDimitry Andric if (cast<VarDecl>(D)->getDescribedVarTemplate()) 3199f785676fSDimitry Andric return; 3200f785676fSDimitry Andric case Decl::VarTemplateSpecialization: 3201f22ef01cSRoman Divacky EmitGlobal(cast<VarDecl>(D)); 3202f22ef01cSRoman Divacky break; 3203f22ef01cSRoman Divacky 32043b0f4066SDimitry Andric // Indirect fields from global anonymous structs and unions can be 32053b0f4066SDimitry Andric // ignored; only the actual variable requires IR gen support. 32063b0f4066SDimitry Andric case Decl::IndirectField: 32073b0f4066SDimitry Andric break; 32083b0f4066SDimitry Andric 3209f22ef01cSRoman Divacky // C++ Decls 3210f22ef01cSRoman Divacky case Decl::Namespace: 3211f22ef01cSRoman Divacky EmitNamespace(cast<NamespaceDecl>(D)); 3212f22ef01cSRoman Divacky break; 3213f22ef01cSRoman Divacky // No code generation needed. 3214f22ef01cSRoman Divacky case Decl::UsingShadow: 3215f22ef01cSRoman Divacky case Decl::ClassTemplate: 3216f785676fSDimitry Andric case Decl::VarTemplate: 3217f785676fSDimitry Andric case Decl::VarTemplatePartialSpecialization: 3218f22ef01cSRoman Divacky case Decl::FunctionTemplate: 3219bd5abe19SDimitry Andric case Decl::TypeAliasTemplate: 3220bd5abe19SDimitry Andric case Decl::Block: 3221139f7f9bSDimitry Andric case Decl::Empty: 3222f22ef01cSRoman Divacky break; 322359d1ed5bSDimitry Andric case Decl::Using: // using X; [C++] 322459d1ed5bSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 322559d1ed5bSDimitry Andric DI->EmitUsingDecl(cast<UsingDecl>(*D)); 322659d1ed5bSDimitry Andric return; 3227f785676fSDimitry Andric case Decl::NamespaceAlias: 3228f785676fSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3229f785676fSDimitry Andric DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 3230f785676fSDimitry Andric return; 3231284c1978SDimitry Andric case Decl::UsingDirective: // using namespace X; [C++] 3232284c1978SDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3233284c1978SDimitry Andric DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 3234284c1978SDimitry Andric return; 3235f22ef01cSRoman Divacky case Decl::CXXConstructor: 3236f22ef01cSRoman Divacky // Skip function templates 32373b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 32383b0f4066SDimitry Andric cast<FunctionDecl>(D)->isLateTemplateParsed()) 3239f22ef01cSRoman Divacky return; 3240f22ef01cSRoman Divacky 3241f785676fSDimitry Andric getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 3242f22ef01cSRoman Divacky break; 3243f22ef01cSRoman Divacky case Decl::CXXDestructor: 32443b0f4066SDimitry Andric if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 32453b0f4066SDimitry Andric return; 3246f785676fSDimitry Andric getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 3247f22ef01cSRoman Divacky break; 3248f22ef01cSRoman Divacky 3249f22ef01cSRoman Divacky case Decl::StaticAssert: 3250f22ef01cSRoman Divacky // Nothing to do. 3251f22ef01cSRoman Divacky break; 3252f22ef01cSRoman Divacky 3253f22ef01cSRoman Divacky // Objective-C Decls 3254f22ef01cSRoman Divacky 3255f22ef01cSRoman Divacky // Forward declarations, no (immediate) code generation. 3256f22ef01cSRoman Divacky case Decl::ObjCInterface: 32577ae0e2c9SDimitry Andric case Decl::ObjCCategory: 3258f22ef01cSRoman Divacky break; 3259f22ef01cSRoman Divacky 3260dff0c46cSDimitry Andric case Decl::ObjCProtocol: { 326159d1ed5bSDimitry Andric auto *Proto = cast<ObjCProtocolDecl>(D); 3262dff0c46cSDimitry Andric if (Proto->isThisDeclarationADefinition()) 3263dff0c46cSDimitry Andric ObjCRuntime->GenerateProtocol(Proto); 3264f22ef01cSRoman Divacky break; 3265dff0c46cSDimitry Andric } 3266f22ef01cSRoman Divacky 3267f22ef01cSRoman Divacky case Decl::ObjCCategoryImpl: 3268f22ef01cSRoman Divacky // Categories have properties but don't support synthesize so we 3269f22ef01cSRoman Divacky // can ignore them here. 32706122f3e6SDimitry Andric ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 3271f22ef01cSRoman Divacky break; 3272f22ef01cSRoman Divacky 3273f22ef01cSRoman Divacky case Decl::ObjCImplementation: { 327459d1ed5bSDimitry Andric auto *OMD = cast<ObjCImplementationDecl>(D); 3275f22ef01cSRoman Divacky EmitObjCPropertyImplementations(OMD); 3276f22ef01cSRoman Divacky EmitObjCIvarInitializations(OMD); 32776122f3e6SDimitry Andric ObjCRuntime->GenerateClass(OMD); 3278dff0c46cSDimitry Andric // Emit global variable debug information. 3279dff0c46cSDimitry Andric if (CGDebugInfo *DI = getModuleDebugInfo()) 3280139f7f9bSDimitry Andric if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 3281139f7f9bSDimitry Andric DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 3282139f7f9bSDimitry Andric OMD->getClassInterface()), OMD->getLocation()); 3283f22ef01cSRoman Divacky break; 3284f22ef01cSRoman Divacky } 3285f22ef01cSRoman Divacky case Decl::ObjCMethod: { 328659d1ed5bSDimitry Andric auto *OMD = cast<ObjCMethodDecl>(D); 3287f22ef01cSRoman Divacky // If this is not a prototype, emit the body. 3288f22ef01cSRoman Divacky if (OMD->getBody()) 3289f22ef01cSRoman Divacky CodeGenFunction(*this).GenerateObjCMethod(OMD); 3290f22ef01cSRoman Divacky break; 3291f22ef01cSRoman Divacky } 3292f22ef01cSRoman Divacky case Decl::ObjCCompatibleAlias: 3293dff0c46cSDimitry Andric ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 3294f22ef01cSRoman Divacky break; 3295f22ef01cSRoman Divacky 3296f22ef01cSRoman Divacky case Decl::LinkageSpec: 3297f22ef01cSRoman Divacky EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 3298f22ef01cSRoman Divacky break; 3299f22ef01cSRoman Divacky 3300f22ef01cSRoman Divacky case Decl::FileScopeAsm: { 330159d1ed5bSDimitry Andric auto *AD = cast<FileScopeAsmDecl>(D); 33026122f3e6SDimitry Andric StringRef AsmString = AD->getAsmString()->getString(); 3303f22ef01cSRoman Divacky 3304f22ef01cSRoman Divacky const std::string &S = getModule().getModuleInlineAsm(); 3305f22ef01cSRoman Divacky if (S.empty()) 3306f22ef01cSRoman Divacky getModule().setModuleInlineAsm(AsmString); 33077ae0e2c9SDimitry Andric else if (S.end()[-1] == '\n') 33086122f3e6SDimitry Andric getModule().setModuleInlineAsm(S + AsmString.str()); 3309f22ef01cSRoman Divacky else 3310f22ef01cSRoman Divacky getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 3311f22ef01cSRoman Divacky break; 3312f22ef01cSRoman Divacky } 3313f22ef01cSRoman Divacky 3314139f7f9bSDimitry Andric case Decl::Import: { 331559d1ed5bSDimitry Andric auto *Import = cast<ImportDecl>(D); 3316139f7f9bSDimitry Andric 3317139f7f9bSDimitry Andric // Ignore import declarations that come from imported modules. 3318139f7f9bSDimitry Andric if (clang::Module *Owner = Import->getOwningModule()) { 3319139f7f9bSDimitry Andric if (getLangOpts().CurrentModule.empty() || 3320139f7f9bSDimitry Andric Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule) 3321139f7f9bSDimitry Andric break; 3322139f7f9bSDimitry Andric } 3323139f7f9bSDimitry Andric 3324139f7f9bSDimitry Andric ImportedModules.insert(Import->getImportedModule()); 3325139f7f9bSDimitry Andric break; 3326139f7f9bSDimitry Andric } 3327139f7f9bSDimitry Andric 332839d628a0SDimitry Andric case Decl::OMPThreadPrivate: 332939d628a0SDimitry Andric EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 333039d628a0SDimitry Andric break; 333139d628a0SDimitry Andric 333259d1ed5bSDimitry Andric case Decl::ClassTemplateSpecialization: { 333359d1ed5bSDimitry Andric const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 333459d1ed5bSDimitry Andric if (DebugInfo && 333539d628a0SDimitry Andric Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition && 333639d628a0SDimitry Andric Spec->hasDefinition()) 333759d1ed5bSDimitry Andric DebugInfo->completeTemplateDefinition(*Spec); 333839d628a0SDimitry Andric break; 333959d1ed5bSDimitry Andric } 334059d1ed5bSDimitry Andric 3341f22ef01cSRoman Divacky default: 3342f22ef01cSRoman Divacky // Make sure we handled everything we should, every other kind is a 3343f22ef01cSRoman Divacky // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 3344f22ef01cSRoman Divacky // function. Need to recode Decl::Kind to do that easily. 3345f22ef01cSRoman Divacky assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 334639d628a0SDimitry Andric break; 334739d628a0SDimitry Andric } 334839d628a0SDimitry Andric } 334939d628a0SDimitry Andric 335039d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 335139d628a0SDimitry Andric // Do we need to generate coverage mapping? 335239d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 335339d628a0SDimitry Andric return; 335439d628a0SDimitry Andric switch (D->getKind()) { 335539d628a0SDimitry Andric case Decl::CXXConversion: 335639d628a0SDimitry Andric case Decl::CXXMethod: 335739d628a0SDimitry Andric case Decl::Function: 335839d628a0SDimitry Andric case Decl::ObjCMethod: 335939d628a0SDimitry Andric case Decl::CXXConstructor: 336039d628a0SDimitry Andric case Decl::CXXDestructor: { 336139d628a0SDimitry Andric if (!cast<FunctionDecl>(D)->hasBody()) 336239d628a0SDimitry Andric return; 336339d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 336439d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 336539d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = true; 336639d628a0SDimitry Andric break; 336739d628a0SDimitry Andric } 336839d628a0SDimitry Andric default: 336939d628a0SDimitry Andric break; 337039d628a0SDimitry Andric }; 337139d628a0SDimitry Andric } 337239d628a0SDimitry Andric 337339d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 337439d628a0SDimitry Andric // Do we need to generate coverage mapping? 337539d628a0SDimitry Andric if (!CodeGenOpts.CoverageMapping) 337639d628a0SDimitry Andric return; 337739d628a0SDimitry Andric if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 337839d628a0SDimitry Andric if (Fn->isTemplateInstantiation()) 337939d628a0SDimitry Andric ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 338039d628a0SDimitry Andric } 338139d628a0SDimitry Andric auto I = DeferredEmptyCoverageMappingDecls.find(D); 338239d628a0SDimitry Andric if (I == DeferredEmptyCoverageMappingDecls.end()) 338339d628a0SDimitry Andric DeferredEmptyCoverageMappingDecls[D] = false; 338439d628a0SDimitry Andric else 338539d628a0SDimitry Andric I->second = false; 338639d628a0SDimitry Andric } 338739d628a0SDimitry Andric 338839d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 338939d628a0SDimitry Andric std::vector<const Decl *> DeferredDecls; 339039d628a0SDimitry Andric for (const auto I : DeferredEmptyCoverageMappingDecls) { 339139d628a0SDimitry Andric if (!I.second) 339239d628a0SDimitry Andric continue; 339339d628a0SDimitry Andric DeferredDecls.push_back(I.first); 339439d628a0SDimitry Andric } 339539d628a0SDimitry Andric // Sort the declarations by their location to make sure that the tests get a 339639d628a0SDimitry Andric // predictable order for the coverage mapping for the unused declarations. 339739d628a0SDimitry Andric if (CodeGenOpts.DumpCoverageMapping) 339839d628a0SDimitry Andric std::sort(DeferredDecls.begin(), DeferredDecls.end(), 339939d628a0SDimitry Andric [] (const Decl *LHS, const Decl *RHS) { 340039d628a0SDimitry Andric return LHS->getLocStart() < RHS->getLocStart(); 340139d628a0SDimitry Andric }); 340239d628a0SDimitry Andric for (const auto *D : DeferredDecls) { 340339d628a0SDimitry Andric switch (D->getKind()) { 340439d628a0SDimitry Andric case Decl::CXXConversion: 340539d628a0SDimitry Andric case Decl::CXXMethod: 340639d628a0SDimitry Andric case Decl::Function: 340739d628a0SDimitry Andric case Decl::ObjCMethod: { 340839d628a0SDimitry Andric CodeGenPGO PGO(*this); 340939d628a0SDimitry Andric GlobalDecl GD(cast<FunctionDecl>(D)); 341039d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 341139d628a0SDimitry Andric getFunctionLinkage(GD)); 341239d628a0SDimitry Andric break; 341339d628a0SDimitry Andric } 341439d628a0SDimitry Andric case Decl::CXXConstructor: { 341539d628a0SDimitry Andric CodeGenPGO PGO(*this); 341639d628a0SDimitry Andric GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 341739d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 341839d628a0SDimitry Andric getFunctionLinkage(GD)); 341939d628a0SDimitry Andric break; 342039d628a0SDimitry Andric } 342139d628a0SDimitry Andric case Decl::CXXDestructor: { 342239d628a0SDimitry Andric CodeGenPGO PGO(*this); 342339d628a0SDimitry Andric GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 342439d628a0SDimitry Andric PGO.emitEmptyCounterMapping(D, getMangledName(GD), 342539d628a0SDimitry Andric getFunctionLinkage(GD)); 342639d628a0SDimitry Andric break; 342739d628a0SDimitry Andric } 342839d628a0SDimitry Andric default: 342939d628a0SDimitry Andric break; 343039d628a0SDimitry Andric }; 3431f22ef01cSRoman Divacky } 3432f22ef01cSRoman Divacky } 3433ffd1746dSEd Schouten 3434ffd1746dSEd Schouten /// Turns the given pointer into a constant. 3435ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 3436ffd1746dSEd Schouten const void *Ptr) { 3437ffd1746dSEd Schouten uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 34386122f3e6SDimitry Andric llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 3439ffd1746dSEd Schouten return llvm::ConstantInt::get(i64, PtrInt); 3440ffd1746dSEd Schouten } 3441ffd1746dSEd Schouten 3442ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 3443ffd1746dSEd Schouten llvm::NamedMDNode *&GlobalMetadata, 3444ffd1746dSEd Schouten GlobalDecl D, 3445ffd1746dSEd Schouten llvm::GlobalValue *Addr) { 3446ffd1746dSEd Schouten if (!GlobalMetadata) 3447ffd1746dSEd Schouten GlobalMetadata = 3448ffd1746dSEd Schouten CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 3449ffd1746dSEd Schouten 3450ffd1746dSEd Schouten // TODO: should we report variant information for ctors/dtors? 345139d628a0SDimitry Andric llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 345239d628a0SDimitry Andric llvm::ConstantAsMetadata::get(GetPointerConstant( 345339d628a0SDimitry Andric CGM.getLLVMContext(), D.getDecl()))}; 34543b0f4066SDimitry Andric GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 3455ffd1746dSEd Schouten } 3456ffd1746dSEd Schouten 3457284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked 3458284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled 3459284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer 3460284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the 3461284c1978SDimitry Andric /// same translation unit. 3462284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() { 3463284c1978SDimitry Andric for (StaticExternCMap::iterator I = StaticExternCValues.begin(), 3464284c1978SDimitry Andric E = StaticExternCValues.end(); 3465284c1978SDimitry Andric I != E; ++I) { 3466284c1978SDimitry Andric IdentifierInfo *Name = I->first; 3467284c1978SDimitry Andric llvm::GlobalValue *Val = I->second; 3468284c1978SDimitry Andric if (Val && !getModule().getNamedValue(Name->getName())) 346959d1ed5bSDimitry Andric addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 3470284c1978SDimitry Andric } 3471284c1978SDimitry Andric } 3472284c1978SDimitry Andric 347359d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 347459d1ed5bSDimitry Andric GlobalDecl &Result) const { 347559d1ed5bSDimitry Andric auto Res = Manglings.find(MangledName); 347659d1ed5bSDimitry Andric if (Res == Manglings.end()) 347759d1ed5bSDimitry Andric return false; 347859d1ed5bSDimitry Andric Result = Res->getValue(); 347959d1ed5bSDimitry Andric return true; 348059d1ed5bSDimitry Andric } 348159d1ed5bSDimitry Andric 3482ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the 3483ffd1746dSEd Schouten /// current module with the Decls they came from. This is useful for 3484ffd1746dSEd Schouten /// projects using IR gen as a subroutine. 3485ffd1746dSEd Schouten /// 3486ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly 3487ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata 3488ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'. 3489ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() { 349059d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 3491ffd1746dSEd Schouten 3492ffd1746dSEd Schouten // StaticLocalDeclMap 349359d1ed5bSDimitry Andric for (auto &I : MangledDeclNames) { 349459d1ed5bSDimitry Andric llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 349559d1ed5bSDimitry Andric EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 3496ffd1746dSEd Schouten } 3497ffd1746dSEd Schouten } 3498ffd1746dSEd Schouten 3499ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current 3500ffd1746dSEd Schouten /// function. 3501ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() { 3502ffd1746dSEd Schouten if (LocalDeclMap.empty()) return; 3503ffd1746dSEd Schouten 3504ffd1746dSEd Schouten llvm::LLVMContext &Context = getLLVMContext(); 3505ffd1746dSEd Schouten 3506ffd1746dSEd Schouten // Find the unique metadata ID for this name. 3507ffd1746dSEd Schouten unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 3508ffd1746dSEd Schouten 350959d1ed5bSDimitry Andric llvm::NamedMDNode *GlobalMetadata = nullptr; 3510ffd1746dSEd Schouten 351159d1ed5bSDimitry Andric for (auto &I : LocalDeclMap) { 351259d1ed5bSDimitry Andric const Decl *D = I.first; 351359d1ed5bSDimitry Andric llvm::Value *Addr = I.second; 351459d1ed5bSDimitry Andric if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 3515ffd1746dSEd Schouten llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 351639d628a0SDimitry Andric Alloca->setMetadata( 351739d628a0SDimitry Andric DeclPtrKind, llvm::MDNode::get( 351839d628a0SDimitry Andric Context, llvm::ValueAsMetadata::getConstant(DAddr))); 351959d1ed5bSDimitry Andric } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 3520ffd1746dSEd Schouten GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 3521ffd1746dSEd Schouten EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 3522ffd1746dSEd Schouten } 3523ffd1746dSEd Schouten } 3524ffd1746dSEd Schouten } 3525e580952dSDimitry Andric 3526f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() { 3527f785676fSDimitry Andric llvm::NamedMDNode *IdentMetadata = 3528f785676fSDimitry Andric TheModule.getOrInsertNamedMetadata("llvm.ident"); 3529f785676fSDimitry Andric std::string Version = getClangFullVersion(); 3530f785676fSDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 3531f785676fSDimitry Andric 353239d628a0SDimitry Andric llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 3533f785676fSDimitry Andric IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 3534f785676fSDimitry Andric } 3535f785676fSDimitry Andric 353659d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() { 353739d628a0SDimitry Andric // Warning, new MangledDeclNames may be appended within this loop. 353839d628a0SDimitry Andric // We rely on MapVector insertions adding new elements to the end 353939d628a0SDimitry Andric // of the container. 354039d628a0SDimitry Andric // FIXME: Move this loop into the one target that needs it, and only 354139d628a0SDimitry Andric // loop over those declarations for which we couldn't emit the target 354239d628a0SDimitry Andric // metadata when we emitted the declaration. 354339d628a0SDimitry Andric for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 354439d628a0SDimitry Andric auto Val = *(MangledDeclNames.begin() + I); 354539d628a0SDimitry Andric const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 354639d628a0SDimitry Andric llvm::GlobalValue *GV = GetGlobalValue(Val.second); 354759d1ed5bSDimitry Andric getTargetCodeGenInfo().emitTargetMD(D, GV, *this); 354859d1ed5bSDimitry Andric } 354959d1ed5bSDimitry Andric } 355059d1ed5bSDimitry Andric 3551bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() { 3552bd5abe19SDimitry Andric if (!getCodeGenOpts().CoverageFile.empty()) { 3553bd5abe19SDimitry Andric if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 3554bd5abe19SDimitry Andric llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 3555bd5abe19SDimitry Andric llvm::LLVMContext &Ctx = TheModule.getContext(); 3556bd5abe19SDimitry Andric llvm::MDString *CoverageFile = 3557bd5abe19SDimitry Andric llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 3558bd5abe19SDimitry Andric for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 3559bd5abe19SDimitry Andric llvm::MDNode *CU = CUNode->getOperand(i); 356039d628a0SDimitry Andric llvm::Metadata *Elts[] = {CoverageFile, CU}; 356139d628a0SDimitry Andric GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 3562bd5abe19SDimitry Andric } 3563bd5abe19SDimitry Andric } 3564bd5abe19SDimitry Andric } 3565bd5abe19SDimitry Andric } 35663861d79fSDimitry Andric 356739d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) { 35683861d79fSDimitry Andric // Sema has checked that all uuid strings are of the form 35693861d79fSDimitry Andric // "12345678-1234-1234-1234-1234567890ab". 35703861d79fSDimitry Andric assert(Uuid.size() == 36); 3571f785676fSDimitry Andric for (unsigned i = 0; i < 36; ++i) { 3572f785676fSDimitry Andric if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-'); 3573f785676fSDimitry Andric else assert(isHexDigit(Uuid[i])); 35743861d79fSDimitry Andric } 35753861d79fSDimitry Andric 357639d628a0SDimitry Andric // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab". 3577f785676fSDimitry Andric const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 }; 35783861d79fSDimitry Andric 3579f785676fSDimitry Andric llvm::Constant *Field3[8]; 3580f785676fSDimitry Andric for (unsigned Idx = 0; Idx < 8; ++Idx) 3581f785676fSDimitry Andric Field3[Idx] = llvm::ConstantInt::get( 3582f785676fSDimitry Andric Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16); 35833861d79fSDimitry Andric 3584f785676fSDimitry Andric llvm::Constant *Fields[4] = { 3585f785676fSDimitry Andric llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16), 3586f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16), 3587f785676fSDimitry Andric llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16), 3588f785676fSDimitry Andric llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3) 3589f785676fSDimitry Andric }; 3590f785676fSDimitry Andric 3591f785676fSDimitry Andric return llvm::ConstantStruct::getAnon(Fields); 35923861d79fSDimitry Andric } 359359d1ed5bSDimitry Andric 359459d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 359559d1ed5bSDimitry Andric bool ForEH) { 359659d1ed5bSDimitry Andric // Return a bogus pointer if RTTI is disabled, unless it's for EH. 359759d1ed5bSDimitry Andric // FIXME: should we even be calling this method if RTTI is disabled 359859d1ed5bSDimitry Andric // and it's not for EH? 359959d1ed5bSDimitry Andric if (!ForEH && !getLangOpts().RTTI) 360059d1ed5bSDimitry Andric return llvm::Constant::getNullValue(Int8PtrTy); 360159d1ed5bSDimitry Andric 360259d1ed5bSDimitry Andric if (ForEH && Ty->isObjCObjectPointerType() && 360359d1ed5bSDimitry Andric LangOpts.ObjCRuntime.isGNUFamily()) 360459d1ed5bSDimitry Andric return ObjCRuntime->GetEHType(Ty); 360559d1ed5bSDimitry Andric 360659d1ed5bSDimitry Andric return getCXXABI().getAddrOfRTTIDescriptor(Ty); 360759d1ed5bSDimitry Andric } 360859d1ed5bSDimitry Andric 360939d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 361039d628a0SDimitry Andric for (auto RefExpr : D->varlists()) { 361139d628a0SDimitry Andric auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 361239d628a0SDimitry Andric bool PerformInit = 361339d628a0SDimitry Andric VD->getAnyInitializer() && 361439d628a0SDimitry Andric !VD->getAnyInitializer()->isConstantInitializer(getContext(), 361539d628a0SDimitry Andric /*ForRef=*/false); 361639d628a0SDimitry Andric if (auto InitFunction = 361739d628a0SDimitry Andric getOpenMPRuntime().EmitOMPThreadPrivateVarDefinition( 361839d628a0SDimitry Andric VD, GetAddrOfGlobalVar(VD), RefExpr->getLocStart(), 361939d628a0SDimitry Andric PerformInit)) 362039d628a0SDimitry Andric CXXGlobalInits.push_back(InitFunction); 362139d628a0SDimitry Andric } 362239d628a0SDimitry Andric } 362339d628a0SDimitry Andric 3624