xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision d65cd7a57bf0600b722afc770838a5d0c1c3a8e1)
10b57cec5SDimitry Andric //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This coordinates the per-module state used while generating code.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "CodeGenModule.h"
140b57cec5SDimitry Andric #include "CGBlocks.h"
150b57cec5SDimitry Andric #include "CGCUDARuntime.h"
160b57cec5SDimitry Andric #include "CGCXXABI.h"
170b57cec5SDimitry Andric #include "CGCall.h"
180b57cec5SDimitry Andric #include "CGDebugInfo.h"
190b57cec5SDimitry Andric #include "CGObjCRuntime.h"
200b57cec5SDimitry Andric #include "CGOpenCLRuntime.h"
210b57cec5SDimitry Andric #include "CGOpenMPRuntime.h"
220b57cec5SDimitry Andric #include "CGOpenMPRuntimeNVPTX.h"
230b57cec5SDimitry Andric #include "CodeGenFunction.h"
240b57cec5SDimitry Andric #include "CodeGenPGO.h"
250b57cec5SDimitry Andric #include "ConstantEmitter.h"
260b57cec5SDimitry Andric #include "CoverageMappingGen.h"
270b57cec5SDimitry Andric #include "TargetInfo.h"
280b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
290b57cec5SDimitry Andric #include "clang/AST/CharUnits.h"
300b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
310b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
320b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
330b57cec5SDimitry Andric #include "clang/AST/Mangle.h"
340b57cec5SDimitry Andric #include "clang/AST/RecordLayout.h"
350b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
360b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h"
370b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
380b57cec5SDimitry Andric #include "clang/Basic/CharInfo.h"
390b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
400b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
410b57cec5SDimitry Andric #include "clang/Basic/Module.h"
420b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
430b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
440b57cec5SDimitry Andric #include "clang/Basic/Version.h"
450b57cec5SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h"
460b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h"
470b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
480b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
490b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
50480093f4SDimitry Andric #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
510b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
520b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
530b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
540b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
550b57cec5SDimitry Andric #include "llvm/IR/Module.h"
560b57cec5SDimitry Andric #include "llvm/IR/ProfileSummary.h"
570b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
580b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
59480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
600b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h"
610b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
620b57cec5SDimitry Andric #include "llvm/Support/MD5.h"
630b57cec5SDimitry Andric #include "llvm/Support/TimeProfiler.h"
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric using namespace clang;
660b57cec5SDimitry Andric using namespace CodeGen;
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric static llvm::cl::opt<bool> LimitedCoverage(
690b57cec5SDimitry Andric     "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
700b57cec5SDimitry Andric     llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
710b57cec5SDimitry Andric     llvm::cl::init(false));
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
760b57cec5SDimitry Andric   switch (CGM.getTarget().getCXXABI().getKind()) {
77480093f4SDimitry Andric   case TargetCXXABI::Fuchsia:
780b57cec5SDimitry Andric   case TargetCXXABI::GenericAArch64:
790b57cec5SDimitry Andric   case TargetCXXABI::GenericARM:
800b57cec5SDimitry Andric   case TargetCXXABI::iOS:
810b57cec5SDimitry Andric   case TargetCXXABI::iOS64:
820b57cec5SDimitry Andric   case TargetCXXABI::WatchOS:
830b57cec5SDimitry Andric   case TargetCXXABI::GenericMIPS:
840b57cec5SDimitry Andric   case TargetCXXABI::GenericItanium:
850b57cec5SDimitry Andric   case TargetCXXABI::WebAssembly:
860b57cec5SDimitry Andric     return CreateItaniumCXXABI(CGM);
870b57cec5SDimitry Andric   case TargetCXXABI::Microsoft:
880b57cec5SDimitry Andric     return CreateMicrosoftCXXABI(CGM);
890b57cec5SDimitry Andric   }
900b57cec5SDimitry Andric 
910b57cec5SDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
920b57cec5SDimitry Andric }
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
950b57cec5SDimitry Andric                              const PreprocessorOptions &PPO,
960b57cec5SDimitry Andric                              const CodeGenOptions &CGO, llvm::Module &M,
970b57cec5SDimitry Andric                              DiagnosticsEngine &diags,
980b57cec5SDimitry Andric                              CoverageSourceInfo *CoverageInfo)
990b57cec5SDimitry Andric     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
1000b57cec5SDimitry Andric       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
1010b57cec5SDimitry Andric       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
1020b57cec5SDimitry Andric       VMContext(M.getContext()), Types(*this), VTables(*this),
1030b57cec5SDimitry Andric       SanitizerMD(new SanitizerMetadata(*this)) {
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric   // Initialize the type cache.
1060b57cec5SDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
1070b57cec5SDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
1080b57cec5SDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
1090b57cec5SDimitry Andric   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
1100b57cec5SDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
1110b57cec5SDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
1120b57cec5SDimitry Andric   HalfTy = llvm::Type::getHalfTy(LLVMContext);
1130b57cec5SDimitry Andric   FloatTy = llvm::Type::getFloatTy(LLVMContext);
1140b57cec5SDimitry Andric   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
1150b57cec5SDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
1160b57cec5SDimitry Andric   PointerAlignInBytes =
1170b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
1180b57cec5SDimitry Andric   SizeSizeInBytes =
1190b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
1200b57cec5SDimitry Andric   IntAlignInBytes =
1210b57cec5SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
1220b57cec5SDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
1230b57cec5SDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext,
1240b57cec5SDimitry Andric     C.getTargetInfo().getMaxPointerWidth());
1250b57cec5SDimitry Andric   Int8PtrTy = Int8Ty->getPointerTo(0);
1260b57cec5SDimitry Andric   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
1270b57cec5SDimitry Andric   AllocaInt8PtrTy = Int8Ty->getPointerTo(
1280b57cec5SDimitry Andric       M.getDataLayout().getAllocaAddrSpace());
1290b57cec5SDimitry Andric   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   if (LangOpts.ObjC)
1340b57cec5SDimitry Andric     createObjCRuntime();
1350b57cec5SDimitry Andric   if (LangOpts.OpenCL)
1360b57cec5SDimitry Andric     createOpenCLRuntime();
1370b57cec5SDimitry Andric   if (LangOpts.OpenMP)
1380b57cec5SDimitry Andric     createOpenMPRuntime();
1390b57cec5SDimitry Andric   if (LangOpts.CUDA)
1400b57cec5SDimitry Andric     createCUDARuntime();
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
1430b57cec5SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
1440b57cec5SDimitry Andric       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
1450b57cec5SDimitry Andric     TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
1460b57cec5SDimitry Andric                                getCXXABI().getMangleContext()));
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
1490b57cec5SDimitry Andric   // object.
1500b57cec5SDimitry Andric   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
1510b57cec5SDimitry Andric       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
1520b57cec5SDimitry Andric     DebugInfo.reset(new CGDebugInfo(*this));
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric   Block.GlobalUniqueCount = 0;
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric   if (C.getLangOpts().ObjC)
1570b57cec5SDimitry Andric     ObjCData.reset(new ObjCEntrypoints());
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric   if (CodeGenOpts.hasProfileClangUse()) {
1600b57cec5SDimitry Andric     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
1610b57cec5SDimitry Andric         CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
1620b57cec5SDimitry Andric     if (auto E = ReaderOrErr.takeError()) {
1630b57cec5SDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1640b57cec5SDimitry Andric                                               "Could not read profile %0: %1");
1650b57cec5SDimitry Andric       llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
1660b57cec5SDimitry Andric         getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
1670b57cec5SDimitry Andric                                   << EI.message();
1680b57cec5SDimitry Andric       });
1690b57cec5SDimitry Andric     } else
1700b57cec5SDimitry Andric       PGOReader = std::move(ReaderOrErr.get());
1710b57cec5SDimitry Andric   }
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   // If coverage mapping generation is enabled, create the
1740b57cec5SDimitry Andric   // CoverageMappingModuleGen object.
1750b57cec5SDimitry Andric   if (CodeGenOpts.CoverageMapping)
1760b57cec5SDimitry Andric     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
1770b57cec5SDimitry Andric }
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric CodeGenModule::~CodeGenModule() {}
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric void CodeGenModule::createObjCRuntime() {
1820b57cec5SDimitry Andric   // This is just isGNUFamily(), but we want to force implementors of
1830b57cec5SDimitry Andric   // new ABIs to decide how best to do this.
1840b57cec5SDimitry Andric   switch (LangOpts.ObjCRuntime.getKind()) {
1850b57cec5SDimitry Andric   case ObjCRuntime::GNUstep:
1860b57cec5SDimitry Andric   case ObjCRuntime::GCC:
1870b57cec5SDimitry Andric   case ObjCRuntime::ObjFW:
1880b57cec5SDimitry Andric     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
1890b57cec5SDimitry Andric     return;
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric   case ObjCRuntime::FragileMacOSX:
1920b57cec5SDimitry Andric   case ObjCRuntime::MacOSX:
1930b57cec5SDimitry Andric   case ObjCRuntime::iOS:
1940b57cec5SDimitry Andric   case ObjCRuntime::WatchOS:
1950b57cec5SDimitry Andric     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
1960b57cec5SDimitry Andric     return;
1970b57cec5SDimitry Andric   }
1980b57cec5SDimitry Andric   llvm_unreachable("bad runtime kind");
1990b57cec5SDimitry Andric }
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
2020b57cec5SDimitry Andric   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
2030b57cec5SDimitry Andric }
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric void CodeGenModule::createOpenMPRuntime() {
2060b57cec5SDimitry Andric   // Select a specialized code generation class based on the target, if any.
2070b57cec5SDimitry Andric   // If it does not exist use the default implementation.
2080b57cec5SDimitry Andric   switch (getTriple().getArch()) {
2090b57cec5SDimitry Andric   case llvm::Triple::nvptx:
2100b57cec5SDimitry Andric   case llvm::Triple::nvptx64:
2110b57cec5SDimitry Andric     assert(getLangOpts().OpenMPIsDevice &&
2120b57cec5SDimitry Andric            "OpenMP NVPTX is only prepared to deal with device code.");
2130b57cec5SDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
2140b57cec5SDimitry Andric     break;
2150b57cec5SDimitry Andric   default:
2160b57cec5SDimitry Andric     if (LangOpts.OpenMPSimd)
2170b57cec5SDimitry Andric       OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
2180b57cec5SDimitry Andric     else
2190b57cec5SDimitry Andric       OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
2200b57cec5SDimitry Andric     break;
2210b57cec5SDimitry Andric   }
222480093f4SDimitry Andric 
223480093f4SDimitry Andric   // The OpenMP-IR-Builder should eventually replace the above runtime codegens
224480093f4SDimitry Andric   // but we are not there yet so they both reside in CGModule for now and the
225480093f4SDimitry Andric   // OpenMP-IR-Builder is opt-in only.
226480093f4SDimitry Andric   if (LangOpts.OpenMPIRBuilder) {
227480093f4SDimitry Andric     OMPBuilder.reset(new llvm::OpenMPIRBuilder(TheModule));
228480093f4SDimitry Andric     OMPBuilder->initialize();
229480093f4SDimitry Andric   }
2300b57cec5SDimitry Andric }
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric void CodeGenModule::createCUDARuntime() {
2330b57cec5SDimitry Andric   CUDARuntime.reset(CreateNVCUDARuntime(*this));
2340b57cec5SDimitry Andric }
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
2370b57cec5SDimitry Andric   Replacements[Name] = C;
2380b57cec5SDimitry Andric }
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric void CodeGenModule::applyReplacements() {
2410b57cec5SDimitry Andric   for (auto &I : Replacements) {
2420b57cec5SDimitry Andric     StringRef MangledName = I.first();
2430b57cec5SDimitry Andric     llvm::Constant *Replacement = I.second;
2440b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2450b57cec5SDimitry Andric     if (!Entry)
2460b57cec5SDimitry Andric       continue;
2470b57cec5SDimitry Andric     auto *OldF = cast<llvm::Function>(Entry);
2480b57cec5SDimitry Andric     auto *NewF = dyn_cast<llvm::Function>(Replacement);
2490b57cec5SDimitry Andric     if (!NewF) {
2500b57cec5SDimitry Andric       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
2510b57cec5SDimitry Andric         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
2520b57cec5SDimitry Andric       } else {
2530b57cec5SDimitry Andric         auto *CE = cast<llvm::ConstantExpr>(Replacement);
2540b57cec5SDimitry Andric         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2550b57cec5SDimitry Andric                CE->getOpcode() == llvm::Instruction::GetElementPtr);
2560b57cec5SDimitry Andric         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
2570b57cec5SDimitry Andric       }
2580b57cec5SDimitry Andric     }
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric     // Replace old with new, but keep the old order.
2610b57cec5SDimitry Andric     OldF->replaceAllUsesWith(Replacement);
2620b57cec5SDimitry Andric     if (NewF) {
2630b57cec5SDimitry Andric       NewF->removeFromParent();
2640b57cec5SDimitry Andric       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
2650b57cec5SDimitry Andric                                                        NewF);
2660b57cec5SDimitry Andric     }
2670b57cec5SDimitry Andric     OldF->eraseFromParent();
2680b57cec5SDimitry Andric   }
2690b57cec5SDimitry Andric }
2700b57cec5SDimitry Andric 
2710b57cec5SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
2720b57cec5SDimitry Andric   GlobalValReplacements.push_back(std::make_pair(GV, C));
2730b57cec5SDimitry Andric }
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric void CodeGenModule::applyGlobalValReplacements() {
2760b57cec5SDimitry Andric   for (auto &I : GlobalValReplacements) {
2770b57cec5SDimitry Andric     llvm::GlobalValue *GV = I.first;
2780b57cec5SDimitry Andric     llvm::Constant *C = I.second;
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric     GV->replaceAllUsesWith(C);
2810b57cec5SDimitry Andric     GV->eraseFromParent();
2820b57cec5SDimitry Andric   }
2830b57cec5SDimitry Andric }
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric // This is only used in aliases that we created and we know they have a
2860b57cec5SDimitry Andric // linear structure.
2870b57cec5SDimitry Andric static const llvm::GlobalObject *getAliasedGlobal(
2880b57cec5SDimitry Andric     const llvm::GlobalIndirectSymbol &GIS) {
2890b57cec5SDimitry Andric   llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
2900b57cec5SDimitry Andric   const llvm::Constant *C = &GIS;
2910b57cec5SDimitry Andric   for (;;) {
2920b57cec5SDimitry Andric     C = C->stripPointerCasts();
2930b57cec5SDimitry Andric     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
2940b57cec5SDimitry Andric       return GO;
2950b57cec5SDimitry Andric     // stripPointerCasts will not walk over weak aliases.
2960b57cec5SDimitry Andric     auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
2970b57cec5SDimitry Andric     if (!GIS2)
2980b57cec5SDimitry Andric       return nullptr;
2990b57cec5SDimitry Andric     if (!Visited.insert(GIS2).second)
3000b57cec5SDimitry Andric       return nullptr;
3010b57cec5SDimitry Andric     C = GIS2->getIndirectSymbol();
3020b57cec5SDimitry Andric   }
3030b57cec5SDimitry Andric }
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric void CodeGenModule::checkAliases() {
3060b57cec5SDimitry Andric   // Check if the constructed aliases are well formed. It is really unfortunate
3070b57cec5SDimitry Andric   // that we have to do this in CodeGen, but we only construct mangled names
3080b57cec5SDimitry Andric   // and aliases during codegen.
3090b57cec5SDimitry Andric   bool Error = false;
3100b57cec5SDimitry Andric   DiagnosticsEngine &Diags = getDiags();
3110b57cec5SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
3120b57cec5SDimitry Andric     const auto *D = cast<ValueDecl>(GD.getDecl());
3130b57cec5SDimitry Andric     SourceLocation Location;
3140b57cec5SDimitry Andric     bool IsIFunc = D->hasAttr<IFuncAttr>();
3150b57cec5SDimitry Andric     if (const Attr *A = D->getDefiningAttr())
3160b57cec5SDimitry Andric       Location = A->getLocation();
3170b57cec5SDimitry Andric     else
3180b57cec5SDimitry Andric       llvm_unreachable("Not an alias or ifunc?");
3190b57cec5SDimitry Andric     StringRef MangledName = getMangledName(GD);
3200b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3210b57cec5SDimitry Andric     auto *Alias  = cast<llvm::GlobalIndirectSymbol>(Entry);
3220b57cec5SDimitry Andric     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
3230b57cec5SDimitry Andric     if (!GV) {
3240b57cec5SDimitry Andric       Error = true;
3250b57cec5SDimitry Andric       Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
3260b57cec5SDimitry Andric     } else if (GV->isDeclaration()) {
3270b57cec5SDimitry Andric       Error = true;
3280b57cec5SDimitry Andric       Diags.Report(Location, diag::err_alias_to_undefined)
3290b57cec5SDimitry Andric           << IsIFunc << IsIFunc;
3300b57cec5SDimitry Andric     } else if (IsIFunc) {
3310b57cec5SDimitry Andric       // Check resolver function type.
3320b57cec5SDimitry Andric       llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
3330b57cec5SDimitry Andric           GV->getType()->getPointerElementType());
3340b57cec5SDimitry Andric       assert(FTy);
3350b57cec5SDimitry Andric       if (!FTy->getReturnType()->isPointerTy())
3360b57cec5SDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_return);
3370b57cec5SDimitry Andric     }
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric     llvm::Constant *Aliasee = Alias->getIndirectSymbol();
3400b57cec5SDimitry Andric     llvm::GlobalValue *AliaseeGV;
3410b57cec5SDimitry Andric     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
3420b57cec5SDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
3430b57cec5SDimitry Andric     else
3440b57cec5SDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3470b57cec5SDimitry Andric       StringRef AliasSection = SA->getName();
3480b57cec5SDimitry Andric       if (AliasSection != AliaseeGV->getSection())
3490b57cec5SDimitry Andric         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
3500b57cec5SDimitry Andric             << AliasSection << IsIFunc << IsIFunc;
3510b57cec5SDimitry Andric     }
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric     // We have to handle alias to weak aliases in here. LLVM itself disallows
3540b57cec5SDimitry Andric     // this since the object semantics would not match the IL one. For
3550b57cec5SDimitry Andric     // compatibility with gcc we implement it by just pointing the alias
3560b57cec5SDimitry Andric     // to its aliasee's aliasee. We also warn, since the user is probably
3570b57cec5SDimitry Andric     // expecting the link to be weak.
3580b57cec5SDimitry Andric     if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
3590b57cec5SDimitry Andric       if (GA->isInterposable()) {
3600b57cec5SDimitry Andric         Diags.Report(Location, diag::warn_alias_to_weak_alias)
3610b57cec5SDimitry Andric             << GV->getName() << GA->getName() << IsIFunc;
3620b57cec5SDimitry Andric         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
3630b57cec5SDimitry Andric             GA->getIndirectSymbol(), Alias->getType());
3640b57cec5SDimitry Andric         Alias->setIndirectSymbol(Aliasee);
3650b57cec5SDimitry Andric       }
3660b57cec5SDimitry Andric     }
3670b57cec5SDimitry Andric   }
3680b57cec5SDimitry Andric   if (!Error)
3690b57cec5SDimitry Andric     return;
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
3720b57cec5SDimitry Andric     StringRef MangledName = getMangledName(GD);
3730b57cec5SDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3740b57cec5SDimitry Andric     auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
3750b57cec5SDimitry Andric     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
3760b57cec5SDimitry Andric     Alias->eraseFromParent();
3770b57cec5SDimitry Andric   }
3780b57cec5SDimitry Andric }
3790b57cec5SDimitry Andric 
3800b57cec5SDimitry Andric void CodeGenModule::clear() {
3810b57cec5SDimitry Andric   DeferredDeclsToEmit.clear();
3820b57cec5SDimitry Andric   if (OpenMPRuntime)
3830b57cec5SDimitry Andric     OpenMPRuntime->clear();
3840b57cec5SDimitry Andric }
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
3870b57cec5SDimitry Andric                                        StringRef MainFile) {
3880b57cec5SDimitry Andric   if (!hasDiagnostics())
3890b57cec5SDimitry Andric     return;
3900b57cec5SDimitry Andric   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
3910b57cec5SDimitry Andric     if (MainFile.empty())
3920b57cec5SDimitry Andric       MainFile = "<stdin>";
3930b57cec5SDimitry Andric     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
3940b57cec5SDimitry Andric   } else {
3950b57cec5SDimitry Andric     if (Mismatched > 0)
3960b57cec5SDimitry Andric       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric     if (Missing > 0)
3990b57cec5SDimitry Andric       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
4000b57cec5SDimitry Andric   }
4010b57cec5SDimitry Andric }
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric void CodeGenModule::Release() {
4040b57cec5SDimitry Andric   EmitDeferred();
4050b57cec5SDimitry Andric   EmitVTablesOpportunistically();
4060b57cec5SDimitry Andric   applyGlobalValReplacements();
4070b57cec5SDimitry Andric   applyReplacements();
4080b57cec5SDimitry Andric   checkAliases();
4090b57cec5SDimitry Andric   emitMultiVersionFunctions();
4100b57cec5SDimitry Andric   EmitCXXGlobalInitFunc();
4110b57cec5SDimitry Andric   EmitCXXGlobalDtorFunc();
4120b57cec5SDimitry Andric   registerGlobalDtorsWithAtExit();
4130b57cec5SDimitry Andric   EmitCXXThreadLocalInitFunc();
4140b57cec5SDimitry Andric   if (ObjCRuntime)
4150b57cec5SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
4160b57cec5SDimitry Andric       AddGlobalCtor(ObjCInitFunction);
4170b57cec5SDimitry Andric   if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
4180b57cec5SDimitry Andric       CUDARuntime) {
4190b57cec5SDimitry Andric     if (llvm::Function *CudaCtorFunction =
4200b57cec5SDimitry Andric             CUDARuntime->makeModuleCtorFunction())
4210b57cec5SDimitry Andric       AddGlobalCtor(CudaCtorFunction);
4220b57cec5SDimitry Andric   }
4230b57cec5SDimitry Andric   if (OpenMPRuntime) {
4240b57cec5SDimitry Andric     if (llvm::Function *OpenMPRequiresDirectiveRegFun =
4250b57cec5SDimitry Andric             OpenMPRuntime->emitRequiresDirectiveRegFun()) {
4260b57cec5SDimitry Andric       AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
4270b57cec5SDimitry Andric     }
428a7dea167SDimitry Andric     OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
4290b57cec5SDimitry Andric     OpenMPRuntime->clear();
4300b57cec5SDimitry Andric   }
4310b57cec5SDimitry Andric   if (PGOReader) {
4320b57cec5SDimitry Andric     getModule().setProfileSummary(
4330b57cec5SDimitry Andric         PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
4340b57cec5SDimitry Andric         llvm::ProfileSummary::PSK_Instr);
4350b57cec5SDimitry Andric     if (PGOStats.hasDiagnostics())
4360b57cec5SDimitry Andric       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
4370b57cec5SDimitry Andric   }
4380b57cec5SDimitry Andric   EmitCtorList(GlobalCtors, "llvm.global_ctors");
4390b57cec5SDimitry Andric   EmitCtorList(GlobalDtors, "llvm.global_dtors");
4400b57cec5SDimitry Andric   EmitGlobalAnnotations();
4410b57cec5SDimitry Andric   EmitStaticExternCAliases();
4420b57cec5SDimitry Andric   EmitDeferredUnusedCoverageMappings();
4430b57cec5SDimitry Andric   if (CoverageMapping)
4440b57cec5SDimitry Andric     CoverageMapping->emit();
4450b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
4460b57cec5SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckFail();
4470b57cec5SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckStub();
4480b57cec5SDimitry Andric   }
4490b57cec5SDimitry Andric   emitAtAvailableLinkGuard();
4500b57cec5SDimitry Andric   emitLLVMUsed();
4510b57cec5SDimitry Andric   if (SanStats)
4520b57cec5SDimitry Andric     SanStats->finish();
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric   if (CodeGenOpts.Autolink &&
4550b57cec5SDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
4560b57cec5SDimitry Andric     EmitModuleLinkOptions();
4570b57cec5SDimitry Andric   }
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric   // On ELF we pass the dependent library specifiers directly to the linker
4600b57cec5SDimitry Andric   // without manipulating them. This is in contrast to other platforms where
4610b57cec5SDimitry Andric   // they are mapped to a specific linker option by the compiler. This
4620b57cec5SDimitry Andric   // difference is a result of the greater variety of ELF linkers and the fact
4630b57cec5SDimitry Andric   // that ELF linkers tend to handle libraries in a more complicated fashion
4640b57cec5SDimitry Andric   // than on other platforms. This forces us to defer handling the dependent
4650b57cec5SDimitry Andric   // libs to the linker.
4660b57cec5SDimitry Andric   //
4670b57cec5SDimitry Andric   // CUDA/HIP device and host libraries are different. Currently there is no
4680b57cec5SDimitry Andric   // way to differentiate dependent libraries for host or device. Existing
4690b57cec5SDimitry Andric   // usage of #pragma comment(lib, *) is intended for host libraries on
4700b57cec5SDimitry Andric   // Windows. Therefore emit llvm.dependent-libraries only for host.
4710b57cec5SDimitry Andric   if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
4720b57cec5SDimitry Andric     auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
4730b57cec5SDimitry Andric     for (auto *MD : ELFDependentLibraries)
4740b57cec5SDimitry Andric       NMD->addOperand(MD);
4750b57cec5SDimitry Andric   }
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric   // Record mregparm value now so it is visible through rest of codegen.
4780b57cec5SDimitry Andric   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
4790b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
4800b57cec5SDimitry Andric                               CodeGenOpts.NumRegisterParameters);
4810b57cec5SDimitry Andric 
4820b57cec5SDimitry Andric   if (CodeGenOpts.DwarfVersion) {
483480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
4840b57cec5SDimitry Andric                               CodeGenOpts.DwarfVersion);
4850b57cec5SDimitry Andric   }
4860b57cec5SDimitry Andric   if (CodeGenOpts.EmitCodeView) {
4870b57cec5SDimitry Andric     // Indicate that we want CodeView in the metadata.
4880b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
4890b57cec5SDimitry Andric   }
4900b57cec5SDimitry Andric   if (CodeGenOpts.CodeViewGHash) {
4910b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
4920b57cec5SDimitry Andric   }
4930b57cec5SDimitry Andric   if (CodeGenOpts.ControlFlowGuard) {
494480093f4SDimitry Andric     // Function ID tables and checks for Control Flow Guard (cfguard=2).
495480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
496480093f4SDimitry Andric   } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
497480093f4SDimitry Andric     // Function ID tables for Control Flow Guard (cfguard=1).
498480093f4SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
4990b57cec5SDimitry Andric   }
5000b57cec5SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
5010b57cec5SDimitry Andric     // We don't support LTO with 2 with different StrictVTablePointers
5020b57cec5SDimitry Andric     // FIXME: we could support it by stripping all the information introduced
5030b57cec5SDimitry Andric     // by StrictVTablePointers.
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric     llvm::Metadata *Ops[2] = {
5080b57cec5SDimitry Andric               llvm::MDString::get(VMContext, "StrictVTablePointers"),
5090b57cec5SDimitry Andric               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
5100b57cec5SDimitry Andric                   llvm::Type::getInt32Ty(VMContext), 1))};
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Require,
5130b57cec5SDimitry Andric                               "StrictVTablePointersRequirement",
5140b57cec5SDimitry Andric                               llvm::MDNode::get(VMContext, Ops));
5150b57cec5SDimitry Andric   }
5160b57cec5SDimitry Andric   if (DebugInfo)
5170b57cec5SDimitry Andric     // We support a single version in the linked module. The LLVM
5180b57cec5SDimitry Andric     // parser will drop debug info with a different version number
5190b57cec5SDimitry Andric     // (and warn about it, too).
5200b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
5210b57cec5SDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
5220b57cec5SDimitry Andric 
5230b57cec5SDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
5240b57cec5SDimitry Andric   // the correct build attributes in the ARM backend. wchar_size is also used by
5250b57cec5SDimitry Andric   // TargetLibraryInfo.
5260b57cec5SDimitry Andric   uint64_t WCharWidth =
5270b57cec5SDimitry Andric       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
5280b57cec5SDimitry Andric   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
5310b57cec5SDimitry Andric   if (   Arch == llvm::Triple::arm
5320b57cec5SDimitry Andric       || Arch == llvm::Triple::armeb
5330b57cec5SDimitry Andric       || Arch == llvm::Triple::thumb
5340b57cec5SDimitry Andric       || Arch == llvm::Triple::thumbeb) {
5350b57cec5SDimitry Andric     // The minimum width of an enum in bytes
5360b57cec5SDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
5370b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
5380b57cec5SDimitry Andric   }
5390b57cec5SDimitry Andric 
54013138422SDimitry Andric   if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
54113138422SDimitry Andric     StringRef ABIStr = Target.getABI();
54213138422SDimitry Andric     llvm::LLVMContext &Ctx = TheModule.getContext();
54313138422SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "target-abi",
54413138422SDimitry Andric                               llvm::MDString::get(Ctx, ABIStr));
54513138422SDimitry Andric   }
54613138422SDimitry Andric 
5470b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
5480b57cec5SDimitry Andric     // Indicate that we want cross-DSO control flow integrity checks.
5490b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
5500b57cec5SDimitry Andric   }
5510b57cec5SDimitry Andric 
552a7dea167SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
553a7dea167SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override,
554a7dea167SDimitry Andric                               "CFI Canonical Jump Tables",
555a7dea167SDimitry Andric                               CodeGenOpts.SanitizeCfiCanonicalJumpTables);
556a7dea167SDimitry Andric   }
557a7dea167SDimitry Andric 
5580b57cec5SDimitry Andric   if (CodeGenOpts.CFProtectionReturn &&
5590b57cec5SDimitry Andric       Target.checkCFProtectionReturnSupported(getDiags())) {
5600b57cec5SDimitry Andric     // Indicate that we want to instrument return control flow protection.
5610b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
5620b57cec5SDimitry Andric                               1);
5630b57cec5SDimitry Andric   }
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric   if (CodeGenOpts.CFProtectionBranch &&
5660b57cec5SDimitry Andric       Target.checkCFProtectionBranchSupported(getDiags())) {
5670b57cec5SDimitry Andric     // Indicate that we want to instrument branch control flow protection.
5680b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
5690b57cec5SDimitry Andric                               1);
5700b57cec5SDimitry Andric   }
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
5730b57cec5SDimitry Andric     // Indicate whether __nvvm_reflect should be configured to flush denormal
5740b57cec5SDimitry Andric     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
5750b57cec5SDimitry Andric     // property.)
5760b57cec5SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
5770b57cec5SDimitry Andric                               CodeGenOpts.FlushDenorm ? 1 : 0);
5780b57cec5SDimitry Andric   }
5790b57cec5SDimitry Andric 
5800b57cec5SDimitry Andric   // Emit OpenCL specific module metadata: OpenCL/SPIR version.
5810b57cec5SDimitry Andric   if (LangOpts.OpenCL) {
5820b57cec5SDimitry Andric     EmitOpenCLMetadata();
5830b57cec5SDimitry Andric     // Emit SPIR version.
5840b57cec5SDimitry Andric     if (getTriple().isSPIR()) {
5850b57cec5SDimitry Andric       // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
5860b57cec5SDimitry Andric       // opencl.spir.version named metadata.
5870b57cec5SDimitry Andric       // C++ is backwards compatible with OpenCL v2.0.
5880b57cec5SDimitry Andric       auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
5890b57cec5SDimitry Andric       llvm::Metadata *SPIRVerElts[] = {
5900b57cec5SDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
5910b57cec5SDimitry Andric               Int32Ty, Version / 100)),
5920b57cec5SDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
5930b57cec5SDimitry Andric               Int32Ty, (Version / 100 > 1) ? 0 : 2))};
5940b57cec5SDimitry Andric       llvm::NamedMDNode *SPIRVerMD =
5950b57cec5SDimitry Andric           TheModule.getOrInsertNamedMetadata("opencl.spir.version");
5960b57cec5SDimitry Andric       llvm::LLVMContext &Ctx = TheModule.getContext();
5970b57cec5SDimitry Andric       SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
5980b57cec5SDimitry Andric     }
5990b57cec5SDimitry Andric   }
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
6020b57cec5SDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
6030b57cec5SDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
6040b57cec5SDimitry Andric     if (Context.getLangOpts().PIE)
6050b57cec5SDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
6060b57cec5SDimitry Andric   }
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric   if (getCodeGenOpts().CodeModel.size() > 0) {
6090b57cec5SDimitry Andric     unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
6100b57cec5SDimitry Andric                   .Case("tiny", llvm::CodeModel::Tiny)
6110b57cec5SDimitry Andric                   .Case("small", llvm::CodeModel::Small)
6120b57cec5SDimitry Andric                   .Case("kernel", llvm::CodeModel::Kernel)
6130b57cec5SDimitry Andric                   .Case("medium", llvm::CodeModel::Medium)
6140b57cec5SDimitry Andric                   .Case("large", llvm::CodeModel::Large)
6150b57cec5SDimitry Andric                   .Default(~0u);
6160b57cec5SDimitry Andric     if (CM != ~0u) {
6170b57cec5SDimitry Andric       llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
6180b57cec5SDimitry Andric       getModule().setCodeModel(codeModel);
6190b57cec5SDimitry Andric     }
6200b57cec5SDimitry Andric   }
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric   if (CodeGenOpts.NoPLT)
6230b57cec5SDimitry Andric     getModule().setRtLibUseGOT();
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric   SimplifyPersonality();
6260b57cec5SDimitry Andric 
6270b57cec5SDimitry Andric   if (getCodeGenOpts().EmitDeclMetadata)
6280b57cec5SDimitry Andric     EmitDeclMetadata();
6290b57cec5SDimitry Andric 
6300b57cec5SDimitry Andric   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
6310b57cec5SDimitry Andric     EmitCoverageFile();
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric   if (DebugInfo)
6340b57cec5SDimitry Andric     DebugInfo->finalize();
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric   if (getCodeGenOpts().EmitVersionIdentMetadata)
6370b57cec5SDimitry Andric     EmitVersionIdentMetadata();
6380b57cec5SDimitry Andric 
6390b57cec5SDimitry Andric   if (!getCodeGenOpts().RecordCommandLine.empty())
6400b57cec5SDimitry Andric     EmitCommandLineMetadata();
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric   EmitTargetMetadata();
6430b57cec5SDimitry Andric }
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric void CodeGenModule::EmitOpenCLMetadata() {
6460b57cec5SDimitry Andric   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
6470b57cec5SDimitry Andric   // opencl.ocl.version named metadata node.
6480b57cec5SDimitry Andric   // C++ is backwards compatible with OpenCL v2.0.
6490b57cec5SDimitry Andric   // FIXME: We might need to add CXX version at some point too?
6500b57cec5SDimitry Andric   auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
6510b57cec5SDimitry Andric   llvm::Metadata *OCLVerElts[] = {
6520b57cec5SDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
6530b57cec5SDimitry Andric           Int32Ty, Version / 100)),
6540b57cec5SDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
6550b57cec5SDimitry Andric           Int32Ty, (Version % 100) / 10))};
6560b57cec5SDimitry Andric   llvm::NamedMDNode *OCLVerMD =
6570b57cec5SDimitry Andric       TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
6580b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
6590b57cec5SDimitry Andric   OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
6600b57cec5SDimitry Andric }
6610b57cec5SDimitry Andric 
6620b57cec5SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
6630b57cec5SDimitry Andric   // Make sure that this type is translated.
6640b57cec5SDimitry Andric   Types.UpdateCompletedType(TD);
6650b57cec5SDimitry Andric }
6660b57cec5SDimitry Andric 
6670b57cec5SDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
6680b57cec5SDimitry Andric   // Make sure that this type is translated.
6690b57cec5SDimitry Andric   Types.RefreshTypeCacheForClass(RD);
6700b57cec5SDimitry Andric }
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
6730b57cec5SDimitry Andric   if (!TBAA)
6740b57cec5SDimitry Andric     return nullptr;
6750b57cec5SDimitry Andric   return TBAA->getTypeInfo(QTy);
6760b57cec5SDimitry Andric }
6770b57cec5SDimitry Andric 
6780b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
6790b57cec5SDimitry Andric   if (!TBAA)
6800b57cec5SDimitry Andric     return TBAAAccessInfo();
6810b57cec5SDimitry Andric   return TBAA->getAccessInfo(AccessType);
6820b57cec5SDimitry Andric }
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric TBAAAccessInfo
6850b57cec5SDimitry Andric CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
6860b57cec5SDimitry Andric   if (!TBAA)
6870b57cec5SDimitry Andric     return TBAAAccessInfo();
6880b57cec5SDimitry Andric   return TBAA->getVTablePtrAccessInfo(VTablePtrType);
6890b57cec5SDimitry Andric }
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
6920b57cec5SDimitry Andric   if (!TBAA)
6930b57cec5SDimitry Andric     return nullptr;
6940b57cec5SDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
6950b57cec5SDimitry Andric }
6960b57cec5SDimitry Andric 
6970b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
6980b57cec5SDimitry Andric   if (!TBAA)
6990b57cec5SDimitry Andric     return nullptr;
7000b57cec5SDimitry Andric   return TBAA->getBaseTypeInfo(QTy);
7010b57cec5SDimitry Andric }
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
7040b57cec5SDimitry Andric   if (!TBAA)
7050b57cec5SDimitry Andric     return nullptr;
7060b57cec5SDimitry Andric   return TBAA->getAccessTagInfo(Info);
7070b57cec5SDimitry Andric }
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
7100b57cec5SDimitry Andric                                                    TBAAAccessInfo TargetInfo) {
7110b57cec5SDimitry Andric   if (!TBAA)
7120b57cec5SDimitry Andric     return TBAAAccessInfo();
7130b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
7140b57cec5SDimitry Andric }
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric TBAAAccessInfo
7170b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
7180b57cec5SDimitry Andric                                                    TBAAAccessInfo InfoB) {
7190b57cec5SDimitry Andric   if (!TBAA)
7200b57cec5SDimitry Andric     return TBAAAccessInfo();
7210b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
7220b57cec5SDimitry Andric }
7230b57cec5SDimitry Andric 
7240b57cec5SDimitry Andric TBAAAccessInfo
7250b57cec5SDimitry Andric CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
7260b57cec5SDimitry Andric                                               TBAAAccessInfo SrcInfo) {
7270b57cec5SDimitry Andric   if (!TBAA)
7280b57cec5SDimitry Andric     return TBAAAccessInfo();
7290b57cec5SDimitry Andric   return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
7300b57cec5SDimitry Andric }
7310b57cec5SDimitry Andric 
7320b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
7330b57cec5SDimitry Andric                                                 TBAAAccessInfo TBAAInfo) {
7340b57cec5SDimitry Andric   if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
7350b57cec5SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
7360b57cec5SDimitry Andric }
7370b57cec5SDimitry Andric 
7380b57cec5SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
7390b57cec5SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
7400b57cec5SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
7410b57cec5SDimitry Andric                  llvm::MDNode::get(getLLVMContext(), {}));
7420b57cec5SDimitry Andric }
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
7450b57cec5SDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
7460b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
7470b57cec5SDimitry Andric }
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
7500b57cec5SDimitry Andric /// specified stmt yet.
7510b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
7520b57cec5SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
7530b57cec5SDimitry Andric                                                "cannot compile this %0 yet");
7540b57cec5SDimitry Andric   std::string Msg = Type;
7550b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
7560b57cec5SDimitry Andric       << Msg << S->getSourceRange();
7570b57cec5SDimitry Andric }
7580b57cec5SDimitry Andric 
7590b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the
7600b57cec5SDimitry Andric /// specified decl yet.
7610b57cec5SDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
7620b57cec5SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
7630b57cec5SDimitry Andric                                                "cannot compile this %0 yet");
7640b57cec5SDimitry Andric   std::string Msg = Type;
7650b57cec5SDimitry Andric   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
7660b57cec5SDimitry Andric }
7670b57cec5SDimitry Andric 
7680b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
7690b57cec5SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
7700b57cec5SDimitry Andric }
7710b57cec5SDimitry Andric 
7720b57cec5SDimitry Andric void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
7730b57cec5SDimitry Andric                                         const NamedDecl *D) const {
7740b57cec5SDimitry Andric   if (GV->hasDLLImportStorageClass())
7750b57cec5SDimitry Andric     return;
7760b57cec5SDimitry Andric   // Internal definitions always have default visibility.
7770b57cec5SDimitry Andric   if (GV->hasLocalLinkage()) {
7780b57cec5SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
7790b57cec5SDimitry Andric     return;
7800b57cec5SDimitry Andric   }
7810b57cec5SDimitry Andric   if (!D)
7820b57cec5SDimitry Andric     return;
7830b57cec5SDimitry Andric   // Set visibility for definitions, and for declarations if requested globally
7840b57cec5SDimitry Andric   // or set explicitly.
7850b57cec5SDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
7860b57cec5SDimitry Andric   if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
7870b57cec5SDimitry Andric       !GV->isDeclarationForLinker())
7880b57cec5SDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
7890b57cec5SDimitry Andric }
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
7920b57cec5SDimitry Andric                                  llvm::GlobalValue *GV) {
7930b57cec5SDimitry Andric   if (GV->hasLocalLinkage())
7940b57cec5SDimitry Andric     return true;
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric   if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
7970b57cec5SDimitry Andric     return true;
7980b57cec5SDimitry Andric 
7990b57cec5SDimitry Andric   // DLLImport explicitly marks the GV as external.
8000b57cec5SDimitry Andric   if (GV->hasDLLImportStorageClass())
8010b57cec5SDimitry Andric     return false;
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric   const llvm::Triple &TT = CGM.getTriple();
8040b57cec5SDimitry Andric   if (TT.isWindowsGNUEnvironment()) {
8050b57cec5SDimitry Andric     // In MinGW, variables without DLLImport can still be automatically
8060b57cec5SDimitry Andric     // imported from a DLL by the linker; don't mark variables that
8070b57cec5SDimitry Andric     // potentially could come from another DLL as DSO local.
8080b57cec5SDimitry Andric     if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
8090b57cec5SDimitry Andric         !GV->isThreadLocal())
8100b57cec5SDimitry Andric       return false;
8110b57cec5SDimitry Andric   }
8120b57cec5SDimitry Andric 
8130b57cec5SDimitry Andric   // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
8140b57cec5SDimitry Andric   // remain unresolved in the link, they can be resolved to zero, which is
8150b57cec5SDimitry Andric   // outside the current DSO.
8160b57cec5SDimitry Andric   if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
8170b57cec5SDimitry Andric     return false;
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric   // Every other GV is local on COFF.
8200b57cec5SDimitry Andric   // Make an exception for windows OS in the triple: Some firmware builds use
8210b57cec5SDimitry Andric   // *-win32-macho triples. This (accidentally?) produced windows relocations
8220b57cec5SDimitry Andric   // without GOT tables in older clang versions; Keep this behaviour.
8230b57cec5SDimitry Andric   // FIXME: even thread local variables?
8240b57cec5SDimitry Andric   if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
8250b57cec5SDimitry Andric     return true;
8260b57cec5SDimitry Andric 
8270b57cec5SDimitry Andric   // Only handle COFF and ELF for now.
8280b57cec5SDimitry Andric   if (!TT.isOSBinFormatELF())
8290b57cec5SDimitry Andric     return false;
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric   // If this is not an executable, don't assume anything is local.
8320b57cec5SDimitry Andric   const auto &CGOpts = CGM.getCodeGenOpts();
8330b57cec5SDimitry Andric   llvm::Reloc::Model RM = CGOpts.RelocationModel;
8340b57cec5SDimitry Andric   const auto &LOpts = CGM.getLangOpts();
835480093f4SDimitry Andric   if (RM != llvm::Reloc::Static && !LOpts.PIE)
8360b57cec5SDimitry Andric     return false;
8370b57cec5SDimitry Andric 
8380b57cec5SDimitry Andric   // A definition cannot be preempted from an executable.
8390b57cec5SDimitry Andric   if (!GV->isDeclarationForLinker())
8400b57cec5SDimitry Andric     return true;
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric   // Most PIC code sequences that assume that a symbol is local cannot produce a
8430b57cec5SDimitry Andric   // 0 if it turns out the symbol is undefined. While this is ABI and relocation
8440b57cec5SDimitry Andric   // depended, it seems worth it to handle it here.
8450b57cec5SDimitry Andric   if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
8460b57cec5SDimitry Andric     return false;
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric   // PPC has no copy relocations and cannot use a plt entry as a symbol address.
8490b57cec5SDimitry Andric   llvm::Triple::ArchType Arch = TT.getArch();
8500b57cec5SDimitry Andric   if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
8510b57cec5SDimitry Andric       Arch == llvm::Triple::ppc64le)
8520b57cec5SDimitry Andric     return false;
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric   // If we can use copy relocations we can assume it is local.
8550b57cec5SDimitry Andric   if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
8560b57cec5SDimitry Andric     if (!Var->isThreadLocal() &&
8570b57cec5SDimitry Andric         (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
8580b57cec5SDimitry Andric       return true;
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric   // If we can use a plt entry as the symbol address we can assume it
8610b57cec5SDimitry Andric   // is local.
8620b57cec5SDimitry Andric   // FIXME: This should work for PIE, but the gold linker doesn't support it.
8630b57cec5SDimitry Andric   if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
8640b57cec5SDimitry Andric     return true;
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric   // Otherwise don't assue it is local.
8670b57cec5SDimitry Andric   return false;
8680b57cec5SDimitry Andric }
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
8710b57cec5SDimitry Andric   GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
8720b57cec5SDimitry Andric }
8730b57cec5SDimitry Andric 
8740b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
8750b57cec5SDimitry Andric                                           GlobalDecl GD) const {
8760b57cec5SDimitry Andric   const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
8770b57cec5SDimitry Andric   // C++ destructors have a few C++ ABI specific special cases.
8780b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
8790b57cec5SDimitry Andric     getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
8800b57cec5SDimitry Andric     return;
8810b57cec5SDimitry Andric   }
8820b57cec5SDimitry Andric   setDLLImportDLLExport(GV, D);
8830b57cec5SDimitry Andric }
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
8860b57cec5SDimitry Andric                                           const NamedDecl *D) const {
8870b57cec5SDimitry Andric   if (D && D->isExternallyVisible()) {
8880b57cec5SDimitry Andric     if (D->hasAttr<DLLImportAttr>())
8890b57cec5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
8900b57cec5SDimitry Andric     else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
8910b57cec5SDimitry Andric       GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
8920b57cec5SDimitry Andric   }
8930b57cec5SDimitry Andric }
8940b57cec5SDimitry Andric 
8950b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
8960b57cec5SDimitry Andric                                     GlobalDecl GD) const {
8970b57cec5SDimitry Andric   setDLLImportDLLExport(GV, GD);
8980b57cec5SDimitry Andric   setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
8990b57cec5SDimitry Andric }
9000b57cec5SDimitry Andric 
9010b57cec5SDimitry Andric void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
9020b57cec5SDimitry Andric                                     const NamedDecl *D) const {
9030b57cec5SDimitry Andric   setDLLImportDLLExport(GV, D);
9040b57cec5SDimitry Andric   setGVPropertiesAux(GV, D);
9050b57cec5SDimitry Andric }
9060b57cec5SDimitry Andric 
9070b57cec5SDimitry Andric void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
9080b57cec5SDimitry Andric                                        const NamedDecl *D) const {
9090b57cec5SDimitry Andric   setGlobalVisibility(GV, D);
9100b57cec5SDimitry Andric   setDSOLocal(GV);
9110b57cec5SDimitry Andric   GV->setPartition(CodeGenOpts.SymbolPartition);
9120b57cec5SDimitry Andric }
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
9150b57cec5SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
9160b57cec5SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
9170b57cec5SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
9180b57cec5SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
9190b57cec5SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
9200b57cec5SDimitry Andric }
9210b57cec5SDimitry Andric 
9220b57cec5SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
9230b57cec5SDimitry Andric     CodeGenOptions::TLSModel M) {
9240b57cec5SDimitry Andric   switch (M) {
9250b57cec5SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
9260b57cec5SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
9270b57cec5SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
9280b57cec5SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
9290b57cec5SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
9300b57cec5SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
9310b57cec5SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
9320b57cec5SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
9330b57cec5SDimitry Andric   }
9340b57cec5SDimitry Andric   llvm_unreachable("Invalid TLS model!");
9350b57cec5SDimitry Andric }
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
9380b57cec5SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
9410b57cec5SDimitry Andric   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
9420b57cec5SDimitry Andric 
9430b57cec5SDimitry Andric   // Override the TLS model if it is explicitly specified.
9440b57cec5SDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
9450b57cec5SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
9460b57cec5SDimitry Andric   }
9470b57cec5SDimitry Andric 
9480b57cec5SDimitry Andric   GV->setThreadLocalMode(TLM);
9490b57cec5SDimitry Andric }
9500b57cec5SDimitry Andric 
9510b57cec5SDimitry Andric static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
9520b57cec5SDimitry Andric                                           StringRef Name) {
9530b57cec5SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
9540b57cec5SDimitry Andric   return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
9550b57cec5SDimitry Andric }
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
9580b57cec5SDimitry Andric                                                  const CPUSpecificAttr *Attr,
9590b57cec5SDimitry Andric                                                  unsigned CPUIndex,
9600b57cec5SDimitry Andric                                                  raw_ostream &Out) {
9610b57cec5SDimitry Andric   // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
9620b57cec5SDimitry Andric   // supported.
9630b57cec5SDimitry Andric   if (Attr)
9640b57cec5SDimitry Andric     Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
9650b57cec5SDimitry Andric   else if (CGM.getTarget().supportsIFunc())
9660b57cec5SDimitry Andric     Out << ".resolver";
9670b57cec5SDimitry Andric }
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric static void AppendTargetMangling(const CodeGenModule &CGM,
9700b57cec5SDimitry Andric                                  const TargetAttr *Attr, raw_ostream &Out) {
9710b57cec5SDimitry Andric   if (Attr->isDefaultVersion())
9720b57cec5SDimitry Andric     return;
9730b57cec5SDimitry Andric 
9740b57cec5SDimitry Andric   Out << '.';
9750b57cec5SDimitry Andric   const TargetInfo &Target = CGM.getTarget();
976480093f4SDimitry Andric   ParsedTargetAttr Info =
9770b57cec5SDimitry Andric       Attr->parse([&Target](StringRef LHS, StringRef RHS) {
9780b57cec5SDimitry Andric         // Multiversioning doesn't allow "no-${feature}", so we can
9790b57cec5SDimitry Andric         // only have "+" prefixes here.
9800b57cec5SDimitry Andric         assert(LHS.startswith("+") && RHS.startswith("+") &&
9810b57cec5SDimitry Andric                "Features should always have a prefix.");
9820b57cec5SDimitry Andric         return Target.multiVersionSortPriority(LHS.substr(1)) >
9830b57cec5SDimitry Andric                Target.multiVersionSortPriority(RHS.substr(1));
9840b57cec5SDimitry Andric       });
9850b57cec5SDimitry Andric 
9860b57cec5SDimitry Andric   bool IsFirst = true;
9870b57cec5SDimitry Andric 
9880b57cec5SDimitry Andric   if (!Info.Architecture.empty()) {
9890b57cec5SDimitry Andric     IsFirst = false;
9900b57cec5SDimitry Andric     Out << "arch_" << Info.Architecture;
9910b57cec5SDimitry Andric   }
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric   for (StringRef Feat : Info.Features) {
9940b57cec5SDimitry Andric     if (!IsFirst)
9950b57cec5SDimitry Andric       Out << '_';
9960b57cec5SDimitry Andric     IsFirst = false;
9970b57cec5SDimitry Andric     Out << Feat.substr(1);
9980b57cec5SDimitry Andric   }
9990b57cec5SDimitry Andric }
10000b57cec5SDimitry Andric 
10010b57cec5SDimitry Andric static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
10020b57cec5SDimitry Andric                                       const NamedDecl *ND,
10030b57cec5SDimitry Andric                                       bool OmitMultiVersionMangling = false) {
10040b57cec5SDimitry Andric   SmallString<256> Buffer;
10050b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
10060b57cec5SDimitry Andric   MangleContext &MC = CGM.getCXXABI().getMangleContext();
10070b57cec5SDimitry Andric   if (MC.shouldMangleDeclName(ND)) {
10080b57cec5SDimitry Andric     llvm::raw_svector_ostream Out(Buffer);
10090b57cec5SDimitry Andric     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
10100b57cec5SDimitry Andric       MC.mangleCXXCtor(D, GD.getCtorType(), Out);
10110b57cec5SDimitry Andric     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
10120b57cec5SDimitry Andric       MC.mangleCXXDtor(D, GD.getDtorType(), Out);
10130b57cec5SDimitry Andric     else
10140b57cec5SDimitry Andric       MC.mangleName(ND, Out);
10150b57cec5SDimitry Andric   } else {
10160b57cec5SDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
10170b57cec5SDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
10180b57cec5SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
10190b57cec5SDimitry Andric 
10200b57cec5SDimitry Andric     if (FD &&
10210b57cec5SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
10220b57cec5SDimitry Andric       llvm::raw_svector_ostream Out(Buffer);
10230b57cec5SDimitry Andric       Out << "__regcall3__" << II->getName();
10240b57cec5SDimitry Andric     } else {
10250b57cec5SDimitry Andric       Out << II->getName();
10260b57cec5SDimitry Andric     }
10270b57cec5SDimitry Andric   }
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
10300b57cec5SDimitry Andric     if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
10310b57cec5SDimitry Andric       switch (FD->getMultiVersionKind()) {
10320b57cec5SDimitry Andric       case MultiVersionKind::CPUDispatch:
10330b57cec5SDimitry Andric       case MultiVersionKind::CPUSpecific:
10340b57cec5SDimitry Andric         AppendCPUSpecificCPUDispatchMangling(CGM,
10350b57cec5SDimitry Andric                                              FD->getAttr<CPUSpecificAttr>(),
10360b57cec5SDimitry Andric                                              GD.getMultiVersionIndex(), Out);
10370b57cec5SDimitry Andric         break;
10380b57cec5SDimitry Andric       case MultiVersionKind::Target:
10390b57cec5SDimitry Andric         AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
10400b57cec5SDimitry Andric         break;
10410b57cec5SDimitry Andric       case MultiVersionKind::None:
10420b57cec5SDimitry Andric         llvm_unreachable("None multiversion type isn't valid here");
10430b57cec5SDimitry Andric       }
10440b57cec5SDimitry Andric     }
10450b57cec5SDimitry Andric 
10460b57cec5SDimitry Andric   return Out.str();
10470b57cec5SDimitry Andric }
10480b57cec5SDimitry Andric 
10490b57cec5SDimitry Andric void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
10500b57cec5SDimitry Andric                                             const FunctionDecl *FD) {
10510b57cec5SDimitry Andric   if (!FD->isMultiVersion())
10520b57cec5SDimitry Andric     return;
10530b57cec5SDimitry Andric 
10540b57cec5SDimitry Andric   // Get the name of what this would be without the 'target' attribute.  This
10550b57cec5SDimitry Andric   // allows us to lookup the version that was emitted when this wasn't a
10560b57cec5SDimitry Andric   // multiversion function.
10570b57cec5SDimitry Andric   std::string NonTargetName =
10580b57cec5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
10590b57cec5SDimitry Andric   GlobalDecl OtherGD;
10600b57cec5SDimitry Andric   if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
10610b57cec5SDimitry Andric     assert(OtherGD.getCanonicalDecl()
10620b57cec5SDimitry Andric                .getDecl()
10630b57cec5SDimitry Andric                ->getAsFunction()
10640b57cec5SDimitry Andric                ->isMultiVersion() &&
10650b57cec5SDimitry Andric            "Other GD should now be a multiversioned function");
10660b57cec5SDimitry Andric     // OtherFD is the version of this function that was mangled BEFORE
10670b57cec5SDimitry Andric     // becoming a MultiVersion function.  It potentially needs to be updated.
10680b57cec5SDimitry Andric     const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
10690b57cec5SDimitry Andric                                       .getDecl()
10700b57cec5SDimitry Andric                                       ->getAsFunction()
10710b57cec5SDimitry Andric                                       ->getMostRecentDecl();
10720b57cec5SDimitry Andric     std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
10730b57cec5SDimitry Andric     // This is so that if the initial version was already the 'default'
10740b57cec5SDimitry Andric     // version, we don't try to update it.
10750b57cec5SDimitry Andric     if (OtherName != NonTargetName) {
10760b57cec5SDimitry Andric       // Remove instead of erase, since others may have stored the StringRef
10770b57cec5SDimitry Andric       // to this.
10780b57cec5SDimitry Andric       const auto ExistingRecord = Manglings.find(NonTargetName);
10790b57cec5SDimitry Andric       if (ExistingRecord != std::end(Manglings))
10800b57cec5SDimitry Andric         Manglings.remove(&(*ExistingRecord));
10810b57cec5SDimitry Andric       auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
10820b57cec5SDimitry Andric       MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
10830b57cec5SDimitry Andric       if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
10840b57cec5SDimitry Andric         Entry->setName(OtherName);
10850b57cec5SDimitry Andric     }
10860b57cec5SDimitry Andric   }
10870b57cec5SDimitry Andric }
10880b57cec5SDimitry Andric 
10890b57cec5SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
10900b57cec5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
10910b57cec5SDimitry Andric 
10920b57cec5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
10930b57cec5SDimitry Andric   // complete constructors get mangled the same.
10940b57cec5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
10950b57cec5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
10960b57cec5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
10970b57cec5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
10980b57cec5SDimitry Andric       if (OrigCtorType == Ctor_Base)
10990b57cec5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
11000b57cec5SDimitry Andric     }
11010b57cec5SDimitry Andric   }
11020b57cec5SDimitry Andric 
11030b57cec5SDimitry Andric   auto FoundName = MangledDeclNames.find(CanonicalGD);
11040b57cec5SDimitry Andric   if (FoundName != MangledDeclNames.end())
11050b57cec5SDimitry Andric     return FoundName->second;
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric   // Keep the first result in the case of a mangling collision.
11080b57cec5SDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
11090b57cec5SDimitry Andric   std::string MangledName = getMangledNameImpl(*this, GD, ND);
11100b57cec5SDimitry Andric 
11110b57cec5SDimitry Andric   // Adjust kernel stub mangling as we may need to be able to differentiate
11120b57cec5SDimitry Andric   // them from the kernel itself (e.g., for HIP).
11130b57cec5SDimitry Andric   if (auto *FD = dyn_cast<FunctionDecl>(GD.getDecl()))
11140b57cec5SDimitry Andric     if (!getLangOpts().CUDAIsDevice && FD->hasAttr<CUDAGlobalAttr>())
11150b57cec5SDimitry Andric       MangledName = getCUDARuntime().getDeviceStubName(MangledName);
11160b57cec5SDimitry Andric 
11170b57cec5SDimitry Andric   auto Result = Manglings.insert(std::make_pair(MangledName, GD));
11180b57cec5SDimitry Andric   return MangledDeclNames[CanonicalGD] = Result.first->first();
11190b57cec5SDimitry Andric }
11200b57cec5SDimitry Andric 
11210b57cec5SDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
11220b57cec5SDimitry Andric                                              const BlockDecl *BD) {
11230b57cec5SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
11240b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
11250b57cec5SDimitry Andric 
11260b57cec5SDimitry Andric   SmallString<256> Buffer;
11270b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
11280b57cec5SDimitry Andric   if (!D)
11290b57cec5SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
11300b57cec5SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
11310b57cec5SDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
11320b57cec5SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
11330b57cec5SDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
11340b57cec5SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
11350b57cec5SDimitry Andric   else
11360b57cec5SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
11370b57cec5SDimitry Andric 
11380b57cec5SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
11390b57cec5SDimitry Andric   return Result.first->first();
11400b57cec5SDimitry Andric }
11410b57cec5SDimitry Andric 
11420b57cec5SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
11430b57cec5SDimitry Andric   return getModule().getNamedValue(Name);
11440b57cec5SDimitry Andric }
11450b57cec5SDimitry Andric 
11460b57cec5SDimitry Andric /// AddGlobalCtor - Add a function to the list that will be called before
11470b57cec5SDimitry Andric /// main() runs.
11480b57cec5SDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
11490b57cec5SDimitry Andric                                   llvm::Constant *AssociatedData) {
11500b57cec5SDimitry Andric   // FIXME: Type coercion of void()* types.
11510b57cec5SDimitry Andric   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
11520b57cec5SDimitry Andric }
11530b57cec5SDimitry Andric 
11540b57cec5SDimitry Andric /// AddGlobalDtor - Add a function to the list that will be called
11550b57cec5SDimitry Andric /// when the module is unloaded.
11560b57cec5SDimitry Andric void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
11570b57cec5SDimitry Andric   if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
11580b57cec5SDimitry Andric     DtorsUsingAtExit[Priority].push_back(Dtor);
11590b57cec5SDimitry Andric     return;
11600b57cec5SDimitry Andric   }
11610b57cec5SDimitry Andric 
11620b57cec5SDimitry Andric   // FIXME: Type coercion of void()* types.
11630b57cec5SDimitry Andric   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
11640b57cec5SDimitry Andric }
11650b57cec5SDimitry Andric 
11660b57cec5SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
11670b57cec5SDimitry Andric   if (Fns.empty()) return;
11680b57cec5SDimitry Andric 
11690b57cec5SDimitry Andric   // Ctor function type is void()*.
11700b57cec5SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
11710b57cec5SDimitry Andric   llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
11720b57cec5SDimitry Andric       TheModule.getDataLayout().getProgramAddressSpace());
11730b57cec5SDimitry Andric 
11740b57cec5SDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
11750b57cec5SDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
11760b57cec5SDimitry Andric       Int32Ty, CtorPFTy, VoidPtrTy);
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric   // Construct the constructor and destructor arrays.
11790b57cec5SDimitry Andric   ConstantInitBuilder builder(*this);
11800b57cec5SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
11810b57cec5SDimitry Andric   for (const auto &I : Fns) {
11820b57cec5SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
11830b57cec5SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
11840b57cec5SDimitry Andric     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
11850b57cec5SDimitry Andric     if (I.AssociatedData)
11860b57cec5SDimitry Andric       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
11870b57cec5SDimitry Andric     else
11880b57cec5SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
11890b57cec5SDimitry Andric     ctor.finishAndAddTo(ctors);
11900b57cec5SDimitry Andric   }
11910b57cec5SDimitry Andric 
11920b57cec5SDimitry Andric   auto list =
11930b57cec5SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
11940b57cec5SDimitry Andric                                 /*constant*/ false,
11950b57cec5SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
11980b57cec5SDimitry Andric   // on appending variables.  Take it off as a workaround.
1199a7dea167SDimitry Andric   list->setAlignment(llvm::None);
12000b57cec5SDimitry Andric 
12010b57cec5SDimitry Andric   Fns.clear();
12020b57cec5SDimitry Andric }
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes
12050b57cec5SDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
12060b57cec5SDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
12090b57cec5SDimitry Andric 
12100b57cec5SDimitry Andric   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
12110b57cec5SDimitry Andric     return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
12120b57cec5SDimitry Andric 
12130b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(D) &&
12140b57cec5SDimitry Andric       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
12150b57cec5SDimitry Andric       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12160b57cec5SDimitry Andric     // Our approach to inheriting constructors is fundamentally different from
12170b57cec5SDimitry Andric     // that used by the MS ABI, so keep our inheriting constructor thunks
12180b57cec5SDimitry Andric     // internal rather than trying to pick an unambiguous mangling for them.
12190b57cec5SDimitry Andric     return llvm::GlobalValue::InternalLinkage;
12200b57cec5SDimitry Andric   }
12210b57cec5SDimitry Andric 
12220b57cec5SDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
12230b57cec5SDimitry Andric }
12240b57cec5SDimitry Andric 
12250b57cec5SDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
12260b57cec5SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
12270b57cec5SDimitry Andric   if (!MDS) return nullptr;
12280b57cec5SDimitry Andric 
12290b57cec5SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
12300b57cec5SDimitry Andric }
12310b57cec5SDimitry Andric 
12320b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
12330b57cec5SDimitry Andric                                               const CGFunctionInfo &Info,
12340b57cec5SDimitry Andric                                               llvm::Function *F) {
12350b57cec5SDimitry Andric   unsigned CallingConv;
12360b57cec5SDimitry Andric   llvm::AttributeList PAL;
12370b57cec5SDimitry Andric   ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, false);
12380b57cec5SDimitry Andric   F->setAttributes(PAL);
12390b57cec5SDimitry Andric   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
12400b57cec5SDimitry Andric }
12410b57cec5SDimitry Andric 
12420b57cec5SDimitry Andric static void removeImageAccessQualifier(std::string& TyName) {
12430b57cec5SDimitry Andric   std::string ReadOnlyQual("__read_only");
12440b57cec5SDimitry Andric   std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
12450b57cec5SDimitry Andric   if (ReadOnlyPos != std::string::npos)
12460b57cec5SDimitry Andric     // "+ 1" for the space after access qualifier.
12470b57cec5SDimitry Andric     TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
12480b57cec5SDimitry Andric   else {
12490b57cec5SDimitry Andric     std::string WriteOnlyQual("__write_only");
12500b57cec5SDimitry Andric     std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
12510b57cec5SDimitry Andric     if (WriteOnlyPos != std::string::npos)
12520b57cec5SDimitry Andric       TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
12530b57cec5SDimitry Andric     else {
12540b57cec5SDimitry Andric       std::string ReadWriteQual("__read_write");
12550b57cec5SDimitry Andric       std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
12560b57cec5SDimitry Andric       if (ReadWritePos != std::string::npos)
12570b57cec5SDimitry Andric         TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
12580b57cec5SDimitry Andric     }
12590b57cec5SDimitry Andric   }
12600b57cec5SDimitry Andric }
12610b57cec5SDimitry Andric 
12620b57cec5SDimitry Andric // Returns the address space id that should be produced to the
12630b57cec5SDimitry Andric // kernel_arg_addr_space metadata. This is always fixed to the ids
12640b57cec5SDimitry Andric // as specified in the SPIR 2.0 specification in order to differentiate
12650b57cec5SDimitry Andric // for example in clGetKernelArgInfo() implementation between the address
12660b57cec5SDimitry Andric // spaces with targets without unique mapping to the OpenCL address spaces
12670b57cec5SDimitry Andric // (basically all single AS CPUs).
12680b57cec5SDimitry Andric static unsigned ArgInfoAddressSpace(LangAS AS) {
12690b57cec5SDimitry Andric   switch (AS) {
12700b57cec5SDimitry Andric   case LangAS::opencl_global:   return 1;
12710b57cec5SDimitry Andric   case LangAS::opencl_constant: return 2;
12720b57cec5SDimitry Andric   case LangAS::opencl_local:    return 3;
12730b57cec5SDimitry Andric   case LangAS::opencl_generic:  return 4; // Not in SPIR 2.0 specs.
12740b57cec5SDimitry Andric   default:
12750b57cec5SDimitry Andric     return 0; // Assume private.
12760b57cec5SDimitry Andric   }
12770b57cec5SDimitry Andric }
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn,
12800b57cec5SDimitry Andric                                          const FunctionDecl *FD,
12810b57cec5SDimitry Andric                                          CodeGenFunction *CGF) {
12820b57cec5SDimitry Andric   assert(((FD && CGF) || (!FD && !CGF)) &&
12830b57cec5SDimitry Andric          "Incorrect use - FD and CGF should either be both null or not!");
12840b57cec5SDimitry Andric   // Create MDNodes that represent the kernel arg metadata.
12850b57cec5SDimitry Andric   // Each MDNode is a list in the form of "key", N number of values which is
12860b57cec5SDimitry Andric   // the same number of values as their are kernel arguments.
12870b57cec5SDimitry Andric 
12880b57cec5SDimitry Andric   const PrintingPolicy &Policy = Context.getPrintingPolicy();
12890b57cec5SDimitry Andric 
12900b57cec5SDimitry Andric   // MDNode for the kernel argument address space qualifiers.
12910b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> addressQuals;
12920b57cec5SDimitry Andric 
12930b57cec5SDimitry Andric   // MDNode for the kernel argument access qualifiers (images only).
12940b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> accessQuals;
12950b57cec5SDimitry Andric 
12960b57cec5SDimitry Andric   // MDNode for the kernel argument type names.
12970b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeNames;
12980b57cec5SDimitry Andric 
12990b57cec5SDimitry Andric   // MDNode for the kernel argument base type names.
13000b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
13010b57cec5SDimitry Andric 
13020b57cec5SDimitry Andric   // MDNode for the kernel argument type qualifiers.
13030b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argTypeQuals;
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric   // MDNode for the kernel argument names.
13060b57cec5SDimitry Andric   SmallVector<llvm::Metadata *, 8> argNames;
13070b57cec5SDimitry Andric 
13080b57cec5SDimitry Andric   if (FD && CGF)
13090b57cec5SDimitry Andric     for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
13100b57cec5SDimitry Andric       const ParmVarDecl *parm = FD->getParamDecl(i);
13110b57cec5SDimitry Andric       QualType ty = parm->getType();
13120b57cec5SDimitry Andric       std::string typeQuals;
13130b57cec5SDimitry Andric 
13140b57cec5SDimitry Andric       if (ty->isPointerType()) {
13150b57cec5SDimitry Andric         QualType pointeeTy = ty->getPointeeType();
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric         // Get address qualifier.
13180b57cec5SDimitry Andric         addressQuals.push_back(
13190b57cec5SDimitry Andric             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
13200b57cec5SDimitry Andric                 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
13210b57cec5SDimitry Andric 
13220b57cec5SDimitry Andric         // Get argument type name.
13230b57cec5SDimitry Andric         std::string typeName =
13240b57cec5SDimitry Andric             pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
13250b57cec5SDimitry Andric 
13260b57cec5SDimitry Andric         // Turn "unsigned type" to "utype"
13270b57cec5SDimitry Andric         std::string::size_type pos = typeName.find("unsigned");
13280b57cec5SDimitry Andric         if (pointeeTy.isCanonical() && pos != std::string::npos)
13290b57cec5SDimitry Andric           typeName.erase(pos + 1, 8);
13300b57cec5SDimitry Andric 
13310b57cec5SDimitry Andric         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
13320b57cec5SDimitry Andric 
13330b57cec5SDimitry Andric         std::string baseTypeName =
13340b57cec5SDimitry Andric             pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
13350b57cec5SDimitry Andric                 Policy) +
13360b57cec5SDimitry Andric             "*";
13370b57cec5SDimitry Andric 
13380b57cec5SDimitry Andric         // Turn "unsigned type" to "utype"
13390b57cec5SDimitry Andric         pos = baseTypeName.find("unsigned");
13400b57cec5SDimitry Andric         if (pos != std::string::npos)
13410b57cec5SDimitry Andric           baseTypeName.erase(pos + 1, 8);
13420b57cec5SDimitry Andric 
13430b57cec5SDimitry Andric         argBaseTypeNames.push_back(
13440b57cec5SDimitry Andric             llvm::MDString::get(VMContext, baseTypeName));
13450b57cec5SDimitry Andric 
13460b57cec5SDimitry Andric         // Get argument type qualifiers:
13470b57cec5SDimitry Andric         if (ty.isRestrictQualified())
13480b57cec5SDimitry Andric           typeQuals = "restrict";
13490b57cec5SDimitry Andric         if (pointeeTy.isConstQualified() ||
13500b57cec5SDimitry Andric             (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
13510b57cec5SDimitry Andric           typeQuals += typeQuals.empty() ? "const" : " const";
13520b57cec5SDimitry Andric         if (pointeeTy.isVolatileQualified())
13530b57cec5SDimitry Andric           typeQuals += typeQuals.empty() ? "volatile" : " volatile";
13540b57cec5SDimitry Andric       } else {
13550b57cec5SDimitry Andric         uint32_t AddrSpc = 0;
13560b57cec5SDimitry Andric         bool isPipe = ty->isPipeType();
13570b57cec5SDimitry Andric         if (ty->isImageType() || isPipe)
13580b57cec5SDimitry Andric           AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
13590b57cec5SDimitry Andric 
13600b57cec5SDimitry Andric         addressQuals.push_back(
13610b57cec5SDimitry Andric             llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric         // Get argument type name.
13640b57cec5SDimitry Andric         std::string typeName;
13650b57cec5SDimitry Andric         if (isPipe)
13660b57cec5SDimitry Andric           typeName = ty.getCanonicalType()
13670b57cec5SDimitry Andric                          ->getAs<PipeType>()
13680b57cec5SDimitry Andric                          ->getElementType()
13690b57cec5SDimitry Andric                          .getAsString(Policy);
13700b57cec5SDimitry Andric         else
13710b57cec5SDimitry Andric           typeName = ty.getUnqualifiedType().getAsString(Policy);
13720b57cec5SDimitry Andric 
13730b57cec5SDimitry Andric         // Turn "unsigned type" to "utype"
13740b57cec5SDimitry Andric         std::string::size_type pos = typeName.find("unsigned");
13750b57cec5SDimitry Andric         if (ty.isCanonical() && pos != std::string::npos)
13760b57cec5SDimitry Andric           typeName.erase(pos + 1, 8);
13770b57cec5SDimitry Andric 
13780b57cec5SDimitry Andric         std::string baseTypeName;
13790b57cec5SDimitry Andric         if (isPipe)
13800b57cec5SDimitry Andric           baseTypeName = ty.getCanonicalType()
13810b57cec5SDimitry Andric                              ->getAs<PipeType>()
13820b57cec5SDimitry Andric                              ->getElementType()
13830b57cec5SDimitry Andric                              .getCanonicalType()
13840b57cec5SDimitry Andric                              .getAsString(Policy);
13850b57cec5SDimitry Andric         else
13860b57cec5SDimitry Andric           baseTypeName =
13870b57cec5SDimitry Andric               ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
13880b57cec5SDimitry Andric 
13890b57cec5SDimitry Andric         // Remove access qualifiers on images
13900b57cec5SDimitry Andric         // (as they are inseparable from type in clang implementation,
13910b57cec5SDimitry Andric         // but OpenCL spec provides a special query to get access qualifier
13920b57cec5SDimitry Andric         // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
13930b57cec5SDimitry Andric         if (ty->isImageType()) {
13940b57cec5SDimitry Andric           removeImageAccessQualifier(typeName);
13950b57cec5SDimitry Andric           removeImageAccessQualifier(baseTypeName);
13960b57cec5SDimitry Andric         }
13970b57cec5SDimitry Andric 
13980b57cec5SDimitry Andric         argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
13990b57cec5SDimitry Andric 
14000b57cec5SDimitry Andric         // Turn "unsigned type" to "utype"
14010b57cec5SDimitry Andric         pos = baseTypeName.find("unsigned");
14020b57cec5SDimitry Andric         if (pos != std::string::npos)
14030b57cec5SDimitry Andric           baseTypeName.erase(pos + 1, 8);
14040b57cec5SDimitry Andric 
14050b57cec5SDimitry Andric         argBaseTypeNames.push_back(
14060b57cec5SDimitry Andric             llvm::MDString::get(VMContext, baseTypeName));
14070b57cec5SDimitry Andric 
14080b57cec5SDimitry Andric         if (isPipe)
14090b57cec5SDimitry Andric           typeQuals = "pipe";
14100b57cec5SDimitry Andric       }
14110b57cec5SDimitry Andric 
14120b57cec5SDimitry Andric       argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
14130b57cec5SDimitry Andric 
14140b57cec5SDimitry Andric       // Get image and pipe access qualifier:
14150b57cec5SDimitry Andric       if (ty->isImageType() || ty->isPipeType()) {
14160b57cec5SDimitry Andric         const Decl *PDecl = parm;
14170b57cec5SDimitry Andric         if (auto *TD = dyn_cast<TypedefType>(ty))
14180b57cec5SDimitry Andric           PDecl = TD->getDecl();
14190b57cec5SDimitry Andric         const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
14200b57cec5SDimitry Andric         if (A && A->isWriteOnly())
14210b57cec5SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
14220b57cec5SDimitry Andric         else if (A && A->isReadWrite())
14230b57cec5SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
14240b57cec5SDimitry Andric         else
14250b57cec5SDimitry Andric           accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
14260b57cec5SDimitry Andric       } else
14270b57cec5SDimitry Andric         accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
14280b57cec5SDimitry Andric 
14290b57cec5SDimitry Andric       // Get argument name.
14300b57cec5SDimitry Andric       argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
14310b57cec5SDimitry Andric     }
14320b57cec5SDimitry Andric 
14330b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_addr_space",
14340b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, addressQuals));
14350b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_access_qual",
14360b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, accessQuals));
14370b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_type",
14380b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, argTypeNames));
14390b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_base_type",
14400b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, argBaseTypeNames));
14410b57cec5SDimitry Andric   Fn->setMetadata("kernel_arg_type_qual",
14420b57cec5SDimitry Andric                   llvm::MDNode::get(VMContext, argTypeQuals));
14430b57cec5SDimitry Andric   if (getCodeGenOpts().EmitOpenCLArgMetadata)
14440b57cec5SDimitry Andric     Fn->setMetadata("kernel_arg_name",
14450b57cec5SDimitry Andric                     llvm::MDNode::get(VMContext, argNames));
14460b57cec5SDimitry Andric }
14470b57cec5SDimitry Andric 
14480b57cec5SDimitry Andric /// Determines whether the language options require us to model
14490b57cec5SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
14500b57cec5SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
14510b57cec5SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
14520b57cec5SDimitry Andric /// enables this.
14530b57cec5SDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
14540b57cec5SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
14550b57cec5SDimitry Andric   if (!LangOpts.Exceptions) return false;
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric   // If C++ exceptions are enabled, this is true.
14580b57cec5SDimitry Andric   if (LangOpts.CXXExceptions) return true;
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
14610b57cec5SDimitry Andric   if (LangOpts.ObjCExceptions) {
14620b57cec5SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
14630b57cec5SDimitry Andric   }
14640b57cec5SDimitry Andric 
14650b57cec5SDimitry Andric   return true;
14660b57cec5SDimitry Andric }
14670b57cec5SDimitry Andric 
14680b57cec5SDimitry Andric static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
14690b57cec5SDimitry Andric                                                       const CXXMethodDecl *MD) {
14700b57cec5SDimitry Andric   // Check that the type metadata can ever actually be used by a call.
14710b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().LTOUnit ||
14720b57cec5SDimitry Andric       !CGM.HasHiddenLTOVisibility(MD->getParent()))
14730b57cec5SDimitry Andric     return false;
14740b57cec5SDimitry Andric 
14750b57cec5SDimitry Andric   // Only functions whose address can be taken with a member function pointer
14760b57cec5SDimitry Andric   // need this sort of type metadata.
14770b57cec5SDimitry Andric   return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
14780b57cec5SDimitry Andric          !isa<CXXDestructorDecl>(MD);
14790b57cec5SDimitry Andric }
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric std::vector<const CXXRecordDecl *>
14820b57cec5SDimitry Andric CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
14830b57cec5SDimitry Andric   llvm::SetVector<const CXXRecordDecl *> MostBases;
14840b57cec5SDimitry Andric 
14850b57cec5SDimitry Andric   std::function<void (const CXXRecordDecl *)> CollectMostBases;
14860b57cec5SDimitry Andric   CollectMostBases = [&](const CXXRecordDecl *RD) {
14870b57cec5SDimitry Andric     if (RD->getNumBases() == 0)
14880b57cec5SDimitry Andric       MostBases.insert(RD);
14890b57cec5SDimitry Andric     for (const CXXBaseSpecifier &B : RD->bases())
14900b57cec5SDimitry Andric       CollectMostBases(B.getType()->getAsCXXRecordDecl());
14910b57cec5SDimitry Andric   };
14920b57cec5SDimitry Andric   CollectMostBases(RD);
14930b57cec5SDimitry Andric   return MostBases.takeVector();
14940b57cec5SDimitry Andric }
14950b57cec5SDimitry Andric 
14960b57cec5SDimitry Andric void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
14970b57cec5SDimitry Andric                                                            llvm::Function *F) {
14980b57cec5SDimitry Andric   llvm::AttrBuilder B;
14990b57cec5SDimitry Andric 
15000b57cec5SDimitry Andric   if (CodeGenOpts.UnwindTables)
15010b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::UWTable);
15020b57cec5SDimitry Andric 
15030b57cec5SDimitry Andric   if (!hasUnwindExceptions(LangOpts))
15040b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
15050b57cec5SDimitry Andric 
15060b57cec5SDimitry Andric   if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
15070b57cec5SDimitry Andric     if (LangOpts.getStackProtector() == LangOptions::SSPOn)
15080b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtect);
15090b57cec5SDimitry Andric     else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
15100b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtectStrong);
15110b57cec5SDimitry Andric     else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
15120b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::StackProtectReq);
15130b57cec5SDimitry Andric   }
15140b57cec5SDimitry Andric 
15150b57cec5SDimitry Andric   if (!D) {
15160b57cec5SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
15170b57cec5SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
15180b57cec5SDimitry Andric     // disabled, mark the function as noinline.
15190b57cec5SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
15200b57cec5SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
15210b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
15240b57cec5SDimitry Andric     return;
15250b57cec5SDimitry Andric   }
15260b57cec5SDimitry Andric 
15270b57cec5SDimitry Andric   // Track whether we need to add the optnone LLVM attribute,
15280b57cec5SDimitry Andric   // starting with the default for this optimization level.
15290b57cec5SDimitry Andric   bool ShouldAddOptNone =
15300b57cec5SDimitry Andric       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
15310b57cec5SDimitry Andric   // We can't add optnone in the following cases, it won't pass the verifier.
15320b57cec5SDimitry Andric   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
15330b57cec5SDimitry Andric   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
15340b57cec5SDimitry Andric 
1535480093f4SDimitry Andric   // Add optnone, but do so only if the function isn't always_inline.
1536480093f4SDimitry Andric   if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
1537480093f4SDimitry Andric       !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
15380b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
15390b57cec5SDimitry Andric 
15400b57cec5SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
15410b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
15420b57cec5SDimitry Andric 
15430b57cec5SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
15440b57cec5SDimitry Andric     // much of their semantics.
15450b57cec5SDimitry Andric     if (D->hasAttr<NakedAttr>())
15460b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
15470b57cec5SDimitry Andric 
15480b57cec5SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
15490b57cec5SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
15500b57cec5SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
15510b57cec5SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
15520b57cec5SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
15530b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
15540b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
15550b57cec5SDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
15560b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
1557480093f4SDimitry Andric   } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1558480093f4SDimitry Andric     // Add noinline if the function isn't always_inline.
15590b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
15600b57cec5SDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
15610b57cec5SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
15620b57cec5SDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
15630b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
15640b57cec5SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
15650b57cec5SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
15660b57cec5SDimitry Andric     // carry an explicit noinline attribute.
15670b57cec5SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
15680b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
15690b57cec5SDimitry Andric   } else {
15700b57cec5SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
15710b57cec5SDimitry Andric     // absence to mark things as noinline.
15720b57cec5SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15730b57cec5SDimitry Andric       // Search function and template pattern redeclarations for inline.
15740b57cec5SDimitry Andric       auto CheckForInline = [](const FunctionDecl *FD) {
15750b57cec5SDimitry Andric         auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
15760b57cec5SDimitry Andric           return Redecl->isInlineSpecified();
15770b57cec5SDimitry Andric         };
15780b57cec5SDimitry Andric         if (any_of(FD->redecls(), CheckRedeclForInline))
15790b57cec5SDimitry Andric           return true;
15800b57cec5SDimitry Andric         const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
15810b57cec5SDimitry Andric         if (!Pattern)
15820b57cec5SDimitry Andric           return false;
15830b57cec5SDimitry Andric         return any_of(Pattern->redecls(), CheckRedeclForInline);
15840b57cec5SDimitry Andric       };
15850b57cec5SDimitry Andric       if (CheckForInline(FD)) {
15860b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
15870b57cec5SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
15880b57cec5SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
15890b57cec5SDimitry Andric                  !FD->isInlined() &&
15900b57cec5SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
15910b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
15920b57cec5SDimitry Andric       }
15930b57cec5SDimitry Andric     }
15940b57cec5SDimitry Andric   }
15950b57cec5SDimitry Andric 
15960b57cec5SDimitry Andric   // Add other optimization related attributes if we are optimizing this
15970b57cec5SDimitry Andric   // function.
15980b57cec5SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
15990b57cec5SDimitry Andric     if (D->hasAttr<ColdAttr>()) {
16000b57cec5SDimitry Andric       if (!ShouldAddOptNone)
16010b57cec5SDimitry Andric         B.addAttribute(llvm::Attribute::OptimizeForSize);
16020b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
16030b57cec5SDimitry Andric     }
16040b57cec5SDimitry Andric 
16050b57cec5SDimitry Andric     if (D->hasAttr<MinSizeAttr>())
16060b57cec5SDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
16070b57cec5SDimitry Andric   }
16080b57cec5SDimitry Andric 
16090b57cec5SDimitry Andric   F->addAttributes(llvm::AttributeList::FunctionIndex, B);
16100b57cec5SDimitry Andric 
16110b57cec5SDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
16120b57cec5SDimitry Andric   if (alignment)
1613a7dea167SDimitry Andric     F->setAlignment(llvm::Align(alignment));
16140b57cec5SDimitry Andric 
16150b57cec5SDimitry Andric   if (!D->hasAttr<AlignedAttr>())
16160b57cec5SDimitry Andric     if (LangOpts.FunctionAlignment)
1617a7dea167SDimitry Andric       F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
16180b57cec5SDimitry Andric 
16190b57cec5SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
16200b57cec5SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
16210b57cec5SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
16220b57cec5SDimitry Andric   // member function, set its alignment accordingly.
16230b57cec5SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
16240b57cec5SDimitry Andric     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1625a7dea167SDimitry Andric       F->setAlignment(llvm::Align(2));
16260b57cec5SDimitry Andric   }
16270b57cec5SDimitry Andric 
1628a7dea167SDimitry Andric   // In the cross-dso CFI mode with canonical jump tables, we want !type
1629a7dea167SDimitry Andric   // attributes on definitions only.
1630a7dea167SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso &&
1631a7dea167SDimitry Andric       CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
1632a7dea167SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1633a7dea167SDimitry Andric       // Skip available_externally functions. They won't be codegen'ed in the
1634a7dea167SDimitry Andric       // current module anyway.
1635a7dea167SDimitry Andric       if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
16360b57cec5SDimitry Andric         CreateFunctionTypeMetadataForIcall(FD, F);
1637a7dea167SDimitry Andric     }
1638a7dea167SDimitry Andric   }
16390b57cec5SDimitry Andric 
16400b57cec5SDimitry Andric   // Emit type metadata on member functions for member function pointer checks.
16410b57cec5SDimitry Andric   // These are only ever necessary on definitions; we're guaranteed that the
16420b57cec5SDimitry Andric   // definition will be present in the LTO unit as a result of LTO visibility.
16430b57cec5SDimitry Andric   auto *MD = dyn_cast<CXXMethodDecl>(D);
16440b57cec5SDimitry Andric   if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
16450b57cec5SDimitry Andric     for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
16460b57cec5SDimitry Andric       llvm::Metadata *Id =
16470b57cec5SDimitry Andric           CreateMetadataIdentifierForType(Context.getMemberPointerType(
16480b57cec5SDimitry Andric               MD->getType(), Context.getRecordType(Base).getTypePtr()));
16490b57cec5SDimitry Andric       F->addTypeMetadata(0, Id);
16500b57cec5SDimitry Andric     }
16510b57cec5SDimitry Andric   }
16520b57cec5SDimitry Andric }
16530b57cec5SDimitry Andric 
16540b57cec5SDimitry Andric void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
16550b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
16560b57cec5SDimitry Andric   if (dyn_cast_or_null<NamedDecl>(D))
16570b57cec5SDimitry Andric     setGVProperties(GV, GD);
16580b57cec5SDimitry Andric   else
16590b57cec5SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
16600b57cec5SDimitry Andric 
16610b57cec5SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
16620b57cec5SDimitry Andric     addUsedGlobal(GV);
16630b57cec5SDimitry Andric 
16640b57cec5SDimitry Andric   if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
16650b57cec5SDimitry Andric     const auto *VD = cast<VarDecl>(D);
16660b57cec5SDimitry Andric     if (VD->getType().isConstQualified() &&
16670b57cec5SDimitry Andric         VD->getStorageDuration() == SD_Static)
16680b57cec5SDimitry Andric       addUsedGlobal(GV);
16690b57cec5SDimitry Andric   }
16700b57cec5SDimitry Andric }
16710b57cec5SDimitry Andric 
16720b57cec5SDimitry Andric bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
16730b57cec5SDimitry Andric                                                 llvm::AttrBuilder &Attrs) {
16740b57cec5SDimitry Andric   // Add target-cpu and target-features attributes to functions. If
16750b57cec5SDimitry Andric   // we have a decl for the function and it has a target attribute then
16760b57cec5SDimitry Andric   // parse that and add it to the feature set.
16770b57cec5SDimitry Andric   StringRef TargetCPU = getTarget().getTargetOpts().CPU;
16780b57cec5SDimitry Andric   std::vector<std::string> Features;
16790b57cec5SDimitry Andric   const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
16800b57cec5SDimitry Andric   FD = FD ? FD->getMostRecentDecl() : FD;
16810b57cec5SDimitry Andric   const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
16820b57cec5SDimitry Andric   const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
16830b57cec5SDimitry Andric   bool AddedAttr = false;
16840b57cec5SDimitry Andric   if (TD || SD) {
16850b57cec5SDimitry Andric     llvm::StringMap<bool> FeatureMap;
1686480093f4SDimitry Andric     getContext().getFunctionFeatureMap(FeatureMap, GD);
16870b57cec5SDimitry Andric 
16880b57cec5SDimitry Andric     // Produce the canonical string for this set of features.
16890b57cec5SDimitry Andric     for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
16900b57cec5SDimitry Andric       Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
16910b57cec5SDimitry Andric 
16920b57cec5SDimitry Andric     // Now add the target-cpu and target-features to the function.
16930b57cec5SDimitry Andric     // While we populated the feature map above, we still need to
16940b57cec5SDimitry Andric     // get and parse the target attribute so we can get the cpu for
16950b57cec5SDimitry Andric     // the function.
16960b57cec5SDimitry Andric     if (TD) {
1697480093f4SDimitry Andric       ParsedTargetAttr ParsedAttr = TD->parse();
16980b57cec5SDimitry Andric       if (ParsedAttr.Architecture != "" &&
16990b57cec5SDimitry Andric           getTarget().isValidCPUName(ParsedAttr.Architecture))
17000b57cec5SDimitry Andric         TargetCPU = ParsedAttr.Architecture;
17010b57cec5SDimitry Andric     }
17020b57cec5SDimitry Andric   } else {
17030b57cec5SDimitry Andric     // Otherwise just add the existing target cpu and target features to the
17040b57cec5SDimitry Andric     // function.
17050b57cec5SDimitry Andric     Features = getTarget().getTargetOpts().Features;
17060b57cec5SDimitry Andric   }
17070b57cec5SDimitry Andric 
17080b57cec5SDimitry Andric   if (TargetCPU != "") {
17090b57cec5SDimitry Andric     Attrs.addAttribute("target-cpu", TargetCPU);
17100b57cec5SDimitry Andric     AddedAttr = true;
17110b57cec5SDimitry Andric   }
17120b57cec5SDimitry Andric   if (!Features.empty()) {
17130b57cec5SDimitry Andric     llvm::sort(Features);
17140b57cec5SDimitry Andric     Attrs.addAttribute("target-features", llvm::join(Features, ","));
17150b57cec5SDimitry Andric     AddedAttr = true;
17160b57cec5SDimitry Andric   }
17170b57cec5SDimitry Andric 
17180b57cec5SDimitry Andric   return AddedAttr;
17190b57cec5SDimitry Andric }
17200b57cec5SDimitry Andric 
17210b57cec5SDimitry Andric void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
17220b57cec5SDimitry Andric                                           llvm::GlobalObject *GO) {
17230b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
17240b57cec5SDimitry Andric   SetCommonAttributes(GD, GO);
17250b57cec5SDimitry Andric 
17260b57cec5SDimitry Andric   if (D) {
17270b57cec5SDimitry Andric     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
17280b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
17290b57cec5SDimitry Andric         GV->addAttribute("bss-section", SA->getName());
17300b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
17310b57cec5SDimitry Andric         GV->addAttribute("data-section", SA->getName());
17320b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
17330b57cec5SDimitry Andric         GV->addAttribute("rodata-section", SA->getName());
1734a7dea167SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
1735a7dea167SDimitry Andric         GV->addAttribute("relro-section", SA->getName());
17360b57cec5SDimitry Andric     }
17370b57cec5SDimitry Andric 
17380b57cec5SDimitry Andric     if (auto *F = dyn_cast<llvm::Function>(GO)) {
17390b57cec5SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
17400b57cec5SDimitry Andric         if (!D->getAttr<SectionAttr>())
17410b57cec5SDimitry Andric           F->addFnAttr("implicit-section-name", SA->getName());
17420b57cec5SDimitry Andric 
17430b57cec5SDimitry Andric       llvm::AttrBuilder Attrs;
17440b57cec5SDimitry Andric       if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
17450b57cec5SDimitry Andric         // We know that GetCPUAndFeaturesAttributes will always have the
17460b57cec5SDimitry Andric         // newest set, since it has the newest possible FunctionDecl, so the
17470b57cec5SDimitry Andric         // new ones should replace the old.
17480b57cec5SDimitry Andric         F->removeFnAttr("target-cpu");
17490b57cec5SDimitry Andric         F->removeFnAttr("target-features");
17500b57cec5SDimitry Andric         F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
17510b57cec5SDimitry Andric       }
17520b57cec5SDimitry Andric     }
17530b57cec5SDimitry Andric 
17540b57cec5SDimitry Andric     if (const auto *CSA = D->getAttr<CodeSegAttr>())
17550b57cec5SDimitry Andric       GO->setSection(CSA->getName());
17560b57cec5SDimitry Andric     else if (const auto *SA = D->getAttr<SectionAttr>())
17570b57cec5SDimitry Andric       GO->setSection(SA->getName());
17580b57cec5SDimitry Andric   }
17590b57cec5SDimitry Andric 
17600b57cec5SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
17610b57cec5SDimitry Andric }
17620b57cec5SDimitry Andric 
17630b57cec5SDimitry Andric void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
17640b57cec5SDimitry Andric                                                   llvm::Function *F,
17650b57cec5SDimitry Andric                                                   const CGFunctionInfo &FI) {
17660b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
17670b57cec5SDimitry Andric   SetLLVMFunctionAttributes(GD, FI, F);
17680b57cec5SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, F);
17690b57cec5SDimitry Andric 
17700b57cec5SDimitry Andric   F->setLinkage(llvm::Function::InternalLinkage);
17710b57cec5SDimitry Andric 
17720b57cec5SDimitry Andric   setNonAliasAttributes(GD, F);
17730b57cec5SDimitry Andric }
17740b57cec5SDimitry Andric 
17750b57cec5SDimitry Andric static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
17760b57cec5SDimitry Andric   // Set linkage and visibility in case we never see a definition.
17770b57cec5SDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
17780b57cec5SDimitry Andric   // Don't set internal linkage on declarations.
17790b57cec5SDimitry Andric   // "extern_weak" is overloaded in LLVM; we probably should have
17800b57cec5SDimitry Andric   // separate linkage types for this.
17810b57cec5SDimitry Andric   if (isExternallyVisible(LV.getLinkage()) &&
17820b57cec5SDimitry Andric       (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
17830b57cec5SDimitry Andric     GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
17840b57cec5SDimitry Andric }
17850b57cec5SDimitry Andric 
17860b57cec5SDimitry Andric void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
17870b57cec5SDimitry Andric                                                        llvm::Function *F) {
17880b57cec5SDimitry Andric   // Only if we are checking indirect calls.
17890b57cec5SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
17900b57cec5SDimitry Andric     return;
17910b57cec5SDimitry Andric 
17920b57cec5SDimitry Andric   // Non-static class methods are handled via vtable or member function pointer
17930b57cec5SDimitry Andric   // checks elsewhere.
17940b57cec5SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
17950b57cec5SDimitry Andric     return;
17960b57cec5SDimitry Andric 
17970b57cec5SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
17980b57cec5SDimitry Andric   F->addTypeMetadata(0, MD);
17990b57cec5SDimitry Andric   F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
18000b57cec5SDimitry Andric 
18010b57cec5SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
18020b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
18030b57cec5SDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
18040b57cec5SDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
18050b57cec5SDimitry Andric }
18060b57cec5SDimitry Andric 
18070b57cec5SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
18080b57cec5SDimitry Andric                                           bool IsIncompleteFunction,
18090b57cec5SDimitry Andric                                           bool IsThunk) {
18100b57cec5SDimitry Andric 
18110b57cec5SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
18120b57cec5SDimitry Andric     // If this is an intrinsic function, set the function's attributes
18130b57cec5SDimitry Andric     // to the intrinsic's attributes.
18140b57cec5SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
18150b57cec5SDimitry Andric     return;
18160b57cec5SDimitry Andric   }
18170b57cec5SDimitry Andric 
18180b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
18190b57cec5SDimitry Andric 
18200b57cec5SDimitry Andric   if (!IsIncompleteFunction)
18210b57cec5SDimitry Andric     SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F);
18220b57cec5SDimitry Andric 
18230b57cec5SDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
18240b57cec5SDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
18250b57cec5SDimitry Andric   // GCC and does not actually return "this".
18260b57cec5SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
18270b57cec5SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
18280b57cec5SDimitry Andric     assert(!F->arg_empty() &&
18290b57cec5SDimitry Andric            F->arg_begin()->getType()
18300b57cec5SDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
18310b57cec5SDimitry Andric            "unexpected this return");
18320b57cec5SDimitry Andric     F->addAttribute(1, llvm::Attribute::Returned);
18330b57cec5SDimitry Andric   }
18340b57cec5SDimitry Andric 
18350b57cec5SDimitry Andric   // Only a few attributes are set on declarations; these may later be
18360b57cec5SDimitry Andric   // overridden by a definition.
18370b57cec5SDimitry Andric 
18380b57cec5SDimitry Andric   setLinkageForGV(F, FD);
18390b57cec5SDimitry Andric   setGVProperties(F, FD);
18400b57cec5SDimitry Andric 
18410b57cec5SDimitry Andric   // Setup target-specific attributes.
18420b57cec5SDimitry Andric   if (!IsIncompleteFunction && F->isDeclaration())
18430b57cec5SDimitry Andric     getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
18440b57cec5SDimitry Andric 
18450b57cec5SDimitry Andric   if (const auto *CSA = FD->getAttr<CodeSegAttr>())
18460b57cec5SDimitry Andric     F->setSection(CSA->getName());
18470b57cec5SDimitry Andric   else if (const auto *SA = FD->getAttr<SectionAttr>())
18480b57cec5SDimitry Andric      F->setSection(SA->getName());
18490b57cec5SDimitry Andric 
1850*d65cd7a5SDimitry Andric   // If we plan on emitting this inline builtin, we can't treat it as a builtin.
1851480093f4SDimitry Andric   if (FD->isInlineBuiltinDeclaration()) {
1852*d65cd7a5SDimitry Andric     const FunctionDecl *FDBody;
1853*d65cd7a5SDimitry Andric     bool HasBody = FD->hasBody(FDBody);
1854*d65cd7a5SDimitry Andric     (void)HasBody;
1855*d65cd7a5SDimitry Andric     assert(HasBody && "Inline builtin declarations should always have an "
1856*d65cd7a5SDimitry Andric                       "available body!");
1857*d65cd7a5SDimitry Andric     if (shouldEmitFunction(FDBody))
1858480093f4SDimitry Andric       F->addAttribute(llvm::AttributeList::FunctionIndex,
1859480093f4SDimitry Andric                       llvm::Attribute::NoBuiltin);
1860480093f4SDimitry Andric   }
1861480093f4SDimitry Andric 
18620b57cec5SDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
18630b57cec5SDimitry Andric     // A replaceable global allocation function does not act like a builtin by
18640b57cec5SDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
18650b57cec5SDimitry Andric     F->addAttribute(llvm::AttributeList::FunctionIndex,
18660b57cec5SDimitry Andric                     llvm::Attribute::NoBuiltin);
18670b57cec5SDimitry Andric 
18680b57cec5SDimitry Andric     // A sane operator new returns a non-aliasing pointer.
18690b57cec5SDimitry Andric     // FIXME: Also add NonNull attribute to the return value
18700b57cec5SDimitry Andric     // for the non-nothrow forms?
18710b57cec5SDimitry Andric     auto Kind = FD->getDeclName().getCXXOverloadedOperator();
18720b57cec5SDimitry Andric     if (getCodeGenOpts().AssumeSaneOperatorNew &&
18730b57cec5SDimitry Andric         (Kind == OO_New || Kind == OO_Array_New))
18740b57cec5SDimitry Andric       F->addAttribute(llvm::AttributeList::ReturnIndex,
18750b57cec5SDimitry Andric                       llvm::Attribute::NoAlias);
18760b57cec5SDimitry Andric   }
18770b57cec5SDimitry Andric 
18780b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
18790b57cec5SDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
18800b57cec5SDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
18810b57cec5SDimitry Andric     if (MD->isVirtual())
18820b57cec5SDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
18830b57cec5SDimitry Andric 
18840b57cec5SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
1885a7dea167SDimitry Andric   // is handled with better precision by the receiving DSO. But if jump tables
1886a7dea167SDimitry Andric   // are non-canonical then we need type metadata in order to produce the local
1887a7dea167SDimitry Andric   // jump table.
1888a7dea167SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso ||
1889a7dea167SDimitry Andric       !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
18900b57cec5SDimitry Andric     CreateFunctionTypeMetadataForIcall(FD, F);
18910b57cec5SDimitry Andric 
18920b57cec5SDimitry Andric   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
18930b57cec5SDimitry Andric     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
18940b57cec5SDimitry Andric 
18950b57cec5SDimitry Andric   if (const auto *CB = FD->getAttr<CallbackAttr>()) {
18960b57cec5SDimitry Andric     // Annotate the callback behavior as metadata:
18970b57cec5SDimitry Andric     //  - The callback callee (as argument number).
18980b57cec5SDimitry Andric     //  - The callback payloads (as argument numbers).
18990b57cec5SDimitry Andric     llvm::LLVMContext &Ctx = F->getContext();
19000b57cec5SDimitry Andric     llvm::MDBuilder MDB(Ctx);
19010b57cec5SDimitry Andric 
19020b57cec5SDimitry Andric     // The payload indices are all but the first one in the encoding. The first
19030b57cec5SDimitry Andric     // identifies the callback callee.
19040b57cec5SDimitry Andric     int CalleeIdx = *CB->encoding_begin();
19050b57cec5SDimitry Andric     ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
19060b57cec5SDimitry Andric     F->addMetadata(llvm::LLVMContext::MD_callback,
19070b57cec5SDimitry Andric                    *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
19080b57cec5SDimitry Andric                                                CalleeIdx, PayloadIndices,
19090b57cec5SDimitry Andric                                                /* VarArgsArePassed */ false)}));
19100b57cec5SDimitry Andric   }
19110b57cec5SDimitry Andric }
19120b57cec5SDimitry Andric 
19130b57cec5SDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
19140b57cec5SDimitry Andric   assert(!GV->isDeclaration() &&
19150b57cec5SDimitry Andric          "Only globals with definition can force usage.");
19160b57cec5SDimitry Andric   LLVMUsed.emplace_back(GV);
19170b57cec5SDimitry Andric }
19180b57cec5SDimitry Andric 
19190b57cec5SDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
19200b57cec5SDimitry Andric   assert(!GV->isDeclaration() &&
19210b57cec5SDimitry Andric          "Only globals with definition can force usage.");
19220b57cec5SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
19230b57cec5SDimitry Andric }
19240b57cec5SDimitry Andric 
19250b57cec5SDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
19260b57cec5SDimitry Andric                      std::vector<llvm::WeakTrackingVH> &List) {
19270b57cec5SDimitry Andric   // Don't create llvm.used if there is no need.
19280b57cec5SDimitry Andric   if (List.empty())
19290b57cec5SDimitry Andric     return;
19300b57cec5SDimitry Andric 
19310b57cec5SDimitry Andric   // Convert List to what ConstantArray needs.
19320b57cec5SDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
19330b57cec5SDimitry Andric   UsedArray.resize(List.size());
19340b57cec5SDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
19350b57cec5SDimitry Andric     UsedArray[i] =
19360b57cec5SDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
19370b57cec5SDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
19380b57cec5SDimitry Andric   }
19390b57cec5SDimitry Andric 
19400b57cec5SDimitry Andric   if (UsedArray.empty())
19410b57cec5SDimitry Andric     return;
19420b57cec5SDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
19430b57cec5SDimitry Andric 
19440b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
19450b57cec5SDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
19460b57cec5SDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
19470b57cec5SDimitry Andric 
19480b57cec5SDimitry Andric   GV->setSection("llvm.metadata");
19490b57cec5SDimitry Andric }
19500b57cec5SDimitry Andric 
19510b57cec5SDimitry Andric void CodeGenModule::emitLLVMUsed() {
19520b57cec5SDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
19530b57cec5SDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
19540b57cec5SDimitry Andric }
19550b57cec5SDimitry Andric 
19560b57cec5SDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
19570b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
19580b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
19590b57cec5SDimitry Andric }
19600b57cec5SDimitry Andric 
19610b57cec5SDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
19620b57cec5SDimitry Andric   llvm::SmallString<32> Opt;
19630b57cec5SDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1964480093f4SDimitry Andric   if (Opt.empty())
1965480093f4SDimitry Andric     return;
19660b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
19670b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
19680b57cec5SDimitry Andric }
19690b57cec5SDimitry Andric 
19700b57cec5SDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
19710b57cec5SDimitry Andric   auto &C = getLLVMContext();
19720b57cec5SDimitry Andric   if (getTarget().getTriple().isOSBinFormatELF()) {
19730b57cec5SDimitry Andric       ELFDependentLibraries.push_back(
19740b57cec5SDimitry Andric         llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
19750b57cec5SDimitry Andric     return;
19760b57cec5SDimitry Andric   }
19770b57cec5SDimitry Andric 
19780b57cec5SDimitry Andric   llvm::SmallString<24> Opt;
19790b57cec5SDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
19800b57cec5SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
19810b57cec5SDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
19820b57cec5SDimitry Andric }
19830b57cec5SDimitry Andric 
19840b57cec5SDimitry Andric /// Add link options implied by the given module, including modules
19850b57cec5SDimitry Andric /// it depends on, using a postorder walk.
19860b57cec5SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
19870b57cec5SDimitry Andric                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
19880b57cec5SDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
19890b57cec5SDimitry Andric   // Import this module's parent.
19900b57cec5SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
19910b57cec5SDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
19920b57cec5SDimitry Andric   }
19930b57cec5SDimitry Andric 
19940b57cec5SDimitry Andric   // Import this module's dependencies.
19950b57cec5SDimitry Andric   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
19960b57cec5SDimitry Andric     if (Visited.insert(Mod->Imports[I - 1]).second)
19970b57cec5SDimitry Andric       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
19980b57cec5SDimitry Andric   }
19990b57cec5SDimitry Andric 
20000b57cec5SDimitry Andric   // Add linker options to link against the libraries/frameworks
20010b57cec5SDimitry Andric   // described by this module.
20020b57cec5SDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
20030b57cec5SDimitry Andric   bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
20040b57cec5SDimitry Andric 
20050b57cec5SDimitry Andric   // For modules that use export_as for linking, use that module
20060b57cec5SDimitry Andric   // name instead.
20070b57cec5SDimitry Andric   if (Mod->UseExportAsModuleLinkName)
20080b57cec5SDimitry Andric     return;
20090b57cec5SDimitry Andric 
20100b57cec5SDimitry Andric   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
20110b57cec5SDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
20120b57cec5SDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
20130b57cec5SDimitry Andric     if (Mod->LinkLibraries[I-1].IsFramework) {
20140b57cec5SDimitry Andric       llvm::Metadata *Args[2] = {
20150b57cec5SDimitry Andric           llvm::MDString::get(Context, "-framework"),
20160b57cec5SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
20170b57cec5SDimitry Andric 
20180b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
20190b57cec5SDimitry Andric       continue;
20200b57cec5SDimitry Andric     }
20210b57cec5SDimitry Andric 
20220b57cec5SDimitry Andric     // Link against a library.
20230b57cec5SDimitry Andric     if (IsELF) {
20240b57cec5SDimitry Andric       llvm::Metadata *Args[2] = {
20250b57cec5SDimitry Andric           llvm::MDString::get(Context, "lib"),
20260b57cec5SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
20270b57cec5SDimitry Andric       };
20280b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
20290b57cec5SDimitry Andric     } else {
20300b57cec5SDimitry Andric       llvm::SmallString<24> Opt;
20310b57cec5SDimitry Andric       CGM.getTargetCodeGenInfo().getDependentLibraryOption(
20320b57cec5SDimitry Andric           Mod->LinkLibraries[I - 1].Library, Opt);
20330b57cec5SDimitry Andric       auto *OptString = llvm::MDString::get(Context, Opt);
20340b57cec5SDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, OptString));
20350b57cec5SDimitry Andric     }
20360b57cec5SDimitry Andric   }
20370b57cec5SDimitry Andric }
20380b57cec5SDimitry Andric 
20390b57cec5SDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
20400b57cec5SDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
20410b57cec5SDimitry Andric   // options, which is essentially the imported modules and all of their
20420b57cec5SDimitry Andric   // non-explicit child modules.
20430b57cec5SDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
20440b57cec5SDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
20450b57cec5SDimitry Andric   SmallVector<clang::Module *, 16> Stack;
20460b57cec5SDimitry Andric 
20470b57cec5SDimitry Andric   // Seed the stack with imported modules.
20480b57cec5SDimitry Andric   for (Module *M : ImportedModules) {
20490b57cec5SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
20500b57cec5SDimitry Andric     // a header of that same module.
20510b57cec5SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
20520b57cec5SDimitry Andric         !getLangOpts().isCompilingModule())
20530b57cec5SDimitry Andric       continue;
20540b57cec5SDimitry Andric     if (Visited.insert(M).second)
20550b57cec5SDimitry Andric       Stack.push_back(M);
20560b57cec5SDimitry Andric   }
20570b57cec5SDimitry Andric 
20580b57cec5SDimitry Andric   // Find all of the modules to import, making a little effort to prune
20590b57cec5SDimitry Andric   // non-leaf modules.
20600b57cec5SDimitry Andric   while (!Stack.empty()) {
20610b57cec5SDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
20620b57cec5SDimitry Andric 
20630b57cec5SDimitry Andric     bool AnyChildren = false;
20640b57cec5SDimitry Andric 
20650b57cec5SDimitry Andric     // Visit the submodules of this module.
20660b57cec5SDimitry Andric     for (const auto &SM : Mod->submodules()) {
20670b57cec5SDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
20680b57cec5SDimitry Andric       // linked against.
20690b57cec5SDimitry Andric       if (SM->IsExplicit)
20700b57cec5SDimitry Andric         continue;
20710b57cec5SDimitry Andric 
20720b57cec5SDimitry Andric       if (Visited.insert(SM).second) {
20730b57cec5SDimitry Andric         Stack.push_back(SM);
20740b57cec5SDimitry Andric         AnyChildren = true;
20750b57cec5SDimitry Andric       }
20760b57cec5SDimitry Andric     }
20770b57cec5SDimitry Andric 
20780b57cec5SDimitry Andric     // We didn't find any children, so add this module to the list of
20790b57cec5SDimitry Andric     // modules to link against.
20800b57cec5SDimitry Andric     if (!AnyChildren) {
20810b57cec5SDimitry Andric       LinkModules.insert(Mod);
20820b57cec5SDimitry Andric     }
20830b57cec5SDimitry Andric   }
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric   // Add link options for all of the imported modules in reverse topological
20860b57cec5SDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
20870b57cec5SDimitry Andric   // to linker options inserted by things like #pragma comment().
20880b57cec5SDimitry Andric   SmallVector<llvm::MDNode *, 16> MetadataArgs;
20890b57cec5SDimitry Andric   Visited.clear();
20900b57cec5SDimitry Andric   for (Module *M : LinkModules)
20910b57cec5SDimitry Andric     if (Visited.insert(M).second)
20920b57cec5SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
20930b57cec5SDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
20940b57cec5SDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
20950b57cec5SDimitry Andric 
20960b57cec5SDimitry Andric   // Add the linker options metadata flag.
20970b57cec5SDimitry Andric   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
20980b57cec5SDimitry Andric   for (auto *MD : LinkerOptionsMetadata)
20990b57cec5SDimitry Andric     NMD->addOperand(MD);
21000b57cec5SDimitry Andric }
21010b57cec5SDimitry Andric 
21020b57cec5SDimitry Andric void CodeGenModule::EmitDeferred() {
21030b57cec5SDimitry Andric   // Emit deferred declare target declarations.
21040b57cec5SDimitry Andric   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
21050b57cec5SDimitry Andric     getOpenMPRuntime().emitDeferredTargetDecls();
21060b57cec5SDimitry Andric 
21070b57cec5SDimitry Andric   // Emit code for any potentially referenced deferred decls.  Since a
21080b57cec5SDimitry Andric   // previously unused static decl may become used during the generation of code
21090b57cec5SDimitry Andric   // for a static function, iterate until no changes are made.
21100b57cec5SDimitry Andric 
21110b57cec5SDimitry Andric   if (!DeferredVTables.empty()) {
21120b57cec5SDimitry Andric     EmitDeferredVTables();
21130b57cec5SDimitry Andric 
21140b57cec5SDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
21150b57cec5SDimitry Andric     // become deferred, although it can cause functions to be
21160b57cec5SDimitry Andric     // emitted that then need those vtables.
21170b57cec5SDimitry Andric     assert(DeferredVTables.empty());
21180b57cec5SDimitry Andric   }
21190b57cec5SDimitry Andric 
21200b57cec5SDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
21210b57cec5SDimitry Andric   if (DeferredDeclsToEmit.empty())
21220b57cec5SDimitry Andric     return;
21230b57cec5SDimitry Andric 
21240b57cec5SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
21250b57cec5SDimitry Andric   // work, it will not interfere with this.
21260b57cec5SDimitry Andric   std::vector<GlobalDecl> CurDeclsToEmit;
21270b57cec5SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
21280b57cec5SDimitry Andric 
21290b57cec5SDimitry Andric   for (GlobalDecl &D : CurDeclsToEmit) {
21300b57cec5SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
21310b57cec5SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
21320b57cec5SDimitry Andric     // might had been created for another decl with the same mangled name but
21330b57cec5SDimitry Andric     // different type.
21340b57cec5SDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
21350b57cec5SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric     // In case of different address spaces, we may still get a cast, even with
21380b57cec5SDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
21390b57cec5SDimitry Andric     // GlobalValue.
21400b57cec5SDimitry Andric     if (!GV)
21410b57cec5SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
21420b57cec5SDimitry Andric 
21430b57cec5SDimitry Andric     // Make sure GetGlobalValue returned non-null.
21440b57cec5SDimitry Andric     assert(GV);
21450b57cec5SDimitry Andric 
21460b57cec5SDimitry Andric     // Check to see if we've already emitted this.  This is necessary
21470b57cec5SDimitry Andric     // for a couple of reasons: first, decls can end up in the
21480b57cec5SDimitry Andric     // deferred-decls queue multiple times, and second, decls can end
21490b57cec5SDimitry Andric     // up with definitions in unusual ways (e.g. by an extern inline
21500b57cec5SDimitry Andric     // function acquiring a strong function redefinition).  Just
21510b57cec5SDimitry Andric     // ignore these cases.
21520b57cec5SDimitry Andric     if (!GV->isDeclaration())
21530b57cec5SDimitry Andric       continue;
21540b57cec5SDimitry Andric 
2155a7dea167SDimitry Andric     // If this is OpenMP, check if it is legal to emit this global normally.
2156a7dea167SDimitry Andric     if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
2157a7dea167SDimitry Andric       continue;
2158a7dea167SDimitry Andric 
21590b57cec5SDimitry Andric     // Otherwise, emit the definition and move on to the next one.
21600b57cec5SDimitry Andric     EmitGlobalDefinition(D, GV);
21610b57cec5SDimitry Andric 
21620b57cec5SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
21630b57cec5SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
21640b57cec5SDimitry Andric     // ones are close together, which is convenient for testing.
21650b57cec5SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
21660b57cec5SDimitry Andric       EmitDeferred();
21670b57cec5SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
21680b57cec5SDimitry Andric     }
21690b57cec5SDimitry Andric   }
21700b57cec5SDimitry Andric }
21710b57cec5SDimitry Andric 
21720b57cec5SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() {
21730b57cec5SDimitry Andric   // Try to emit external vtables as available_externally if they have emitted
21740b57cec5SDimitry Andric   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
21750b57cec5SDimitry Andric   // is not allowed to create new references to things that need to be emitted
21760b57cec5SDimitry Andric   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
21770b57cec5SDimitry Andric 
21780b57cec5SDimitry Andric   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
21790b57cec5SDimitry Andric          && "Only emit opportunistic vtables with optimizations");
21800b57cec5SDimitry Andric 
21810b57cec5SDimitry Andric   for (const CXXRecordDecl *RD : OpportunisticVTables) {
21820b57cec5SDimitry Andric     assert(getVTables().isVTableExternal(RD) &&
21830b57cec5SDimitry Andric            "This queue should only contain external vtables");
21840b57cec5SDimitry Andric     if (getCXXABI().canSpeculativelyEmitVTable(RD))
21850b57cec5SDimitry Andric       VTables.GenerateClassData(RD);
21860b57cec5SDimitry Andric   }
21870b57cec5SDimitry Andric   OpportunisticVTables.clear();
21880b57cec5SDimitry Andric }
21890b57cec5SDimitry Andric 
21900b57cec5SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
21910b57cec5SDimitry Andric   if (Annotations.empty())
21920b57cec5SDimitry Andric     return;
21930b57cec5SDimitry Andric 
21940b57cec5SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
21950b57cec5SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
21960b57cec5SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
21970b57cec5SDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
21980b57cec5SDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
21990b57cec5SDimitry Andric                                       Array, "llvm.global.annotations");
22000b57cec5SDimitry Andric   gv->setSection(AnnotationSection);
22010b57cec5SDimitry Andric }
22020b57cec5SDimitry Andric 
22030b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
22040b57cec5SDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
22050b57cec5SDimitry Andric   if (AStr)
22060b57cec5SDimitry Andric     return AStr;
22070b57cec5SDimitry Andric 
22080b57cec5SDimitry Andric   // Not found yet, create a new global.
22090b57cec5SDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
22100b57cec5SDimitry Andric   auto *gv =
22110b57cec5SDimitry Andric       new llvm::GlobalVariable(getModule(), s->getType(), true,
22120b57cec5SDimitry Andric                                llvm::GlobalValue::PrivateLinkage, s, ".str");
22130b57cec5SDimitry Andric   gv->setSection(AnnotationSection);
22140b57cec5SDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
22150b57cec5SDimitry Andric   AStr = gv;
22160b57cec5SDimitry Andric   return gv;
22170b57cec5SDimitry Andric }
22180b57cec5SDimitry Andric 
22190b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
22200b57cec5SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
22210b57cec5SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
22220b57cec5SDimitry Andric   if (PLoc.isValid())
22230b57cec5SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
22240b57cec5SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
22250b57cec5SDimitry Andric }
22260b57cec5SDimitry Andric 
22270b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
22280b57cec5SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
22290b57cec5SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
22300b57cec5SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
22310b57cec5SDimitry Andric     SM.getExpansionLineNumber(L);
22320b57cec5SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
22330b57cec5SDimitry Andric }
22340b57cec5SDimitry Andric 
22350b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
22360b57cec5SDimitry Andric                                                 const AnnotateAttr *AA,
22370b57cec5SDimitry Andric                                                 SourceLocation L) {
22380b57cec5SDimitry Andric   // Get the globals for file name, annotation, and the line number.
22390b57cec5SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
22400b57cec5SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
22410b57cec5SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L);
22420b57cec5SDimitry Andric 
2243480093f4SDimitry Andric   llvm::Constant *ASZeroGV = GV;
2244480093f4SDimitry Andric   if (GV->getAddressSpace() != 0) {
2245480093f4SDimitry Andric     ASZeroGV = llvm::ConstantExpr::getAddrSpaceCast(
2246480093f4SDimitry Andric                    GV, GV->getValueType()->getPointerTo(0));
2247480093f4SDimitry Andric   }
2248480093f4SDimitry Andric 
22490b57cec5SDimitry Andric   // Create the ConstantStruct for the global annotation.
22500b57cec5SDimitry Andric   llvm::Constant *Fields[4] = {
2251480093f4SDimitry Andric     llvm::ConstantExpr::getBitCast(ASZeroGV, Int8PtrTy),
22520b57cec5SDimitry Andric     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
22530b57cec5SDimitry Andric     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
22540b57cec5SDimitry Andric     LineNoCst
22550b57cec5SDimitry Andric   };
22560b57cec5SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
22570b57cec5SDimitry Andric }
22580b57cec5SDimitry Andric 
22590b57cec5SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
22600b57cec5SDimitry Andric                                          llvm::GlobalValue *GV) {
22610b57cec5SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
22620b57cec5SDimitry Andric   // Get the struct elements for these annotations.
22630b57cec5SDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
22640b57cec5SDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
22650b57cec5SDimitry Andric }
22660b57cec5SDimitry Andric 
22670b57cec5SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
22680b57cec5SDimitry Andric                                            llvm::Function *Fn,
22690b57cec5SDimitry Andric                                            SourceLocation Loc) const {
22700b57cec5SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
22710b57cec5SDimitry Andric   // Blacklist by function name.
22720b57cec5SDimitry Andric   if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
22730b57cec5SDimitry Andric     return true;
22740b57cec5SDimitry Andric   // Blacklist by location.
22750b57cec5SDimitry Andric   if (Loc.isValid())
22760b57cec5SDimitry Andric     return SanitizerBL.isBlacklistedLocation(Kind, Loc);
22770b57cec5SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
22780b57cec5SDimitry Andric   // it's located in the main file.
22790b57cec5SDimitry Andric   auto &SM = Context.getSourceManager();
22800b57cec5SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
22810b57cec5SDimitry Andric     return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
22820b57cec5SDimitry Andric   }
22830b57cec5SDimitry Andric   return false;
22840b57cec5SDimitry Andric }
22850b57cec5SDimitry Andric 
22860b57cec5SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
22870b57cec5SDimitry Andric                                            SourceLocation Loc, QualType Ty,
22880b57cec5SDimitry Andric                                            StringRef Category) const {
22890b57cec5SDimitry Andric   // For now globals can be blacklisted only in ASan and KASan.
22900b57cec5SDimitry Andric   const SanitizerMask EnabledAsanMask =
22910b57cec5SDimitry Andric       LangOpts.Sanitize.Mask &
22920b57cec5SDimitry Andric       (SanitizerKind::Address | SanitizerKind::KernelAddress |
22930b57cec5SDimitry Andric        SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
22940b57cec5SDimitry Andric        SanitizerKind::MemTag);
22950b57cec5SDimitry Andric   if (!EnabledAsanMask)
22960b57cec5SDimitry Andric     return false;
22970b57cec5SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
22980b57cec5SDimitry Andric   if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
22990b57cec5SDimitry Andric     return true;
23000b57cec5SDimitry Andric   if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
23010b57cec5SDimitry Andric     return true;
23020b57cec5SDimitry Andric   // Check global type.
23030b57cec5SDimitry Andric   if (!Ty.isNull()) {
23040b57cec5SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
23050b57cec5SDimitry Andric     // blacklisted, we also don't instrument arrays of them.
23060b57cec5SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
23070b57cec5SDimitry Andric       Ty = AT->getElementType();
23080b57cec5SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
23090b57cec5SDimitry Andric     // We allow to blacklist only record types (classes, structs etc.)
23100b57cec5SDimitry Andric     if (Ty->isRecordType()) {
23110b57cec5SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
23120b57cec5SDimitry Andric       if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
23130b57cec5SDimitry Andric         return true;
23140b57cec5SDimitry Andric     }
23150b57cec5SDimitry Andric   }
23160b57cec5SDimitry Andric   return false;
23170b57cec5SDimitry Andric }
23180b57cec5SDimitry Andric 
23190b57cec5SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
23200b57cec5SDimitry Andric                                    StringRef Category) const {
23210b57cec5SDimitry Andric   const auto &XRayFilter = getContext().getXRayFilter();
23220b57cec5SDimitry Andric   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
23230b57cec5SDimitry Andric   auto Attr = ImbueAttr::NONE;
23240b57cec5SDimitry Andric   if (Loc.isValid())
23250b57cec5SDimitry Andric     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
23260b57cec5SDimitry Andric   if (Attr == ImbueAttr::NONE)
23270b57cec5SDimitry Andric     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
23280b57cec5SDimitry Andric   switch (Attr) {
23290b57cec5SDimitry Andric   case ImbueAttr::NONE:
23300b57cec5SDimitry Andric     return false;
23310b57cec5SDimitry Andric   case ImbueAttr::ALWAYS:
23320b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
23330b57cec5SDimitry Andric     break;
23340b57cec5SDimitry Andric   case ImbueAttr::ALWAYS_ARG1:
23350b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
23360b57cec5SDimitry Andric     Fn->addFnAttr("xray-log-args", "1");
23370b57cec5SDimitry Andric     break;
23380b57cec5SDimitry Andric   case ImbueAttr::NEVER:
23390b57cec5SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-never");
23400b57cec5SDimitry Andric     break;
23410b57cec5SDimitry Andric   }
23420b57cec5SDimitry Andric   return true;
23430b57cec5SDimitry Andric }
23440b57cec5SDimitry Andric 
23450b57cec5SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
23460b57cec5SDimitry Andric   // Never defer when EmitAllDecls is specified.
23470b57cec5SDimitry Andric   if (LangOpts.EmitAllDecls)
23480b57cec5SDimitry Andric     return true;
23490b57cec5SDimitry Andric 
23500b57cec5SDimitry Andric   if (CodeGenOpts.KeepStaticConsts) {
23510b57cec5SDimitry Andric     const auto *VD = dyn_cast<VarDecl>(Global);
23520b57cec5SDimitry Andric     if (VD && VD->getType().isConstQualified() &&
23530b57cec5SDimitry Andric         VD->getStorageDuration() == SD_Static)
23540b57cec5SDimitry Andric       return true;
23550b57cec5SDimitry Andric   }
23560b57cec5SDimitry Andric 
23570b57cec5SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
23580b57cec5SDimitry Andric }
23590b57cec5SDimitry Andric 
23600b57cec5SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2361a7dea167SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
23620b57cec5SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
23630b57cec5SDimitry Andric       // Implicit template instantiations may change linkage if they are later
23640b57cec5SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
23650b57cec5SDimitry Andric       return false;
2366a7dea167SDimitry Andric     // In OpenMP 5.0 function may be marked as device_type(nohost) and we should
2367a7dea167SDimitry Andric     // not emit them eagerly unless we sure that the function must be emitted on
2368a7dea167SDimitry Andric     // the host.
2369a7dea167SDimitry Andric     if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd &&
2370a7dea167SDimitry Andric         !LangOpts.OpenMPIsDevice &&
2371a7dea167SDimitry Andric         !OMPDeclareTargetDeclAttr::getDeviceType(FD) &&
2372a7dea167SDimitry Andric         !FD->isUsed(/*CheckUsedAttr=*/false) && !FD->isReferenced())
2373a7dea167SDimitry Andric       return false;
2374a7dea167SDimitry Andric   }
23750b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global))
23760b57cec5SDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
23770b57cec5SDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
23780b57cec5SDimitry Andric       // A definition of an inline constexpr static data member may change
23790b57cec5SDimitry Andric       // linkage later if it's redeclared outside the class.
23800b57cec5SDimitry Andric       return false;
23810b57cec5SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
23820b57cec5SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
23830b57cec5SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
23840b57cec5SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
23850b57cec5SDimitry Andric       !isTypeConstant(Global->getType(), false) &&
23860b57cec5SDimitry Andric       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
23870b57cec5SDimitry Andric     return false;
23880b57cec5SDimitry Andric 
23890b57cec5SDimitry Andric   return true;
23900b57cec5SDimitry Andric }
23910b57cec5SDimitry Andric 
23920b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
23930b57cec5SDimitry Andric     const CXXUuidofExpr* E) {
23940b57cec5SDimitry Andric   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
23950b57cec5SDimitry Andric   // well-formed.
23960b57cec5SDimitry Andric   StringRef Uuid = E->getUuidStr();
23970b57cec5SDimitry Andric   std::string Name = "_GUID_" + Uuid.lower();
23980b57cec5SDimitry Andric   std::replace(Name.begin(), Name.end(), '-', '_');
23990b57cec5SDimitry Andric 
24000b57cec5SDimitry Andric   // The UUID descriptor should be pointer aligned.
24010b57cec5SDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
24020b57cec5SDimitry Andric 
24030b57cec5SDimitry Andric   // Look for an existing global.
24040b57cec5SDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
24050b57cec5SDimitry Andric     return ConstantAddress(GV, Alignment);
24060b57cec5SDimitry Andric 
24070b57cec5SDimitry Andric   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
24080b57cec5SDimitry Andric   assert(Init && "failed to initialize as constant");
24090b57cec5SDimitry Andric 
24100b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
24110b57cec5SDimitry Andric       getModule(), Init->getType(),
24120b57cec5SDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
24130b57cec5SDimitry Andric   if (supportsCOMDAT())
24140b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
24150b57cec5SDimitry Andric   setDSOLocal(GV);
24160b57cec5SDimitry Andric   return ConstantAddress(GV, Alignment);
24170b57cec5SDimitry Andric }
24180b57cec5SDimitry Andric 
24190b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
24200b57cec5SDimitry Andric   const AliasAttr *AA = VD->getAttr<AliasAttr>();
24210b57cec5SDimitry Andric   assert(AA && "No alias?");
24220b57cec5SDimitry Andric 
24230b57cec5SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
24240b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
24250b57cec5SDimitry Andric 
24260b57cec5SDimitry Andric   // See if there is already something with the target's name in the module.
24270b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
24280b57cec5SDimitry Andric   if (Entry) {
24290b57cec5SDimitry Andric     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
24300b57cec5SDimitry Andric     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
24310b57cec5SDimitry Andric     return ConstantAddress(Ptr, Alignment);
24320b57cec5SDimitry Andric   }
24330b57cec5SDimitry Andric 
24340b57cec5SDimitry Andric   llvm::Constant *Aliasee;
24350b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(DeclTy))
24360b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
24370b57cec5SDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
24380b57cec5SDimitry Andric                                       /*ForVTable=*/false);
24390b57cec5SDimitry Andric   else
24400b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
24410b57cec5SDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
24420b57cec5SDimitry Andric                                     nullptr);
24430b57cec5SDimitry Andric 
24440b57cec5SDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
24450b57cec5SDimitry Andric   F->setLinkage(llvm::Function::ExternalWeakLinkage);
24460b57cec5SDimitry Andric   WeakRefReferences.insert(F);
24470b57cec5SDimitry Andric 
24480b57cec5SDimitry Andric   return ConstantAddress(Aliasee, Alignment);
24490b57cec5SDimitry Andric }
24500b57cec5SDimitry Andric 
24510b57cec5SDimitry Andric void CodeGenModule::EmitGlobal(GlobalDecl GD) {
24520b57cec5SDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
24530b57cec5SDimitry Andric 
24540b57cec5SDimitry Andric   // Weak references don't produce any output by themselves.
24550b57cec5SDimitry Andric   if (Global->hasAttr<WeakRefAttr>())
24560b57cec5SDimitry Andric     return;
24570b57cec5SDimitry Andric 
24580b57cec5SDimitry Andric   // If this is an alias definition (which otherwise looks like a declaration)
24590b57cec5SDimitry Andric   // emit it now.
24600b57cec5SDimitry Andric   if (Global->hasAttr<AliasAttr>())
24610b57cec5SDimitry Andric     return EmitAliasDefinition(GD);
24620b57cec5SDimitry Andric 
24630b57cec5SDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
24640b57cec5SDimitry Andric   if (Global->hasAttr<IFuncAttr>())
24650b57cec5SDimitry Andric     return emitIFuncDefinition(GD);
24660b57cec5SDimitry Andric 
24670b57cec5SDimitry Andric   // If this is a cpu_dispatch multiversion function, emit the resolver.
24680b57cec5SDimitry Andric   if (Global->hasAttr<CPUDispatchAttr>())
24690b57cec5SDimitry Andric     return emitCPUDispatchDefinition(GD);
24700b57cec5SDimitry Andric 
24710b57cec5SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
24720b57cec5SDimitry Andric   if (LangOpts.CUDA) {
24730b57cec5SDimitry Andric     if (LangOpts.CUDAIsDevice) {
24740b57cec5SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
24750b57cec5SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
24760b57cec5SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
24770b57cec5SDimitry Andric           !Global->hasAttr<CUDASharedAttr>() &&
24780b57cec5SDimitry Andric           !(LangOpts.HIP && Global->hasAttr<HIPPinnedShadowAttr>()))
24790b57cec5SDimitry Andric         return;
24800b57cec5SDimitry Andric     } else {
24810b57cec5SDimitry Andric       // We need to emit host-side 'shadows' for all global
24820b57cec5SDimitry Andric       // device-side variables because the CUDA runtime needs their
24830b57cec5SDimitry Andric       // size and host-side address in order to provide access to
24840b57cec5SDimitry Andric       // their device-side incarnations.
24850b57cec5SDimitry Andric 
24860b57cec5SDimitry Andric       // So device-only functions are the only things we skip.
24870b57cec5SDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
24880b57cec5SDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
24890b57cec5SDimitry Andric         return;
24900b57cec5SDimitry Andric 
24910b57cec5SDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
24920b57cec5SDimitry Andric              "Expected Variable or Function");
24930b57cec5SDimitry Andric     }
24940b57cec5SDimitry Andric   }
24950b57cec5SDimitry Andric 
24960b57cec5SDimitry Andric   if (LangOpts.OpenMP) {
2497a7dea167SDimitry Andric     // If this is OpenMP, check if it is legal to emit this global normally.
24980b57cec5SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
24990b57cec5SDimitry Andric       return;
25000b57cec5SDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
25010b57cec5SDimitry Andric       if (MustBeEmitted(Global))
25020b57cec5SDimitry Andric         EmitOMPDeclareReduction(DRD);
25030b57cec5SDimitry Andric       return;
25040b57cec5SDimitry Andric     } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
25050b57cec5SDimitry Andric       if (MustBeEmitted(Global))
25060b57cec5SDimitry Andric         EmitOMPDeclareMapper(DMD);
25070b57cec5SDimitry Andric       return;
25080b57cec5SDimitry Andric     }
25090b57cec5SDimitry Andric   }
25100b57cec5SDimitry Andric 
25110b57cec5SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
25120b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
25130b57cec5SDimitry Andric     // Forward declarations are emitted lazily on first use.
25140b57cec5SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
25150b57cec5SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
25160b57cec5SDimitry Andric         return;
25170b57cec5SDimitry Andric 
25180b57cec5SDimitry Andric       StringRef MangledName = getMangledName(GD);
25190b57cec5SDimitry Andric 
25200b57cec5SDimitry Andric       // Compute the function info and LLVM type.
25210b57cec5SDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
25220b57cec5SDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
25230b57cec5SDimitry Andric 
25240b57cec5SDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
25250b57cec5SDimitry Andric                               /*DontDefer=*/false);
25260b57cec5SDimitry Andric       return;
25270b57cec5SDimitry Andric     }
25280b57cec5SDimitry Andric   } else {
25290b57cec5SDimitry Andric     const auto *VD = cast<VarDecl>(Global);
25300b57cec5SDimitry Andric     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
25310b57cec5SDimitry Andric     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
25320b57cec5SDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
25330b57cec5SDimitry Andric       if (LangOpts.OpenMP) {
25340b57cec5SDimitry Andric         // Emit declaration of the must-be-emitted declare target variable.
25350b57cec5SDimitry Andric         if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
25360b57cec5SDimitry Andric                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
25370b57cec5SDimitry Andric           bool UnifiedMemoryEnabled =
25380b57cec5SDimitry Andric               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
25390b57cec5SDimitry Andric           if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
25400b57cec5SDimitry Andric               !UnifiedMemoryEnabled) {
25410b57cec5SDimitry Andric             (void)GetAddrOfGlobalVar(VD);
25420b57cec5SDimitry Andric           } else {
25430b57cec5SDimitry Andric             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
25440b57cec5SDimitry Andric                     (*Res == OMPDeclareTargetDeclAttr::MT_To &&
25450b57cec5SDimitry Andric                      UnifiedMemoryEnabled)) &&
25460b57cec5SDimitry Andric                    "Link clause or to clause with unified memory expected.");
25470b57cec5SDimitry Andric             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
25480b57cec5SDimitry Andric           }
25490b57cec5SDimitry Andric 
25500b57cec5SDimitry Andric           return;
25510b57cec5SDimitry Andric         }
25520b57cec5SDimitry Andric       }
25530b57cec5SDimitry Andric       // If this declaration may have caused an inline variable definition to
25540b57cec5SDimitry Andric       // change linkage, make sure that it's emitted.
25550b57cec5SDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
25560b57cec5SDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
25570b57cec5SDimitry Andric         GetAddrOfGlobalVar(VD);
25580b57cec5SDimitry Andric       return;
25590b57cec5SDimitry Andric     }
25600b57cec5SDimitry Andric   }
25610b57cec5SDimitry Andric 
25620b57cec5SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
25630b57cec5SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
25640b57cec5SDimitry Andric   // to benefit from cache locality.
25650b57cec5SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
25660b57cec5SDimitry Andric     // Emit the definition if it can't be deferred.
25670b57cec5SDimitry Andric     EmitGlobalDefinition(GD);
25680b57cec5SDimitry Andric     return;
25690b57cec5SDimitry Andric   }
25700b57cec5SDimitry Andric 
2571a7dea167SDimitry Andric     // Check if this must be emitted as declare variant.
2572a7dea167SDimitry Andric   if (LangOpts.OpenMP && isa<FunctionDecl>(Global) && OpenMPRuntime &&
2573a7dea167SDimitry Andric       OpenMPRuntime->emitDeclareVariant(GD, /*IsForDefinition=*/false))
2574a7dea167SDimitry Andric     return;
2575a7dea167SDimitry Andric 
25760b57cec5SDimitry Andric   // If we're deferring emission of a C++ variable with an
25770b57cec5SDimitry Andric   // initializer, remember the order in which it appeared in the file.
25780b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
25790b57cec5SDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
25800b57cec5SDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
25810b57cec5SDimitry Andric     CXXGlobalInits.push_back(nullptr);
25820b57cec5SDimitry Andric   }
25830b57cec5SDimitry Andric 
25840b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
25850b57cec5SDimitry Andric   if (GetGlobalValue(MangledName) != nullptr) {
25860b57cec5SDimitry Andric     // The value has already been used and should therefore be emitted.
25870b57cec5SDimitry Andric     addDeferredDeclToEmit(GD);
25880b57cec5SDimitry Andric   } else if (MustBeEmitted(Global)) {
25890b57cec5SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
25900b57cec5SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
25910b57cec5SDimitry Andric     addDeferredDeclToEmit(GD);
25920b57cec5SDimitry Andric   } else {
25930b57cec5SDimitry Andric     // Otherwise, remember that we saw a deferred decl with this name.  The
25940b57cec5SDimitry Andric     // first use of the mangled name will cause it to move into
25950b57cec5SDimitry Andric     // DeferredDeclsToEmit.
25960b57cec5SDimitry Andric     DeferredDecls[MangledName] = GD;
25970b57cec5SDimitry Andric   }
25980b57cec5SDimitry Andric }
25990b57cec5SDimitry Andric 
26000b57cec5SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
26010b57cec5SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
26020b57cec5SDimitry Andric   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
26030b57cec5SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
26040b57cec5SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
26050b57cec5SDimitry Andric         return true;
26060b57cec5SDimitry Andric 
26070b57cec5SDimitry Andric   return false;
26080b57cec5SDimitry Andric }
26090b57cec5SDimitry Andric 
26100b57cec5SDimitry Andric namespace {
26110b57cec5SDimitry Andric   struct FunctionIsDirectlyRecursive
26120b57cec5SDimitry Andric       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
26130b57cec5SDimitry Andric     const StringRef Name;
26140b57cec5SDimitry Andric     const Builtin::Context &BI;
26150b57cec5SDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
26160b57cec5SDimitry Andric         : Name(N), BI(C) {}
26170b57cec5SDimitry Andric 
26180b57cec5SDimitry Andric     bool VisitCallExpr(const CallExpr *E) {
26190b57cec5SDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
26200b57cec5SDimitry Andric       if (!FD)
26210b57cec5SDimitry Andric         return false;
26220b57cec5SDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
26230b57cec5SDimitry Andric       if (Attr && Name == Attr->getLabel())
26240b57cec5SDimitry Andric         return true;
26250b57cec5SDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
26260b57cec5SDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
26270b57cec5SDimitry Andric         return false;
26280b57cec5SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
26290b57cec5SDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
26300b57cec5SDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
26310b57cec5SDimitry Andric         return true;
26320b57cec5SDimitry Andric       }
26330b57cec5SDimitry Andric       return false;
26340b57cec5SDimitry Andric     }
26350b57cec5SDimitry Andric 
26360b57cec5SDimitry Andric     bool VisitStmt(const Stmt *S) {
26370b57cec5SDimitry Andric       for (const Stmt *Child : S->children())
26380b57cec5SDimitry Andric         if (Child && this->Visit(Child))
26390b57cec5SDimitry Andric           return true;
26400b57cec5SDimitry Andric       return false;
26410b57cec5SDimitry Andric     }
26420b57cec5SDimitry Andric   };
26430b57cec5SDimitry Andric 
26440b57cec5SDimitry Andric   // Make sure we're not referencing non-imported vars or functions.
26450b57cec5SDimitry Andric   struct DLLImportFunctionVisitor
26460b57cec5SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
26470b57cec5SDimitry Andric     bool SafeToInline = true;
26480b57cec5SDimitry Andric 
26490b57cec5SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
26500b57cec5SDimitry Andric 
26510b57cec5SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
26520b57cec5SDimitry Andric       if (VD->getTLSKind()) {
26530b57cec5SDimitry Andric         // A thread-local variable cannot be imported.
26540b57cec5SDimitry Andric         SafeToInline = false;
26550b57cec5SDimitry Andric         return SafeToInline;
26560b57cec5SDimitry Andric       }
26570b57cec5SDimitry Andric 
26580b57cec5SDimitry Andric       // A variable definition might imply a destructor call.
26590b57cec5SDimitry Andric       if (VD->isThisDeclarationADefinition())
26600b57cec5SDimitry Andric         SafeToInline = !HasNonDllImportDtor(VD->getType());
26610b57cec5SDimitry Andric 
26620b57cec5SDimitry Andric       return SafeToInline;
26630b57cec5SDimitry Andric     }
26640b57cec5SDimitry Andric 
26650b57cec5SDimitry Andric     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
26660b57cec5SDimitry Andric       if (const auto *D = E->getTemporary()->getDestructor())
26670b57cec5SDimitry Andric         SafeToInline = D->hasAttr<DLLImportAttr>();
26680b57cec5SDimitry Andric       return SafeToInline;
26690b57cec5SDimitry Andric     }
26700b57cec5SDimitry Andric 
26710b57cec5SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
26720b57cec5SDimitry Andric       ValueDecl *VD = E->getDecl();
26730b57cec5SDimitry Andric       if (isa<FunctionDecl>(VD))
26740b57cec5SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
26750b57cec5SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
26760b57cec5SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
26770b57cec5SDimitry Andric       return SafeToInline;
26780b57cec5SDimitry Andric     }
26790b57cec5SDimitry Andric 
26800b57cec5SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
26810b57cec5SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
26820b57cec5SDimitry Andric       return SafeToInline;
26830b57cec5SDimitry Andric     }
26840b57cec5SDimitry Andric 
26850b57cec5SDimitry Andric     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
26860b57cec5SDimitry Andric       CXXMethodDecl *M = E->getMethodDecl();
26870b57cec5SDimitry Andric       if (!M) {
26880b57cec5SDimitry Andric         // Call through a pointer to member function. This is safe to inline.
26890b57cec5SDimitry Andric         SafeToInline = true;
26900b57cec5SDimitry Andric       } else {
26910b57cec5SDimitry Andric         SafeToInline = M->hasAttr<DLLImportAttr>();
26920b57cec5SDimitry Andric       }
26930b57cec5SDimitry Andric       return SafeToInline;
26940b57cec5SDimitry Andric     }
26950b57cec5SDimitry Andric 
26960b57cec5SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
26970b57cec5SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
26980b57cec5SDimitry Andric       return SafeToInline;
26990b57cec5SDimitry Andric     }
27000b57cec5SDimitry Andric 
27010b57cec5SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
27020b57cec5SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
27030b57cec5SDimitry Andric       return SafeToInline;
27040b57cec5SDimitry Andric     }
27050b57cec5SDimitry Andric   };
27060b57cec5SDimitry Andric }
27070b57cec5SDimitry Andric 
27080b57cec5SDimitry Andric // isTriviallyRecursive - Check if this function calls another
27090b57cec5SDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
27100b57cec5SDimitry Andric // ends up pointing to itself.
27110b57cec5SDimitry Andric bool
27120b57cec5SDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
27130b57cec5SDimitry Andric   StringRef Name;
27140b57cec5SDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
27150b57cec5SDimitry Andric     // asm labels are a special kind of mangling we have to support.
27160b57cec5SDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
27170b57cec5SDimitry Andric     if (!Attr)
27180b57cec5SDimitry Andric       return false;
27190b57cec5SDimitry Andric     Name = Attr->getLabel();
27200b57cec5SDimitry Andric   } else {
27210b57cec5SDimitry Andric     Name = FD->getName();
27220b57cec5SDimitry Andric   }
27230b57cec5SDimitry Andric 
27240b57cec5SDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
27250b57cec5SDimitry Andric   const Stmt *Body = FD->getBody();
27260b57cec5SDimitry Andric   return Body ? Walker.Visit(Body) : false;
27270b57cec5SDimitry Andric }
27280b57cec5SDimitry Andric 
27290b57cec5SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
27300b57cec5SDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
27310b57cec5SDimitry Andric     return true;
27320b57cec5SDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
27330b57cec5SDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
27340b57cec5SDimitry Andric     return false;
27350b57cec5SDimitry Andric 
27360b57cec5SDimitry Andric   if (F->hasAttr<DLLImportAttr>()) {
27370b57cec5SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
27380b57cec5SDimitry Andric     DLLImportFunctionVisitor Visitor;
27390b57cec5SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
27400b57cec5SDimitry Andric     if (!Visitor.SafeToInline)
27410b57cec5SDimitry Andric       return false;
27420b57cec5SDimitry Andric 
27430b57cec5SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
27440b57cec5SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
27450b57cec5SDimitry Andric       // check above can't see them. Check for them manually here.
27460b57cec5SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
27470b57cec5SDimitry Andric         if (isa<FieldDecl>(Member))
27480b57cec5SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
27490b57cec5SDimitry Andric             return false;
27500b57cec5SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
27510b57cec5SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
27520b57cec5SDimitry Andric           return false;
27530b57cec5SDimitry Andric     }
27540b57cec5SDimitry Andric   }
27550b57cec5SDimitry Andric 
27560b57cec5SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
27570b57cec5SDimitry Andric   // externally function should have an equivalent function somewhere else,
27580b57cec5SDimitry Andric   // but a function that calls itself is clearly not equivalent to the real
27590b57cec5SDimitry Andric   // implementation.
27600b57cec5SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
27610b57cec5SDimitry Andric   return !isTriviallyRecursive(F);
27620b57cec5SDimitry Andric }
27630b57cec5SDimitry Andric 
27640b57cec5SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
27650b57cec5SDimitry Andric   return CodeGenOpts.OptimizationLevel > 0;
27660b57cec5SDimitry Andric }
27670b57cec5SDimitry Andric 
27680b57cec5SDimitry Andric void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
27690b57cec5SDimitry Andric                                                        llvm::GlobalValue *GV) {
27700b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
27710b57cec5SDimitry Andric 
27720b57cec5SDimitry Andric   if (FD->isCPUSpecificMultiVersion()) {
27730b57cec5SDimitry Andric     auto *Spec = FD->getAttr<CPUSpecificAttr>();
27740b57cec5SDimitry Andric     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
27750b57cec5SDimitry Andric       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
27760b57cec5SDimitry Andric     // Requires multiple emits.
27770b57cec5SDimitry Andric   } else
27780b57cec5SDimitry Andric     EmitGlobalFunctionDefinition(GD, GV);
27790b57cec5SDimitry Andric }
27800b57cec5SDimitry Andric 
2781a7dea167SDimitry Andric void CodeGenModule::emitOpenMPDeviceFunctionRedefinition(
2782a7dea167SDimitry Andric     GlobalDecl OldGD, GlobalDecl NewGD, llvm::GlobalValue *GV) {
2783a7dea167SDimitry Andric   assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2784a7dea167SDimitry Andric          OpenMPRuntime && "Expected OpenMP device mode.");
2785a7dea167SDimitry Andric   const auto *D = cast<FunctionDecl>(OldGD.getDecl());
2786a7dea167SDimitry Andric 
2787a7dea167SDimitry Andric   // Compute the function info and LLVM type.
2788a7dea167SDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(OldGD);
2789a7dea167SDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2790a7dea167SDimitry Andric 
2791a7dea167SDimitry Andric   // Get or create the prototype for the function.
2792a7dea167SDimitry Andric   if (!GV || (GV->getType()->getElementType() != Ty)) {
2793a7dea167SDimitry Andric     GV = cast<llvm::GlobalValue>(GetOrCreateLLVMFunction(
2794a7dea167SDimitry Andric         getMangledName(OldGD), Ty, GlobalDecl(), /*ForVTable=*/false,
2795a7dea167SDimitry Andric         /*DontDefer=*/true, /*IsThunk=*/false, llvm::AttributeList(),
2796a7dea167SDimitry Andric         ForDefinition));
2797a7dea167SDimitry Andric     SetFunctionAttributes(OldGD, cast<llvm::Function>(GV),
2798a7dea167SDimitry Andric                           /*IsIncompleteFunction=*/false,
2799a7dea167SDimitry Andric                           /*IsThunk=*/false);
2800a7dea167SDimitry Andric   }
2801a7dea167SDimitry Andric   // We need to set linkage and visibility on the function before
2802a7dea167SDimitry Andric   // generating code for it because various parts of IR generation
2803a7dea167SDimitry Andric   // want to propagate this information down (e.g. to local static
2804a7dea167SDimitry Andric   // declarations).
2805a7dea167SDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
2806a7dea167SDimitry Andric   setFunctionLinkage(OldGD, Fn);
2807a7dea167SDimitry Andric 
2808a7dea167SDimitry Andric   // FIXME: this is redundant with part of
2809a7dea167SDimitry Andric   // setFunctionDefinitionAttributes
2810a7dea167SDimitry Andric   setGVProperties(Fn, OldGD);
2811a7dea167SDimitry Andric 
2812a7dea167SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
2813a7dea167SDimitry Andric 
2814a7dea167SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
2815a7dea167SDimitry Andric 
2816a7dea167SDimitry Andric   CodeGenFunction(*this).GenerateCode(NewGD, Fn, FI);
2817a7dea167SDimitry Andric 
2818a7dea167SDimitry Andric   setNonAliasAttributes(OldGD, Fn);
2819a7dea167SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, Fn);
2820a7dea167SDimitry Andric 
2821a7dea167SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
2822a7dea167SDimitry Andric     AddGlobalAnnotations(D, Fn);
2823a7dea167SDimitry Andric }
2824a7dea167SDimitry Andric 
28250b57cec5SDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
28260b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
28270b57cec5SDimitry Andric 
28280b57cec5SDimitry Andric   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
28290b57cec5SDimitry Andric                                  Context.getSourceManager(),
28300b57cec5SDimitry Andric                                  "Generating code for declaration");
28310b57cec5SDimitry Andric 
28320b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
28330b57cec5SDimitry Andric     // At -O0, don't generate IR for functions with available_externally
28340b57cec5SDimitry Andric     // linkage.
28350b57cec5SDimitry Andric     if (!shouldEmitFunction(GD))
28360b57cec5SDimitry Andric       return;
28370b57cec5SDimitry Andric 
28380b57cec5SDimitry Andric     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
28390b57cec5SDimitry Andric       std::string Name;
28400b57cec5SDimitry Andric       llvm::raw_string_ostream OS(Name);
28410b57cec5SDimitry Andric       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
28420b57cec5SDimitry Andric                                /*Qualified=*/true);
28430b57cec5SDimitry Andric       return Name;
28440b57cec5SDimitry Andric     });
28450b57cec5SDimitry Andric 
28460b57cec5SDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
28470b57cec5SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
28480b57cec5SDimitry Andric       // This is necessary for the generation of certain thunks.
28490b57cec5SDimitry Andric       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
28500b57cec5SDimitry Andric         ABI->emitCXXStructor(GD);
28510b57cec5SDimitry Andric       else if (FD->isMultiVersion())
28520b57cec5SDimitry Andric         EmitMultiVersionFunctionDefinition(GD, GV);
28530b57cec5SDimitry Andric       else
28540b57cec5SDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
28550b57cec5SDimitry Andric 
28560b57cec5SDimitry Andric       if (Method->isVirtual())
28570b57cec5SDimitry Andric         getVTables().EmitThunks(GD);
28580b57cec5SDimitry Andric 
28590b57cec5SDimitry Andric       return;
28600b57cec5SDimitry Andric     }
28610b57cec5SDimitry Andric 
28620b57cec5SDimitry Andric     if (FD->isMultiVersion())
28630b57cec5SDimitry Andric       return EmitMultiVersionFunctionDefinition(GD, GV);
28640b57cec5SDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
28650b57cec5SDimitry Andric   }
28660b57cec5SDimitry Andric 
28670b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
28680b57cec5SDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
28690b57cec5SDimitry Andric 
28700b57cec5SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
28710b57cec5SDimitry Andric }
28720b57cec5SDimitry Andric 
28730b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
28740b57cec5SDimitry Andric                                                       llvm::Function *NewFn);
28750b57cec5SDimitry Andric 
28760b57cec5SDimitry Andric static unsigned
28770b57cec5SDimitry Andric TargetMVPriority(const TargetInfo &TI,
28780b57cec5SDimitry Andric                  const CodeGenFunction::MultiVersionResolverOption &RO) {
28790b57cec5SDimitry Andric   unsigned Priority = 0;
28800b57cec5SDimitry Andric   for (StringRef Feat : RO.Conditions.Features)
28810b57cec5SDimitry Andric     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
28820b57cec5SDimitry Andric 
28830b57cec5SDimitry Andric   if (!RO.Conditions.Architecture.empty())
28840b57cec5SDimitry Andric     Priority = std::max(
28850b57cec5SDimitry Andric         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
28860b57cec5SDimitry Andric   return Priority;
28870b57cec5SDimitry Andric }
28880b57cec5SDimitry Andric 
28890b57cec5SDimitry Andric void CodeGenModule::emitMultiVersionFunctions() {
28900b57cec5SDimitry Andric   for (GlobalDecl GD : MultiVersionFuncs) {
28910b57cec5SDimitry Andric     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
28920b57cec5SDimitry Andric     const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
28930b57cec5SDimitry Andric     getContext().forEachMultiversionedFunctionVersion(
28940b57cec5SDimitry Andric         FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
28950b57cec5SDimitry Andric           GlobalDecl CurGD{
28960b57cec5SDimitry Andric               (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
28970b57cec5SDimitry Andric           StringRef MangledName = getMangledName(CurGD);
28980b57cec5SDimitry Andric           llvm::Constant *Func = GetGlobalValue(MangledName);
28990b57cec5SDimitry Andric           if (!Func) {
29000b57cec5SDimitry Andric             if (CurFD->isDefined()) {
29010b57cec5SDimitry Andric               EmitGlobalFunctionDefinition(CurGD, nullptr);
29020b57cec5SDimitry Andric               Func = GetGlobalValue(MangledName);
29030b57cec5SDimitry Andric             } else {
29040b57cec5SDimitry Andric               const CGFunctionInfo &FI =
29050b57cec5SDimitry Andric                   getTypes().arrangeGlobalDeclaration(GD);
29060b57cec5SDimitry Andric               llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
29070b57cec5SDimitry Andric               Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
29080b57cec5SDimitry Andric                                        /*DontDefer=*/false, ForDefinition);
29090b57cec5SDimitry Andric             }
29100b57cec5SDimitry Andric             assert(Func && "This should have just been created");
29110b57cec5SDimitry Andric           }
29120b57cec5SDimitry Andric 
29130b57cec5SDimitry Andric           const auto *TA = CurFD->getAttr<TargetAttr>();
29140b57cec5SDimitry Andric           llvm::SmallVector<StringRef, 8> Feats;
29150b57cec5SDimitry Andric           TA->getAddedFeatures(Feats);
29160b57cec5SDimitry Andric 
29170b57cec5SDimitry Andric           Options.emplace_back(cast<llvm::Function>(Func),
29180b57cec5SDimitry Andric                                TA->getArchitecture(), Feats);
29190b57cec5SDimitry Andric         });
29200b57cec5SDimitry Andric 
29210b57cec5SDimitry Andric     llvm::Function *ResolverFunc;
29220b57cec5SDimitry Andric     const TargetInfo &TI = getTarget();
29230b57cec5SDimitry Andric 
2924a7dea167SDimitry Andric     if (TI.supportsIFunc() || FD->isTargetMultiVersion()) {
29250b57cec5SDimitry Andric       ResolverFunc = cast<llvm::Function>(
29260b57cec5SDimitry Andric           GetGlobalValue((getMangledName(GD) + ".resolver").str()));
2927a7dea167SDimitry Andric       ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
2928a7dea167SDimitry Andric     } else {
29290b57cec5SDimitry Andric       ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
2930a7dea167SDimitry Andric     }
29310b57cec5SDimitry Andric 
29320b57cec5SDimitry Andric     if (supportsCOMDAT())
29330b57cec5SDimitry Andric       ResolverFunc->setComdat(
29340b57cec5SDimitry Andric           getModule().getOrInsertComdat(ResolverFunc->getName()));
29350b57cec5SDimitry Andric 
29360b57cec5SDimitry Andric     llvm::stable_sort(
29370b57cec5SDimitry Andric         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
29380b57cec5SDimitry Andric                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
29390b57cec5SDimitry Andric           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
29400b57cec5SDimitry Andric         });
29410b57cec5SDimitry Andric     CodeGenFunction CGF(*this);
29420b57cec5SDimitry Andric     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
29430b57cec5SDimitry Andric   }
29440b57cec5SDimitry Andric }
29450b57cec5SDimitry Andric 
29460b57cec5SDimitry Andric void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
29470b57cec5SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
29480b57cec5SDimitry Andric   assert(FD && "Not a FunctionDecl?");
29490b57cec5SDimitry Andric   const auto *DD = FD->getAttr<CPUDispatchAttr>();
29500b57cec5SDimitry Andric   assert(DD && "Not a cpu_dispatch Function?");
29510b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
29520b57cec5SDimitry Andric 
29530b57cec5SDimitry Andric   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
29540b57cec5SDimitry Andric     const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
29550b57cec5SDimitry Andric     DeclTy = getTypes().GetFunctionType(FInfo);
29560b57cec5SDimitry Andric   }
29570b57cec5SDimitry Andric 
29580b57cec5SDimitry Andric   StringRef ResolverName = getMangledName(GD);
29590b57cec5SDimitry Andric 
29600b57cec5SDimitry Andric   llvm::Type *ResolverType;
29610b57cec5SDimitry Andric   GlobalDecl ResolverGD;
29620b57cec5SDimitry Andric   if (getTarget().supportsIFunc())
29630b57cec5SDimitry Andric     ResolverType = llvm::FunctionType::get(
29640b57cec5SDimitry Andric         llvm::PointerType::get(DeclTy,
29650b57cec5SDimitry Andric                                Context.getTargetAddressSpace(FD->getType())),
29660b57cec5SDimitry Andric         false);
29670b57cec5SDimitry Andric   else {
29680b57cec5SDimitry Andric     ResolverType = DeclTy;
29690b57cec5SDimitry Andric     ResolverGD = GD;
29700b57cec5SDimitry Andric   }
29710b57cec5SDimitry Andric 
29720b57cec5SDimitry Andric   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
29730b57cec5SDimitry Andric       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
2974a7dea167SDimitry Andric   ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
2975a7dea167SDimitry Andric   if (supportsCOMDAT())
2976a7dea167SDimitry Andric     ResolverFunc->setComdat(
2977a7dea167SDimitry Andric         getModule().getOrInsertComdat(ResolverFunc->getName()));
29780b57cec5SDimitry Andric 
29790b57cec5SDimitry Andric   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
29800b57cec5SDimitry Andric   const TargetInfo &Target = getTarget();
29810b57cec5SDimitry Andric   unsigned Index = 0;
29820b57cec5SDimitry Andric   for (const IdentifierInfo *II : DD->cpus()) {
29830b57cec5SDimitry Andric     // Get the name of the target function so we can look it up/create it.
29840b57cec5SDimitry Andric     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
29850b57cec5SDimitry Andric                               getCPUSpecificMangling(*this, II->getName());
29860b57cec5SDimitry Andric 
29870b57cec5SDimitry Andric     llvm::Constant *Func = GetGlobalValue(MangledName);
29880b57cec5SDimitry Andric 
29890b57cec5SDimitry Andric     if (!Func) {
29900b57cec5SDimitry Andric       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
29910b57cec5SDimitry Andric       if (ExistingDecl.getDecl() &&
29920b57cec5SDimitry Andric           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
29930b57cec5SDimitry Andric         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
29940b57cec5SDimitry Andric         Func = GetGlobalValue(MangledName);
29950b57cec5SDimitry Andric       } else {
29960b57cec5SDimitry Andric         if (!ExistingDecl.getDecl())
29970b57cec5SDimitry Andric           ExistingDecl = GD.getWithMultiVersionIndex(Index);
29980b57cec5SDimitry Andric 
29990b57cec5SDimitry Andric       Func = GetOrCreateLLVMFunction(
30000b57cec5SDimitry Andric           MangledName, DeclTy, ExistingDecl,
30010b57cec5SDimitry Andric           /*ForVTable=*/false, /*DontDefer=*/true,
30020b57cec5SDimitry Andric           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
30030b57cec5SDimitry Andric       }
30040b57cec5SDimitry Andric     }
30050b57cec5SDimitry Andric 
30060b57cec5SDimitry Andric     llvm::SmallVector<StringRef, 32> Features;
30070b57cec5SDimitry Andric     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
30080b57cec5SDimitry Andric     llvm::transform(Features, Features.begin(),
30090b57cec5SDimitry Andric                     [](StringRef Str) { return Str.substr(1); });
30100b57cec5SDimitry Andric     Features.erase(std::remove_if(
30110b57cec5SDimitry Andric         Features.begin(), Features.end(), [&Target](StringRef Feat) {
30120b57cec5SDimitry Andric           return !Target.validateCpuSupports(Feat);
30130b57cec5SDimitry Andric         }), Features.end());
30140b57cec5SDimitry Andric     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
30150b57cec5SDimitry Andric     ++Index;
30160b57cec5SDimitry Andric   }
30170b57cec5SDimitry Andric 
30180b57cec5SDimitry Andric   llvm::sort(
30190b57cec5SDimitry Andric       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
30200b57cec5SDimitry Andric                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
30210b57cec5SDimitry Andric         return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
30220b57cec5SDimitry Andric                CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
30230b57cec5SDimitry Andric       });
30240b57cec5SDimitry Andric 
30250b57cec5SDimitry Andric   // If the list contains multiple 'default' versions, such as when it contains
30260b57cec5SDimitry Andric   // 'pentium' and 'generic', don't emit the call to the generic one (since we
30270b57cec5SDimitry Andric   // always run on at least a 'pentium'). We do this by deleting the 'least
30280b57cec5SDimitry Andric   // advanced' (read, lowest mangling letter).
30290b57cec5SDimitry Andric   while (Options.size() > 1 &&
30300b57cec5SDimitry Andric          CodeGenFunction::GetX86CpuSupportsMask(
30310b57cec5SDimitry Andric              (Options.end() - 2)->Conditions.Features) == 0) {
30320b57cec5SDimitry Andric     StringRef LHSName = (Options.end() - 2)->Function->getName();
30330b57cec5SDimitry Andric     StringRef RHSName = (Options.end() - 1)->Function->getName();
30340b57cec5SDimitry Andric     if (LHSName.compare(RHSName) < 0)
30350b57cec5SDimitry Andric       Options.erase(Options.end() - 2);
30360b57cec5SDimitry Andric     else
30370b57cec5SDimitry Andric       Options.erase(Options.end() - 1);
30380b57cec5SDimitry Andric   }
30390b57cec5SDimitry Andric 
30400b57cec5SDimitry Andric   CodeGenFunction CGF(*this);
30410b57cec5SDimitry Andric   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3042a7dea167SDimitry Andric 
3043a7dea167SDimitry Andric   if (getTarget().supportsIFunc()) {
3044a7dea167SDimitry Andric     std::string AliasName = getMangledNameImpl(
3045a7dea167SDimitry Andric         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3046a7dea167SDimitry Andric     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3047a7dea167SDimitry Andric     if (!AliasFunc) {
3048a7dea167SDimitry Andric       auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
3049a7dea167SDimitry Andric           AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
3050a7dea167SDimitry Andric           /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
3051a7dea167SDimitry Andric       auto *GA = llvm::GlobalAlias::create(
3052a7dea167SDimitry Andric          DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule());
3053a7dea167SDimitry Andric       GA->setLinkage(llvm::Function::WeakODRLinkage);
3054a7dea167SDimitry Andric       SetCommonAttributes(GD, GA);
3055a7dea167SDimitry Andric     }
3056a7dea167SDimitry Andric   }
30570b57cec5SDimitry Andric }
30580b57cec5SDimitry Andric 
30590b57cec5SDimitry Andric /// If a dispatcher for the specified mangled name is not in the module, create
30600b57cec5SDimitry Andric /// and return an llvm Function with the specified type.
30610b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
30620b57cec5SDimitry Andric     GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
30630b57cec5SDimitry Andric   std::string MangledName =
30640b57cec5SDimitry Andric       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
30650b57cec5SDimitry Andric 
30660b57cec5SDimitry Andric   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
30670b57cec5SDimitry Andric   // a separate resolver).
30680b57cec5SDimitry Andric   std::string ResolverName = MangledName;
30690b57cec5SDimitry Andric   if (getTarget().supportsIFunc())
30700b57cec5SDimitry Andric     ResolverName += ".ifunc";
30710b57cec5SDimitry Andric   else if (FD->isTargetMultiVersion())
30720b57cec5SDimitry Andric     ResolverName += ".resolver";
30730b57cec5SDimitry Andric 
30740b57cec5SDimitry Andric   // If this already exists, just return that one.
30750b57cec5SDimitry Andric   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
30760b57cec5SDimitry Andric     return ResolverGV;
30770b57cec5SDimitry Andric 
30780b57cec5SDimitry Andric   // Since this is the first time we've created this IFunc, make sure
30790b57cec5SDimitry Andric   // that we put this multiversioned function into the list to be
30800b57cec5SDimitry Andric   // replaced later if necessary (target multiversioning only).
30810b57cec5SDimitry Andric   if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
30820b57cec5SDimitry Andric     MultiVersionFuncs.push_back(GD);
30830b57cec5SDimitry Andric 
30840b57cec5SDimitry Andric   if (getTarget().supportsIFunc()) {
30850b57cec5SDimitry Andric     llvm::Type *ResolverType = llvm::FunctionType::get(
30860b57cec5SDimitry Andric         llvm::PointerType::get(
30870b57cec5SDimitry Andric             DeclTy, getContext().getTargetAddressSpace(FD->getType())),
30880b57cec5SDimitry Andric         false);
30890b57cec5SDimitry Andric     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
30900b57cec5SDimitry Andric         MangledName + ".resolver", ResolverType, GlobalDecl{},
30910b57cec5SDimitry Andric         /*ForVTable=*/false);
30920b57cec5SDimitry Andric     llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
3093a7dea167SDimitry Andric         DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule());
30940b57cec5SDimitry Andric     GIF->setName(ResolverName);
30950b57cec5SDimitry Andric     SetCommonAttributes(FD, GIF);
30960b57cec5SDimitry Andric 
30970b57cec5SDimitry Andric     return GIF;
30980b57cec5SDimitry Andric   }
30990b57cec5SDimitry Andric 
31000b57cec5SDimitry Andric   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
31010b57cec5SDimitry Andric       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
31020b57cec5SDimitry Andric   assert(isa<llvm::GlobalValue>(Resolver) &&
31030b57cec5SDimitry Andric          "Resolver should be created for the first time");
31040b57cec5SDimitry Andric   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
31050b57cec5SDimitry Andric   return Resolver;
31060b57cec5SDimitry Andric }
31070b57cec5SDimitry Andric 
31080b57cec5SDimitry Andric /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
31090b57cec5SDimitry Andric /// module, create and return an llvm Function with the specified type. If there
31100b57cec5SDimitry Andric /// is something in the module with the specified name, return it potentially
31110b57cec5SDimitry Andric /// bitcasted to the right type.
31120b57cec5SDimitry Andric ///
31130b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this.  This is used
31140b57cec5SDimitry Andric /// to set the attributes on the function when it is first created.
31150b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
31160b57cec5SDimitry Andric     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
31170b57cec5SDimitry Andric     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
31180b57cec5SDimitry Andric     ForDefinition_t IsForDefinition) {
31190b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
31200b57cec5SDimitry Andric 
31210b57cec5SDimitry Andric   // Any attempts to use a MultiVersion function should result in retrieving
31220b57cec5SDimitry Andric   // the iFunc instead. Name Mangling will handle the rest of the changes.
31230b57cec5SDimitry Andric   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
31240b57cec5SDimitry Andric     // For the device mark the function as one that should be emitted.
31250b57cec5SDimitry Andric     if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
31260b57cec5SDimitry Andric         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
31270b57cec5SDimitry Andric         !DontDefer && !IsForDefinition) {
31280b57cec5SDimitry Andric       if (const FunctionDecl *FDDef = FD->getDefinition()) {
31290b57cec5SDimitry Andric         GlobalDecl GDDef;
31300b57cec5SDimitry Andric         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
31310b57cec5SDimitry Andric           GDDef = GlobalDecl(CD, GD.getCtorType());
31320b57cec5SDimitry Andric         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
31330b57cec5SDimitry Andric           GDDef = GlobalDecl(DD, GD.getDtorType());
31340b57cec5SDimitry Andric         else
31350b57cec5SDimitry Andric           GDDef = GlobalDecl(FDDef);
31360b57cec5SDimitry Andric         EmitGlobal(GDDef);
31370b57cec5SDimitry Andric       }
31380b57cec5SDimitry Andric     }
3139a7dea167SDimitry Andric     // Check if this must be emitted as declare variant and emit reference to
3140a7dea167SDimitry Andric     // the the declare variant function.
3141a7dea167SDimitry Andric     if (LangOpts.OpenMP && OpenMPRuntime)
3142a7dea167SDimitry Andric       (void)OpenMPRuntime->emitDeclareVariant(GD, /*IsForDefinition=*/true);
31430b57cec5SDimitry Andric 
31440b57cec5SDimitry Andric     if (FD->isMultiVersion()) {
31450b57cec5SDimitry Andric       const auto *TA = FD->getAttr<TargetAttr>();
31460b57cec5SDimitry Andric       if (TA && TA->isDefaultVersion())
31470b57cec5SDimitry Andric         UpdateMultiVersionNames(GD, FD);
31480b57cec5SDimitry Andric       if (!IsForDefinition)
31490b57cec5SDimitry Andric         return GetOrCreateMultiVersionResolver(GD, Ty, FD);
31500b57cec5SDimitry Andric     }
31510b57cec5SDimitry Andric   }
31520b57cec5SDimitry Andric 
31530b57cec5SDimitry Andric   // Lookup the entry, lazily creating it if necessary.
31540b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
31550b57cec5SDimitry Andric   if (Entry) {
31560b57cec5SDimitry Andric     if (WeakRefReferences.erase(Entry)) {
31570b57cec5SDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
31580b57cec5SDimitry Andric       if (FD && !FD->hasAttr<WeakAttr>())
31590b57cec5SDimitry Andric         Entry->setLinkage(llvm::Function::ExternalLinkage);
31600b57cec5SDimitry Andric     }
31610b57cec5SDimitry Andric 
31620b57cec5SDimitry Andric     // Handle dropped DLL attributes.
31630b57cec5SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
31640b57cec5SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
31650b57cec5SDimitry Andric       setDSOLocal(Entry);
31660b57cec5SDimitry Andric     }
31670b57cec5SDimitry Andric 
31680b57cec5SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
31690b57cec5SDimitry Andric     // error.
31700b57cec5SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
31710b57cec5SDimitry Andric       GlobalDecl OtherGD;
31720b57cec5SDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
31730b57cec5SDimitry Andric       // to make sure that we issue an error only once.
31740b57cec5SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
31750b57cec5SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
31760b57cec5SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
31770b57cec5SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
31780b57cec5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
31790b57cec5SDimitry Andric             << MangledName;
31800b57cec5SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
31810b57cec5SDimitry Andric                           diag::note_previous_definition);
31820b57cec5SDimitry Andric       }
31830b57cec5SDimitry Andric     }
31840b57cec5SDimitry Andric 
31850b57cec5SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
31860b57cec5SDimitry Andric         (Entry->getType()->getElementType() == Ty)) {
31870b57cec5SDimitry Andric       return Entry;
31880b57cec5SDimitry Andric     }
31890b57cec5SDimitry Andric 
31900b57cec5SDimitry Andric     // Make sure the result is of the correct type.
31910b57cec5SDimitry Andric     // (If function is requested for a definition, we always need to create a new
31920b57cec5SDimitry Andric     // function, not just return a bitcast.)
31930b57cec5SDimitry Andric     if (!IsForDefinition)
31940b57cec5SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
31950b57cec5SDimitry Andric   }
31960b57cec5SDimitry Andric 
31970b57cec5SDimitry Andric   // This function doesn't have a complete type (for example, the return
31980b57cec5SDimitry Andric   // type is an incomplete struct). Use a fake type instead, and make
31990b57cec5SDimitry Andric   // sure not to try to set attributes.
32000b57cec5SDimitry Andric   bool IsIncompleteFunction = false;
32010b57cec5SDimitry Andric 
32020b57cec5SDimitry Andric   llvm::FunctionType *FTy;
32030b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(Ty)) {
32040b57cec5SDimitry Andric     FTy = cast<llvm::FunctionType>(Ty);
32050b57cec5SDimitry Andric   } else {
32060b57cec5SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
32070b57cec5SDimitry Andric     IsIncompleteFunction = true;
32080b57cec5SDimitry Andric   }
32090b57cec5SDimitry Andric 
32100b57cec5SDimitry Andric   llvm::Function *F =
32110b57cec5SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
32120b57cec5SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
32130b57cec5SDimitry Andric 
32140b57cec5SDimitry Andric   // If we already created a function with the same mangled name (but different
32150b57cec5SDimitry Andric   // type) before, take its name and add it to the list of functions to be
32160b57cec5SDimitry Andric   // replaced with F at the end of CodeGen.
32170b57cec5SDimitry Andric   //
32180b57cec5SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
32190b57cec5SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
32200b57cec5SDimitry Andric   if (Entry) {
32210b57cec5SDimitry Andric     F->takeName(Entry);
32220b57cec5SDimitry Andric 
32230b57cec5SDimitry Andric     // This might be an implementation of a function without a prototype, in
32240b57cec5SDimitry Andric     // which case, try to do special replacement of calls which match the new
32250b57cec5SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
32260b57cec5SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
32270b57cec5SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
32280b57cec5SDimitry Andric     // dropping arguments.
32290b57cec5SDimitry Andric     if (!Entry->use_empty()) {
32300b57cec5SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
32310b57cec5SDimitry Andric       Entry->removeDeadConstantUsers();
32320b57cec5SDimitry Andric     }
32330b57cec5SDimitry Andric 
32340b57cec5SDimitry Andric     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
32350b57cec5SDimitry Andric         F, Entry->getType()->getElementType()->getPointerTo());
32360b57cec5SDimitry Andric     addGlobalValReplacement(Entry, BC);
32370b57cec5SDimitry Andric   }
32380b57cec5SDimitry Andric 
32390b57cec5SDimitry Andric   assert(F->getName() == MangledName && "name was uniqued!");
32400b57cec5SDimitry Andric   if (D)
32410b57cec5SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
32420b57cec5SDimitry Andric   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
32430b57cec5SDimitry Andric     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
32440b57cec5SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
32450b57cec5SDimitry Andric   }
32460b57cec5SDimitry Andric 
32470b57cec5SDimitry Andric   if (!DontDefer) {
32480b57cec5SDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
32490b57cec5SDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
32500b57cec5SDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
32510b57cec5SDimitry Andric     if (D && isa<CXXDestructorDecl>(D) &&
32520b57cec5SDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
32530b57cec5SDimitry Andric                                            GD.getDtorType()))
32540b57cec5SDimitry Andric       addDeferredDeclToEmit(GD);
32550b57cec5SDimitry Andric 
32560b57cec5SDimitry Andric     // This is the first use or definition of a mangled name.  If there is a
32570b57cec5SDimitry Andric     // deferred decl with this name, remember that we need to emit it at the end
32580b57cec5SDimitry Andric     // of the file.
32590b57cec5SDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
32600b57cec5SDimitry Andric     if (DDI != DeferredDecls.end()) {
32610b57cec5SDimitry Andric       // Move the potentially referenced deferred decl to the
32620b57cec5SDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
32630b57cec5SDimitry Andric       // don't need it anymore).
32640b57cec5SDimitry Andric       addDeferredDeclToEmit(DDI->second);
32650b57cec5SDimitry Andric       DeferredDecls.erase(DDI);
32660b57cec5SDimitry Andric 
32670b57cec5SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
32680b57cec5SDimitry Andric       // using a declaration for which we must emit a definition but where
32690b57cec5SDimitry Andric       // we might not find a top-level definition:
32700b57cec5SDimitry Andric       //   - member functions defined inline in their classes
32710b57cec5SDimitry Andric       //   - friend functions defined inline in some class
32720b57cec5SDimitry Andric       //   - special member functions with implicit definitions
32730b57cec5SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
32740b57cec5SDimitry Andric       // this will be unnecessary.
32750b57cec5SDimitry Andric       //
32760b57cec5SDimitry Andric       // We also don't emit a definition for a function if it's going to be an
32770b57cec5SDimitry Andric       // entry in a vtable, unless it's already marked as used.
32780b57cec5SDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
32790b57cec5SDimitry Andric       // Look for a declaration that's lexically in a record.
32800b57cec5SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
32810b57cec5SDimitry Andric            FD = FD->getPreviousDecl()) {
32820b57cec5SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
32830b57cec5SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
32840b57cec5SDimitry Andric             addDeferredDeclToEmit(GD.getWithDecl(FD));
32850b57cec5SDimitry Andric             break;
32860b57cec5SDimitry Andric           }
32870b57cec5SDimitry Andric         }
32880b57cec5SDimitry Andric       }
32890b57cec5SDimitry Andric     }
32900b57cec5SDimitry Andric   }
32910b57cec5SDimitry Andric 
32920b57cec5SDimitry Andric   // Make sure the result is of the requested type.
32930b57cec5SDimitry Andric   if (!IsIncompleteFunction) {
32940b57cec5SDimitry Andric     assert(F->getType()->getElementType() == Ty);
32950b57cec5SDimitry Andric     return F;
32960b57cec5SDimitry Andric   }
32970b57cec5SDimitry Andric 
32980b57cec5SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
32990b57cec5SDimitry Andric   return llvm::ConstantExpr::getBitCast(F, PTy);
33000b57cec5SDimitry Andric }
33010b57cec5SDimitry Andric 
33020b57cec5SDimitry Andric /// GetAddrOfFunction - Return the address of the given function.  If Ty is
33030b57cec5SDimitry Andric /// non-null, then this function will use the specified type if it has to
33040b57cec5SDimitry Andric /// create it (this occurs when we see a definition of the function).
33050b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
33060b57cec5SDimitry Andric                                                  llvm::Type *Ty,
33070b57cec5SDimitry Andric                                                  bool ForVTable,
33080b57cec5SDimitry Andric                                                  bool DontDefer,
33090b57cec5SDimitry Andric                                               ForDefinition_t IsForDefinition) {
33100b57cec5SDimitry Andric   // If there was no specific requested type, just convert it now.
33110b57cec5SDimitry Andric   if (!Ty) {
33120b57cec5SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
33130b57cec5SDimitry Andric     Ty = getTypes().ConvertType(FD->getType());
33140b57cec5SDimitry Andric   }
33150b57cec5SDimitry Andric 
33160b57cec5SDimitry Andric   // Devirtualized destructor calls may come through here instead of via
33170b57cec5SDimitry Andric   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
33180b57cec5SDimitry Andric   // of the complete destructor when necessary.
33190b57cec5SDimitry Andric   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
33200b57cec5SDimitry Andric     if (getTarget().getCXXABI().isMicrosoft() &&
33210b57cec5SDimitry Andric         GD.getDtorType() == Dtor_Complete &&
33220b57cec5SDimitry Andric         DD->getParent()->getNumVBases() == 0)
33230b57cec5SDimitry Andric       GD = GlobalDecl(DD, Dtor_Base);
33240b57cec5SDimitry Andric   }
33250b57cec5SDimitry Andric 
33260b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
33270b57cec5SDimitry Andric   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
33280b57cec5SDimitry Andric                                  /*IsThunk=*/false, llvm::AttributeList(),
33290b57cec5SDimitry Andric                                  IsForDefinition);
33300b57cec5SDimitry Andric }
33310b57cec5SDimitry Andric 
33320b57cec5SDimitry Andric static const FunctionDecl *
33330b57cec5SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
33340b57cec5SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
33350b57cec5SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
33360b57cec5SDimitry Andric 
33370b57cec5SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
33380b57cec5SDimitry Andric   for (const auto &Result : DC->lookup(&CII))
33390b57cec5SDimitry Andric     if (const auto FD = dyn_cast<FunctionDecl>(Result))
33400b57cec5SDimitry Andric       return FD;
33410b57cec5SDimitry Andric 
33420b57cec5SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
33430b57cec5SDimitry Andric     return nullptr;
33440b57cec5SDimitry Andric 
33450b57cec5SDimitry Andric   // Demangle the premangled name from getTerminateFn()
33460b57cec5SDimitry Andric   IdentifierInfo &CXXII =
33470b57cec5SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
33480b57cec5SDimitry Andric           ? C.Idents.get("terminate")
33490b57cec5SDimitry Andric           : C.Idents.get(Name);
33500b57cec5SDimitry Andric 
33510b57cec5SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
33520b57cec5SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
33530b57cec5SDimitry Andric     for (const auto &Result : DC->lookup(&NS)) {
33540b57cec5SDimitry Andric       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
33550b57cec5SDimitry Andric       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
33560b57cec5SDimitry Andric         for (const auto &Result : LSD->lookup(&NS))
33570b57cec5SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
33580b57cec5SDimitry Andric             break;
33590b57cec5SDimitry Andric 
33600b57cec5SDimitry Andric       if (ND)
33610b57cec5SDimitry Andric         for (const auto &Result : ND->lookup(&CXXII))
33620b57cec5SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
33630b57cec5SDimitry Andric             return FD;
33640b57cec5SDimitry Andric     }
33650b57cec5SDimitry Andric   }
33660b57cec5SDimitry Andric 
33670b57cec5SDimitry Andric   return nullptr;
33680b57cec5SDimitry Andric }
33690b57cec5SDimitry Andric 
33700b57cec5SDimitry Andric /// CreateRuntimeFunction - Create a new runtime function with the specified
33710b57cec5SDimitry Andric /// type and name.
33720b57cec5SDimitry Andric llvm::FunctionCallee
33730b57cec5SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
3374480093f4SDimitry Andric                                      llvm::AttributeList ExtraAttrs, bool Local,
3375480093f4SDimitry Andric                                      bool AssumeConvergent) {
3376480093f4SDimitry Andric   if (AssumeConvergent) {
3377480093f4SDimitry Andric     ExtraAttrs =
3378480093f4SDimitry Andric         ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex,
3379480093f4SDimitry Andric                                 llvm::Attribute::Convergent);
3380480093f4SDimitry Andric   }
3381480093f4SDimitry Andric 
33820b57cec5SDimitry Andric   llvm::Constant *C =
33830b57cec5SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
33840b57cec5SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
33850b57cec5SDimitry Andric                               ExtraAttrs);
33860b57cec5SDimitry Andric 
33870b57cec5SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
33880b57cec5SDimitry Andric     if (F->empty()) {
33890b57cec5SDimitry Andric       F->setCallingConv(getRuntimeCC());
33900b57cec5SDimitry Andric 
33910b57cec5SDimitry Andric       // In Windows Itanium environments, try to mark runtime functions
33920b57cec5SDimitry Andric       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
33930b57cec5SDimitry Andric       // will link their standard library statically or dynamically. Marking
33940b57cec5SDimitry Andric       // functions imported when they are not imported can cause linker errors
33950b57cec5SDimitry Andric       // and warnings.
33960b57cec5SDimitry Andric       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
33970b57cec5SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd) {
33980b57cec5SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
33990b57cec5SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
34000b57cec5SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
34010b57cec5SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
34020b57cec5SDimitry Andric         }
34030b57cec5SDimitry Andric       }
34040b57cec5SDimitry Andric       setDSOLocal(F);
34050b57cec5SDimitry Andric     }
34060b57cec5SDimitry Andric   }
34070b57cec5SDimitry Andric 
34080b57cec5SDimitry Andric   return {FTy, C};
34090b57cec5SDimitry Andric }
34100b57cec5SDimitry Andric 
34110b57cec5SDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
34120b57cec5SDimitry Andric /// as a constant.
34130b57cec5SDimitry Andric ///
34140b57cec5SDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
34150b57cec5SDimitry Andric /// will not be considered. The caller will need to verify that the object is
34160b57cec5SDimitry Andric /// not written to during its construction.
34170b57cec5SDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
34180b57cec5SDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
34190b57cec5SDimitry Andric     return false;
34200b57cec5SDimitry Andric 
34210b57cec5SDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
34220b57cec5SDimitry Andric     if (const CXXRecordDecl *Record
34230b57cec5SDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
34240b57cec5SDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
34250b57cec5SDimitry Andric              Record->hasTrivialDestructor();
34260b57cec5SDimitry Andric   }
34270b57cec5SDimitry Andric 
34280b57cec5SDimitry Andric   return true;
34290b57cec5SDimitry Andric }
34300b57cec5SDimitry Andric 
34310b57cec5SDimitry Andric /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
34320b57cec5SDimitry Andric /// create and return an llvm GlobalVariable with the specified type.  If there
34330b57cec5SDimitry Andric /// is something in the module with the specified name, return it potentially
34340b57cec5SDimitry Andric /// bitcasted to the right type.
34350b57cec5SDimitry Andric ///
34360b57cec5SDimitry Andric /// If D is non-null, it specifies a decl that correspond to this.  This is used
34370b57cec5SDimitry Andric /// to set the attributes on the global when it is first created.
34380b57cec5SDimitry Andric ///
34390b57cec5SDimitry Andric /// If IsForDefinition is true, it is guaranteed that an actual global with
34400b57cec5SDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
34410b57cec5SDimitry Andric /// mangled name but some other type.
34420b57cec5SDimitry Andric llvm::Constant *
34430b57cec5SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
34440b57cec5SDimitry Andric                                      llvm::PointerType *Ty,
34450b57cec5SDimitry Andric                                      const VarDecl *D,
34460b57cec5SDimitry Andric                                      ForDefinition_t IsForDefinition) {
34470b57cec5SDimitry Andric   // Lookup the entry, lazily creating it if necessary.
34480b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
34490b57cec5SDimitry Andric   if (Entry) {
34500b57cec5SDimitry Andric     if (WeakRefReferences.erase(Entry)) {
34510b57cec5SDimitry Andric       if (D && !D->hasAttr<WeakAttr>())
34520b57cec5SDimitry Andric         Entry->setLinkage(llvm::Function::ExternalLinkage);
34530b57cec5SDimitry Andric     }
34540b57cec5SDimitry Andric 
34550b57cec5SDimitry Andric     // Handle dropped DLL attributes.
34560b57cec5SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
34570b57cec5SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
34580b57cec5SDimitry Andric 
34590b57cec5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
34600b57cec5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
34610b57cec5SDimitry Andric 
34620b57cec5SDimitry Andric     if (Entry->getType() == Ty)
34630b57cec5SDimitry Andric       return Entry;
34640b57cec5SDimitry Andric 
34650b57cec5SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
34660b57cec5SDimitry Andric     // error.
34670b57cec5SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
34680b57cec5SDimitry Andric       GlobalDecl OtherGD;
34690b57cec5SDimitry Andric       const VarDecl *OtherD;
34700b57cec5SDimitry Andric 
34710b57cec5SDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
34720b57cec5SDimitry Andric       // to make sure that we issue an error only once.
34730b57cec5SDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
34740b57cec5SDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
34750b57cec5SDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
34760b57cec5SDimitry Andric           OtherD->hasInit() &&
34770b57cec5SDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
34780b57cec5SDimitry Andric         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
34790b57cec5SDimitry Andric             << MangledName;
34800b57cec5SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
34810b57cec5SDimitry Andric                           diag::note_previous_definition);
34820b57cec5SDimitry Andric       }
34830b57cec5SDimitry Andric     }
34840b57cec5SDimitry Andric 
34850b57cec5SDimitry Andric     // Make sure the result is of the correct type.
34860b57cec5SDimitry Andric     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
34870b57cec5SDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
34880b57cec5SDimitry Andric 
34890b57cec5SDimitry Andric     // (If global is requested for a definition, we always need to create a new
34900b57cec5SDimitry Andric     // global, not just return a bitcast.)
34910b57cec5SDimitry Andric     if (!IsForDefinition)
34920b57cec5SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty);
34930b57cec5SDimitry Andric   }
34940b57cec5SDimitry Andric 
34950b57cec5SDimitry Andric   auto AddrSpace = GetGlobalVarAddressSpace(D);
34960b57cec5SDimitry Andric   auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
34970b57cec5SDimitry Andric 
34980b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
34990b57cec5SDimitry Andric       getModule(), Ty->getElementType(), false,
35000b57cec5SDimitry Andric       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
35010b57cec5SDimitry Andric       llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
35020b57cec5SDimitry Andric 
35030b57cec5SDimitry Andric   // If we already created a global with the same mangled name (but different
35040b57cec5SDimitry Andric   // type) before, take its name and remove it from its parent.
35050b57cec5SDimitry Andric   if (Entry) {
35060b57cec5SDimitry Andric     GV->takeName(Entry);
35070b57cec5SDimitry Andric 
35080b57cec5SDimitry Andric     if (!Entry->use_empty()) {
35090b57cec5SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
35100b57cec5SDimitry Andric           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
35110b57cec5SDimitry Andric       Entry->replaceAllUsesWith(NewPtrForOldDecl);
35120b57cec5SDimitry Andric     }
35130b57cec5SDimitry Andric 
35140b57cec5SDimitry Andric     Entry->eraseFromParent();
35150b57cec5SDimitry Andric   }
35160b57cec5SDimitry Andric 
35170b57cec5SDimitry Andric   // This is the first use or definition of a mangled name.  If there is a
35180b57cec5SDimitry Andric   // deferred decl with this name, remember that we need to emit it at the end
35190b57cec5SDimitry Andric   // of the file.
35200b57cec5SDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
35210b57cec5SDimitry Andric   if (DDI != DeferredDecls.end()) {
35220b57cec5SDimitry Andric     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
35230b57cec5SDimitry Andric     // list, and remove it from DeferredDecls (since we don't need it anymore).
35240b57cec5SDimitry Andric     addDeferredDeclToEmit(DDI->second);
35250b57cec5SDimitry Andric     DeferredDecls.erase(DDI);
35260b57cec5SDimitry Andric   }
35270b57cec5SDimitry Andric 
35280b57cec5SDimitry Andric   // Handle things which are present even on external declarations.
35290b57cec5SDimitry Andric   if (D) {
35300b57cec5SDimitry Andric     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
35310b57cec5SDimitry Andric       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
35320b57cec5SDimitry Andric 
35330b57cec5SDimitry Andric     // FIXME: This code is overly simple and should be merged with other global
35340b57cec5SDimitry Andric     // handling.
35350b57cec5SDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false));
35360b57cec5SDimitry Andric 
3537a7dea167SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
35380b57cec5SDimitry Andric 
35390b57cec5SDimitry Andric     setLinkageForGV(GV, D);
35400b57cec5SDimitry Andric 
35410b57cec5SDimitry Andric     if (D->getTLSKind()) {
35420b57cec5SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
35430b57cec5SDimitry Andric         CXXThreadLocals.push_back(D);
35440b57cec5SDimitry Andric       setTLSMode(GV, *D);
35450b57cec5SDimitry Andric     }
35460b57cec5SDimitry Andric 
35470b57cec5SDimitry Andric     setGVProperties(GV, D);
35480b57cec5SDimitry Andric 
35490b57cec5SDimitry Andric     // If required by the ABI, treat declarations of static data members with
35500b57cec5SDimitry Andric     // inline initializers as definitions.
35510b57cec5SDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
35520b57cec5SDimitry Andric       EmitGlobalVarDefinition(D);
35530b57cec5SDimitry Andric     }
35540b57cec5SDimitry Andric 
35550b57cec5SDimitry Andric     // Emit section information for extern variables.
35560b57cec5SDimitry Andric     if (D->hasExternalStorage()) {
35570b57cec5SDimitry Andric       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
35580b57cec5SDimitry Andric         GV->setSection(SA->getName());
35590b57cec5SDimitry Andric     }
35600b57cec5SDimitry Andric 
35610b57cec5SDimitry Andric     // Handle XCore specific ABI requirements.
35620b57cec5SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
35630b57cec5SDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
35640b57cec5SDimitry Andric         D->getType().isConstant(Context) &&
35650b57cec5SDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
35660b57cec5SDimitry Andric       GV->setSection(".cp.rodata");
35670b57cec5SDimitry Andric 
35680b57cec5SDimitry Andric     // Check if we a have a const declaration with an initializer, we may be
35690b57cec5SDimitry Andric     // able to emit it as available_externally to expose it's value to the
35700b57cec5SDimitry Andric     // optimizer.
35710b57cec5SDimitry Andric     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
35720b57cec5SDimitry Andric         D->getType().isConstQualified() && !GV->hasInitializer() &&
35730b57cec5SDimitry Andric         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
35740b57cec5SDimitry Andric       const auto *Record =
35750b57cec5SDimitry Andric           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
35760b57cec5SDimitry Andric       bool HasMutableFields = Record && Record->hasMutableFields();
35770b57cec5SDimitry Andric       if (!HasMutableFields) {
35780b57cec5SDimitry Andric         const VarDecl *InitDecl;
35790b57cec5SDimitry Andric         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
35800b57cec5SDimitry Andric         if (InitExpr) {
35810b57cec5SDimitry Andric           ConstantEmitter emitter(*this);
35820b57cec5SDimitry Andric           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
35830b57cec5SDimitry Andric           if (Init) {
35840b57cec5SDimitry Andric             auto *InitType = Init->getType();
35850b57cec5SDimitry Andric             if (GV->getType()->getElementType() != InitType) {
35860b57cec5SDimitry Andric               // The type of the initializer does not match the definition.
35870b57cec5SDimitry Andric               // This happens when an initializer has a different type from
35880b57cec5SDimitry Andric               // the type of the global (because of padding at the end of a
35890b57cec5SDimitry Andric               // structure for instance).
35900b57cec5SDimitry Andric               GV->setName(StringRef());
35910b57cec5SDimitry Andric               // Make a new global with the correct type, this is now guaranteed
35920b57cec5SDimitry Andric               // to work.
35930b57cec5SDimitry Andric               auto *NewGV = cast<llvm::GlobalVariable>(
3594a7dea167SDimitry Andric                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
3595a7dea167SDimitry Andric                       ->stripPointerCasts());
35960b57cec5SDimitry Andric 
35970b57cec5SDimitry Andric               // Erase the old global, since it is no longer used.
35980b57cec5SDimitry Andric               GV->eraseFromParent();
35990b57cec5SDimitry Andric               GV = NewGV;
36000b57cec5SDimitry Andric             } else {
36010b57cec5SDimitry Andric               GV->setInitializer(Init);
36020b57cec5SDimitry Andric               GV->setConstant(true);
36030b57cec5SDimitry Andric               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
36040b57cec5SDimitry Andric             }
36050b57cec5SDimitry Andric             emitter.finalize(GV);
36060b57cec5SDimitry Andric           }
36070b57cec5SDimitry Andric         }
36080b57cec5SDimitry Andric       }
36090b57cec5SDimitry Andric     }
36100b57cec5SDimitry Andric   }
36110b57cec5SDimitry Andric 
3612480093f4SDimitry Andric   if (GV->isDeclaration())
3613480093f4SDimitry Andric     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
3614480093f4SDimitry Andric 
36150b57cec5SDimitry Andric   LangAS ExpectedAS =
36160b57cec5SDimitry Andric       D ? D->getType().getAddressSpace()
36170b57cec5SDimitry Andric         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
36180b57cec5SDimitry Andric   assert(getContext().getTargetAddressSpace(ExpectedAS) ==
36190b57cec5SDimitry Andric          Ty->getPointerAddressSpace());
36200b57cec5SDimitry Andric   if (AddrSpace != ExpectedAS)
36210b57cec5SDimitry Andric     return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
36220b57cec5SDimitry Andric                                                        ExpectedAS, Ty);
36230b57cec5SDimitry Andric 
36240b57cec5SDimitry Andric   return GV;
36250b57cec5SDimitry Andric }
36260b57cec5SDimitry Andric 
36270b57cec5SDimitry Andric llvm::Constant *
36280b57cec5SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
36290b57cec5SDimitry Andric                                ForDefinition_t IsForDefinition) {
36300b57cec5SDimitry Andric   const Decl *D = GD.getDecl();
36310b57cec5SDimitry Andric   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
36320b57cec5SDimitry Andric     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
36330b57cec5SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
36340b57cec5SDimitry Andric   else if (isa<CXXMethodDecl>(D)) {
36350b57cec5SDimitry Andric     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
36360b57cec5SDimitry Andric         cast<CXXMethodDecl>(D));
36370b57cec5SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
36380b57cec5SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
36390b57cec5SDimitry Andric                              IsForDefinition);
36400b57cec5SDimitry Andric   } else if (isa<FunctionDecl>(D)) {
36410b57cec5SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
36420b57cec5SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
36430b57cec5SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
36440b57cec5SDimitry Andric                              IsForDefinition);
36450b57cec5SDimitry Andric   } else
36460b57cec5SDimitry Andric     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
36470b57cec5SDimitry Andric                               IsForDefinition);
36480b57cec5SDimitry Andric }
36490b57cec5SDimitry Andric 
36500b57cec5SDimitry Andric llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
36510b57cec5SDimitry Andric     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
36520b57cec5SDimitry Andric     unsigned Alignment) {
36530b57cec5SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
36540b57cec5SDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
36550b57cec5SDimitry Andric 
36560b57cec5SDimitry Andric   if (GV) {
36570b57cec5SDimitry Andric     // Check if the variable has the right type.
36580b57cec5SDimitry Andric     if (GV->getType()->getElementType() == Ty)
36590b57cec5SDimitry Andric       return GV;
36600b57cec5SDimitry Andric 
36610b57cec5SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
36620b57cec5SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
36630b57cec5SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
36640b57cec5SDimitry Andric     OldGV = GV;
36650b57cec5SDimitry Andric   }
36660b57cec5SDimitry Andric 
36670b57cec5SDimitry Andric   // Create a new variable.
36680b57cec5SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
36690b57cec5SDimitry Andric                                 Linkage, nullptr, Name);
36700b57cec5SDimitry Andric 
36710b57cec5SDimitry Andric   if (OldGV) {
36720b57cec5SDimitry Andric     // Replace occurrences of the old variable if needed.
36730b57cec5SDimitry Andric     GV->takeName(OldGV);
36740b57cec5SDimitry Andric 
36750b57cec5SDimitry Andric     if (!OldGV->use_empty()) {
36760b57cec5SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
36770b57cec5SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
36780b57cec5SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
36790b57cec5SDimitry Andric     }
36800b57cec5SDimitry Andric 
36810b57cec5SDimitry Andric     OldGV->eraseFromParent();
36820b57cec5SDimitry Andric   }
36830b57cec5SDimitry Andric 
36840b57cec5SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
36850b57cec5SDimitry Andric       !GV->hasAvailableExternallyLinkage())
36860b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
36870b57cec5SDimitry Andric 
3688a7dea167SDimitry Andric   GV->setAlignment(llvm::MaybeAlign(Alignment));
36890b57cec5SDimitry Andric 
36900b57cec5SDimitry Andric   return GV;
36910b57cec5SDimitry Andric }
36920b57cec5SDimitry Andric 
36930b57cec5SDimitry Andric /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
36940b57cec5SDimitry Andric /// given global variable.  If Ty is non-null and if the global doesn't exist,
36950b57cec5SDimitry Andric /// then it will be created with the specified type instead of whatever the
36960b57cec5SDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guaranteed
36970b57cec5SDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
36980b57cec5SDimitry Andric /// variable with the same mangled name but some other type.
36990b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
37000b57cec5SDimitry Andric                                                   llvm::Type *Ty,
37010b57cec5SDimitry Andric                                            ForDefinition_t IsForDefinition) {
37020b57cec5SDimitry Andric   assert(D->hasGlobalStorage() && "Not a global variable");
37030b57cec5SDimitry Andric   QualType ASTTy = D->getType();
37040b57cec5SDimitry Andric   if (!Ty)
37050b57cec5SDimitry Andric     Ty = getTypes().ConvertTypeForMem(ASTTy);
37060b57cec5SDimitry Andric 
37070b57cec5SDimitry Andric   llvm::PointerType *PTy =
37080b57cec5SDimitry Andric     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
37090b57cec5SDimitry Andric 
37100b57cec5SDimitry Andric   StringRef MangledName = getMangledName(D);
37110b57cec5SDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
37120b57cec5SDimitry Andric }
37130b57cec5SDimitry Andric 
37140b57cec5SDimitry Andric /// CreateRuntimeVariable - Create a new runtime global variable with the
37150b57cec5SDimitry Andric /// specified type and name.
37160b57cec5SDimitry Andric llvm::Constant *
37170b57cec5SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
37180b57cec5SDimitry Andric                                      StringRef Name) {
37190b57cec5SDimitry Andric   auto PtrTy =
37200b57cec5SDimitry Andric       getContext().getLangOpts().OpenCL
37210b57cec5SDimitry Andric           ? llvm::PointerType::get(
37220b57cec5SDimitry Andric                 Ty, getContext().getTargetAddressSpace(LangAS::opencl_global))
37230b57cec5SDimitry Andric           : llvm::PointerType::getUnqual(Ty);
37240b57cec5SDimitry Andric   auto *Ret = GetOrCreateLLVMGlobal(Name, PtrTy, nullptr);
37250b57cec5SDimitry Andric   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
37260b57cec5SDimitry Andric   return Ret;
37270b57cec5SDimitry Andric }
37280b57cec5SDimitry Andric 
37290b57cec5SDimitry Andric void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
37300b57cec5SDimitry Andric   assert(!D->getInit() && "Cannot emit definite definitions here!");
37310b57cec5SDimitry Andric 
37320b57cec5SDimitry Andric   StringRef MangledName = getMangledName(D);
37330b57cec5SDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
37340b57cec5SDimitry Andric 
37350b57cec5SDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
37360b57cec5SDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
37370b57cec5SDimitry Andric   // definition).
37380b57cec5SDimitry Andric   if (GV && !GV->isDeclaration())
37390b57cec5SDimitry Andric     return;
37400b57cec5SDimitry Andric 
37410b57cec5SDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
37420b57cec5SDimitry Andric   // deferred declarations table to be emitted if needed later.
37430b57cec5SDimitry Andric   if (!MustBeEmitted(D) && !GV) {
37440b57cec5SDimitry Andric       DeferredDecls[MangledName] = D;
37450b57cec5SDimitry Andric       return;
37460b57cec5SDimitry Andric   }
37470b57cec5SDimitry Andric 
37480b57cec5SDimitry Andric   // The tentative definition is the only definition.
37490b57cec5SDimitry Andric   EmitGlobalVarDefinition(D);
37500b57cec5SDimitry Andric }
37510b57cec5SDimitry Andric 
3752480093f4SDimitry Andric void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
3753480093f4SDimitry Andric   EmitExternalVarDeclaration(D);
3754480093f4SDimitry Andric }
3755480093f4SDimitry Andric 
37560b57cec5SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
37570b57cec5SDimitry Andric   return Context.toCharUnitsFromBits(
37580b57cec5SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
37590b57cec5SDimitry Andric }
37600b57cec5SDimitry Andric 
37610b57cec5SDimitry Andric LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
37620b57cec5SDimitry Andric   LangAS AddrSpace = LangAS::Default;
37630b57cec5SDimitry Andric   if (LangOpts.OpenCL) {
37640b57cec5SDimitry Andric     AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
37650b57cec5SDimitry Andric     assert(AddrSpace == LangAS::opencl_global ||
37660b57cec5SDimitry Andric            AddrSpace == LangAS::opencl_constant ||
37670b57cec5SDimitry Andric            AddrSpace == LangAS::opencl_local ||
37680b57cec5SDimitry Andric            AddrSpace >= LangAS::FirstTargetAddressSpace);
37690b57cec5SDimitry Andric     return AddrSpace;
37700b57cec5SDimitry Andric   }
37710b57cec5SDimitry Andric 
37720b57cec5SDimitry Andric   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
37730b57cec5SDimitry Andric     if (D && D->hasAttr<CUDAConstantAttr>())
37740b57cec5SDimitry Andric       return LangAS::cuda_constant;
37750b57cec5SDimitry Andric     else if (D && D->hasAttr<CUDASharedAttr>())
37760b57cec5SDimitry Andric       return LangAS::cuda_shared;
37770b57cec5SDimitry Andric     else if (D && D->hasAttr<CUDADeviceAttr>())
37780b57cec5SDimitry Andric       return LangAS::cuda_device;
37790b57cec5SDimitry Andric     else if (D && D->getType().isConstQualified())
37800b57cec5SDimitry Andric       return LangAS::cuda_constant;
37810b57cec5SDimitry Andric     else
37820b57cec5SDimitry Andric       return LangAS::cuda_device;
37830b57cec5SDimitry Andric   }
37840b57cec5SDimitry Andric 
37850b57cec5SDimitry Andric   if (LangOpts.OpenMP) {
37860b57cec5SDimitry Andric     LangAS AS;
37870b57cec5SDimitry Andric     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
37880b57cec5SDimitry Andric       return AS;
37890b57cec5SDimitry Andric   }
37900b57cec5SDimitry Andric   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
37910b57cec5SDimitry Andric }
37920b57cec5SDimitry Andric 
37930b57cec5SDimitry Andric LangAS CodeGenModule::getStringLiteralAddressSpace() const {
37940b57cec5SDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
37950b57cec5SDimitry Andric   if (LangOpts.OpenCL)
37960b57cec5SDimitry Andric     return LangAS::opencl_constant;
37970b57cec5SDimitry Andric   if (auto AS = getTarget().getConstantAddressSpace())
37980b57cec5SDimitry Andric     return AS.getValue();
37990b57cec5SDimitry Andric   return LangAS::Default;
38000b57cec5SDimitry Andric }
38010b57cec5SDimitry Andric 
38020b57cec5SDimitry Andric // In address space agnostic languages, string literals are in default address
38030b57cec5SDimitry Andric // space in AST. However, certain targets (e.g. amdgcn) request them to be
38040b57cec5SDimitry Andric // emitted in constant address space in LLVM IR. To be consistent with other
38050b57cec5SDimitry Andric // parts of AST, string literal global variables in constant address space
38060b57cec5SDimitry Andric // need to be casted to default address space before being put into address
38070b57cec5SDimitry Andric // map and referenced by other part of CodeGen.
38080b57cec5SDimitry Andric // In OpenCL, string literals are in constant address space in AST, therefore
38090b57cec5SDimitry Andric // they should not be casted to default address space.
38100b57cec5SDimitry Andric static llvm::Constant *
38110b57cec5SDimitry Andric castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
38120b57cec5SDimitry Andric                                        llvm::GlobalVariable *GV) {
38130b57cec5SDimitry Andric   llvm::Constant *Cast = GV;
38140b57cec5SDimitry Andric   if (!CGM.getLangOpts().OpenCL) {
38150b57cec5SDimitry Andric     if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
38160b57cec5SDimitry Andric       if (AS != LangAS::Default)
38170b57cec5SDimitry Andric         Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
38180b57cec5SDimitry Andric             CGM, GV, AS.getValue(), LangAS::Default,
38190b57cec5SDimitry Andric             GV->getValueType()->getPointerTo(
38200b57cec5SDimitry Andric                 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
38210b57cec5SDimitry Andric     }
38220b57cec5SDimitry Andric   }
38230b57cec5SDimitry Andric   return Cast;
38240b57cec5SDimitry Andric }
38250b57cec5SDimitry Andric 
38260b57cec5SDimitry Andric template<typename SomeDecl>
38270b57cec5SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
38280b57cec5SDimitry Andric                                                llvm::GlobalValue *GV) {
38290b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus)
38300b57cec5SDimitry Andric     return;
38310b57cec5SDimitry Andric 
38320b57cec5SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
38330b57cec5SDimitry Andric   // the name existing.
38340b57cec5SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
38350b57cec5SDimitry Andric     return;
38360b57cec5SDimitry Andric 
38370b57cec5SDimitry Andric   // Must have internal linkage and an ordinary name.
38380b57cec5SDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
38390b57cec5SDimitry Andric     return;
38400b57cec5SDimitry Andric 
38410b57cec5SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
38420b57cec5SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
38430b57cec5SDimitry Andric   const SomeDecl *First = D->getFirstDecl();
38440b57cec5SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
38450b57cec5SDimitry Andric     return;
38460b57cec5SDimitry Andric 
38470b57cec5SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
38480b57cec5SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
38490b57cec5SDimitry Andric   // mangled name if nothing else is using that name.
38500b57cec5SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
38510b57cec5SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
38520b57cec5SDimitry Andric 
38530b57cec5SDimitry Andric   // If we have multiple internal linkage entities with the same name
38540b57cec5SDimitry Andric   // in extern "C" regions, none of them gets that name.
38550b57cec5SDimitry Andric   if (!R.second)
38560b57cec5SDimitry Andric     R.first->second = nullptr;
38570b57cec5SDimitry Andric }
38580b57cec5SDimitry Andric 
38590b57cec5SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
38600b57cec5SDimitry Andric   if (!CGM.supportsCOMDAT())
38610b57cec5SDimitry Andric     return false;
38620b57cec5SDimitry Andric 
38630b57cec5SDimitry Andric   // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
38640b57cec5SDimitry Andric   // them being "merged" by the COMDAT Folding linker optimization.
38650b57cec5SDimitry Andric   if (D.hasAttr<CUDAGlobalAttr>())
38660b57cec5SDimitry Andric     return false;
38670b57cec5SDimitry Andric 
38680b57cec5SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
38690b57cec5SDimitry Andric     return true;
38700b57cec5SDimitry Andric 
38710b57cec5SDimitry Andric   GVALinkage Linkage;
38720b57cec5SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
38730b57cec5SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
38740b57cec5SDimitry Andric   else
38750b57cec5SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
38760b57cec5SDimitry Andric 
38770b57cec5SDimitry Andric   switch (Linkage) {
38780b57cec5SDimitry Andric   case GVA_Internal:
38790b57cec5SDimitry Andric   case GVA_AvailableExternally:
38800b57cec5SDimitry Andric   case GVA_StrongExternal:
38810b57cec5SDimitry Andric     return false;
38820b57cec5SDimitry Andric   case GVA_DiscardableODR:
38830b57cec5SDimitry Andric   case GVA_StrongODR:
38840b57cec5SDimitry Andric     return true;
38850b57cec5SDimitry Andric   }
38860b57cec5SDimitry Andric   llvm_unreachable("No such linkage");
38870b57cec5SDimitry Andric }
38880b57cec5SDimitry Andric 
38890b57cec5SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
38900b57cec5SDimitry Andric                                           llvm::GlobalObject &GO) {
38910b57cec5SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
38920b57cec5SDimitry Andric     return;
38930b57cec5SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
38940b57cec5SDimitry Andric }
38950b57cec5SDimitry Andric 
38960b57cec5SDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
38970b57cec5SDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
38980b57cec5SDimitry Andric                                             bool IsTentative) {
38990b57cec5SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
39000b57cec5SDimitry Andric   // therefore no need to be translated.
39010b57cec5SDimitry Andric   QualType ASTTy = D->getType();
39020b57cec5SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
39030b57cec5SDimitry Andric     return;
39040b57cec5SDimitry Andric 
39050b57cec5SDimitry Andric   // If this is OpenMP device, check if it is legal to emit this global
39060b57cec5SDimitry Andric   // normally.
39070b57cec5SDimitry Andric   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
39080b57cec5SDimitry Andric       OpenMPRuntime->emitTargetGlobalVariable(D))
39090b57cec5SDimitry Andric     return;
39100b57cec5SDimitry Andric 
39110b57cec5SDimitry Andric   llvm::Constant *Init = nullptr;
39120b57cec5SDimitry Andric   bool NeedsGlobalCtor = false;
3913a7dea167SDimitry Andric   bool NeedsGlobalDtor =
3914a7dea167SDimitry Andric       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
39150b57cec5SDimitry Andric 
39160b57cec5SDimitry Andric   const VarDecl *InitDecl;
39170b57cec5SDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
39180b57cec5SDimitry Andric 
39190b57cec5SDimitry Andric   Optional<ConstantEmitter> emitter;
39200b57cec5SDimitry Andric 
39210b57cec5SDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
39220b57cec5SDimitry Andric   // as part of their declaration."  Sema has already checked for
39230b57cec5SDimitry Andric   // error cases, so we just need to set Init to UndefValue.
39240b57cec5SDimitry Andric   bool IsCUDASharedVar =
39250b57cec5SDimitry Andric       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
39260b57cec5SDimitry Andric   // Shadows of initialized device-side global variables are also left
39270b57cec5SDimitry Andric   // undefined.
39280b57cec5SDimitry Andric   bool IsCUDAShadowVar =
39290b57cec5SDimitry Andric       !getLangOpts().CUDAIsDevice &&
39300b57cec5SDimitry Andric       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
39310b57cec5SDimitry Andric        D->hasAttr<CUDASharedAttr>());
39320b57cec5SDimitry Andric   // HIP pinned shadow of initialized host-side global variables are also
39330b57cec5SDimitry Andric   // left undefined.
39340b57cec5SDimitry Andric   bool IsHIPPinnedShadowVar =
39350b57cec5SDimitry Andric       getLangOpts().CUDAIsDevice && D->hasAttr<HIPPinnedShadowAttr>();
39360b57cec5SDimitry Andric   if (getLangOpts().CUDA &&
39370b57cec5SDimitry Andric       (IsCUDASharedVar || IsCUDAShadowVar || IsHIPPinnedShadowVar))
39380b57cec5SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
39390b57cec5SDimitry Andric   else if (!InitExpr) {
39400b57cec5SDimitry Andric     // This is a tentative definition; tentative definitions are
39410b57cec5SDimitry Andric     // implicitly initialized with { 0 }.
39420b57cec5SDimitry Andric     //
39430b57cec5SDimitry Andric     // Note that tentative definitions are only emitted at the end of
39440b57cec5SDimitry Andric     // a translation unit, so they should never have incomplete
39450b57cec5SDimitry Andric     // type. In addition, EmitTentativeDefinition makes sure that we
39460b57cec5SDimitry Andric     // never attempt to emit a tentative definition if a real one
39470b57cec5SDimitry Andric     // exists. A use may still exists, however, so we still may need
39480b57cec5SDimitry Andric     // to do a RAUW.
39490b57cec5SDimitry Andric     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
39500b57cec5SDimitry Andric     Init = EmitNullConstant(D->getType());
39510b57cec5SDimitry Andric   } else {
39520b57cec5SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
39530b57cec5SDimitry Andric     emitter.emplace(*this);
39540b57cec5SDimitry Andric     Init = emitter->tryEmitForInitializer(*InitDecl);
39550b57cec5SDimitry Andric 
39560b57cec5SDimitry Andric     if (!Init) {
39570b57cec5SDimitry Andric       QualType T = InitExpr->getType();
39580b57cec5SDimitry Andric       if (D->getType()->isReferenceType())
39590b57cec5SDimitry Andric         T = D->getType();
39600b57cec5SDimitry Andric 
39610b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus) {
39620b57cec5SDimitry Andric         Init = EmitNullConstant(T);
39630b57cec5SDimitry Andric         NeedsGlobalCtor = true;
39640b57cec5SDimitry Andric       } else {
39650b57cec5SDimitry Andric         ErrorUnsupported(D, "static initializer");
39660b57cec5SDimitry Andric         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
39670b57cec5SDimitry Andric       }
39680b57cec5SDimitry Andric     } else {
39690b57cec5SDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
39700b57cec5SDimitry Andric       // initializer position (just in case this entry was delayed) if we
39710b57cec5SDimitry Andric       // also don't need to register a destructor.
39720b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
39730b57cec5SDimitry Andric         DelayedCXXInitPosition.erase(D);
39740b57cec5SDimitry Andric     }
39750b57cec5SDimitry Andric   }
39760b57cec5SDimitry Andric 
39770b57cec5SDimitry Andric   llvm::Type* InitType = Init->getType();
39780b57cec5SDimitry Andric   llvm::Constant *Entry =
39790b57cec5SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
39800b57cec5SDimitry Andric 
3981a7dea167SDimitry Andric   // Strip off pointer casts if we got them.
3982a7dea167SDimitry Andric   Entry = Entry->stripPointerCasts();
39830b57cec5SDimitry Andric 
39840b57cec5SDimitry Andric   // Entry is now either a Function or GlobalVariable.
39850b57cec5SDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
39860b57cec5SDimitry Andric 
39870b57cec5SDimitry Andric   // We have a definition after a declaration with the wrong type.
39880b57cec5SDimitry Andric   // We must make a new GlobalVariable* and update everything that used OldGV
39890b57cec5SDimitry Andric   // (a declaration or tentative definition) with the new GlobalVariable*
39900b57cec5SDimitry Andric   // (which will be a definition).
39910b57cec5SDimitry Andric   //
39920b57cec5SDimitry Andric   // This happens if there is a prototype for a global (e.g.
39930b57cec5SDimitry Andric   // "extern int x[];") and then a definition of a different type (e.g.
39940b57cec5SDimitry Andric   // "int x[10];"). This also happens when an initializer has a different type
39950b57cec5SDimitry Andric   // from the type of the global (this happens with unions).
39960b57cec5SDimitry Andric   if (!GV || GV->getType()->getElementType() != InitType ||
39970b57cec5SDimitry Andric       GV->getType()->getAddressSpace() !=
39980b57cec5SDimitry Andric           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
39990b57cec5SDimitry Andric 
40000b57cec5SDimitry Andric     // Move the old entry aside so that we'll create a new one.
40010b57cec5SDimitry Andric     Entry->setName(StringRef());
40020b57cec5SDimitry Andric 
40030b57cec5SDimitry Andric     // Make a new global with the correct type, this is now guaranteed to work.
40040b57cec5SDimitry Andric     GV = cast<llvm::GlobalVariable>(
4005a7dea167SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
4006a7dea167SDimitry Andric             ->stripPointerCasts());
40070b57cec5SDimitry Andric 
40080b57cec5SDimitry Andric     // Replace all uses of the old global with the new global
40090b57cec5SDimitry Andric     llvm::Constant *NewPtrForOldDecl =
40100b57cec5SDimitry Andric         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
40110b57cec5SDimitry Andric     Entry->replaceAllUsesWith(NewPtrForOldDecl);
40120b57cec5SDimitry Andric 
40130b57cec5SDimitry Andric     // Erase the old global, since it is no longer used.
40140b57cec5SDimitry Andric     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
40150b57cec5SDimitry Andric   }
40160b57cec5SDimitry Andric 
40170b57cec5SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
40180b57cec5SDimitry Andric 
40190b57cec5SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
40200b57cec5SDimitry Andric     AddGlobalAnnotations(D, GV);
40210b57cec5SDimitry Andric 
40220b57cec5SDimitry Andric   // Set the llvm linkage type as appropriate.
40230b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
40240b57cec5SDimitry Andric       getLLVMLinkageVarDefinition(D, GV->isConstant());
40250b57cec5SDimitry Andric 
40260b57cec5SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
40270b57cec5SDimitry Andric   // the device. [...]"
40280b57cec5SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
40290b57cec5SDimitry Andric   // __device__, declares a variable that: [...]
40300b57cec5SDimitry Andric   // Is accessible from all the threads within the grid and from the host
40310b57cec5SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
40320b57cec5SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
40330b57cec5SDimitry Andric   if (GV && LangOpts.CUDA) {
40340b57cec5SDimitry Andric     if (LangOpts.CUDAIsDevice) {
40350b57cec5SDimitry Andric       if (Linkage != llvm::GlobalValue::InternalLinkage &&
40360b57cec5SDimitry Andric           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()))
40370b57cec5SDimitry Andric         GV->setExternallyInitialized(true);
40380b57cec5SDimitry Andric     } else {
40390b57cec5SDimitry Andric       // Host-side shadows of external declarations of device-side
40400b57cec5SDimitry Andric       // global variables become internal definitions. These have to
40410b57cec5SDimitry Andric       // be internal in order to prevent name conflicts with global
40420b57cec5SDimitry Andric       // host variables with the same name in a different TUs.
40430b57cec5SDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
40440b57cec5SDimitry Andric           D->hasAttr<HIPPinnedShadowAttr>()) {
40450b57cec5SDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
40460b57cec5SDimitry Andric 
40470b57cec5SDimitry Andric         // Shadow variables and their properties must be registered
40480b57cec5SDimitry Andric         // with CUDA runtime.
40490b57cec5SDimitry Andric         unsigned Flags = 0;
40500b57cec5SDimitry Andric         if (!D->hasDefinition())
40510b57cec5SDimitry Andric           Flags |= CGCUDARuntime::ExternDeviceVar;
40520b57cec5SDimitry Andric         if (D->hasAttr<CUDAConstantAttr>())
40530b57cec5SDimitry Andric           Flags |= CGCUDARuntime::ConstantDeviceVar;
40540b57cec5SDimitry Andric         // Extern global variables will be registered in the TU where they are
40550b57cec5SDimitry Andric         // defined.
40560b57cec5SDimitry Andric         if (!D->hasExternalStorage())
40570b57cec5SDimitry Andric           getCUDARuntime().registerDeviceVar(D, *GV, Flags);
40580b57cec5SDimitry Andric       } else if (D->hasAttr<CUDASharedAttr>())
40590b57cec5SDimitry Andric         // __shared__ variables are odd. Shadows do get created, but
40600b57cec5SDimitry Andric         // they are not registered with the CUDA runtime, so they
40610b57cec5SDimitry Andric         // can't really be used to access their device-side
40620b57cec5SDimitry Andric         // counterparts. It's not clear yet whether it's nvcc's bug or
40630b57cec5SDimitry Andric         // a feature, but we've got to do the same for compatibility.
40640b57cec5SDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
40650b57cec5SDimitry Andric     }
40660b57cec5SDimitry Andric   }
40670b57cec5SDimitry Andric 
40680b57cec5SDimitry Andric   if (!IsHIPPinnedShadowVar)
40690b57cec5SDimitry Andric     GV->setInitializer(Init);
40700b57cec5SDimitry Andric   if (emitter) emitter->finalize(GV);
40710b57cec5SDimitry Andric 
40720b57cec5SDimitry Andric   // If it is safe to mark the global 'constant', do so now.
40730b57cec5SDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
40740b57cec5SDimitry Andric                   isTypeConstant(D->getType(), true));
40750b57cec5SDimitry Andric 
40760b57cec5SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
40770b57cec5SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
40780b57cec5SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
40790b57cec5SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
40800b57cec5SDimitry Andric       GV->setConstant(true);
40810b57cec5SDimitry Andric   }
40820b57cec5SDimitry Andric 
4083a7dea167SDimitry Andric   GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
40840b57cec5SDimitry Andric 
40850b57cec5SDimitry Andric   // On Darwin, if the normal linkage of a C++ thread_local variable is
40860b57cec5SDimitry Andric   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
40870b57cec5SDimitry Andric   // copies within a linkage unit; otherwise, the backing variable has
40880b57cec5SDimitry Andric   // internal linkage and all accesses should just be calls to the
40890b57cec5SDimitry Andric   // Itanium-specified entry point, which has the normal linkage of the
40900b57cec5SDimitry Andric   // variable. This is to preserve the ability to change the implementation
40910b57cec5SDimitry Andric   // behind the scenes.
40920b57cec5SDimitry Andric   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
40930b57cec5SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
40940b57cec5SDimitry Andric       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
40950b57cec5SDimitry Andric       !llvm::GlobalVariable::isWeakLinkage(Linkage))
40960b57cec5SDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
40970b57cec5SDimitry Andric 
40980b57cec5SDimitry Andric   GV->setLinkage(Linkage);
40990b57cec5SDimitry Andric   if (D->hasAttr<DLLImportAttr>())
41000b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
41010b57cec5SDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
41020b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
41030b57cec5SDimitry Andric   else
41040b57cec5SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
41050b57cec5SDimitry Andric 
41060b57cec5SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
41070b57cec5SDimitry Andric     // common vars aren't constant even if declared const.
41080b57cec5SDimitry Andric     GV->setConstant(false);
41090b57cec5SDimitry Andric     // Tentative definition of global variables may be initialized with
41100b57cec5SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
41110b57cec5SDimitry Andric     // since common linkage must have zero initializer and must not have
41120b57cec5SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
41130b57cec5SDimitry Andric     if (!GV->getInitializer()->isNullValue())
41140b57cec5SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
41150b57cec5SDimitry Andric   }
41160b57cec5SDimitry Andric 
41170b57cec5SDimitry Andric   setNonAliasAttributes(D, GV);
41180b57cec5SDimitry Andric 
41190b57cec5SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
41200b57cec5SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
41210b57cec5SDimitry Andric       CXXThreadLocals.push_back(D);
41220b57cec5SDimitry Andric     setTLSMode(GV, *D);
41230b57cec5SDimitry Andric   }
41240b57cec5SDimitry Andric 
41250b57cec5SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
41260b57cec5SDimitry Andric 
41270b57cec5SDimitry Andric   // Emit the initializer function if necessary.
41280b57cec5SDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
41290b57cec5SDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
41300b57cec5SDimitry Andric 
41310b57cec5SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
41320b57cec5SDimitry Andric 
41330b57cec5SDimitry Andric   // Emit global variable debug information.
41340b57cec5SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
4135480093f4SDimitry Andric     if (getCodeGenOpts().hasReducedDebugInfo())
41360b57cec5SDimitry Andric       DI->EmitGlobalVariable(GV, D);
41370b57cec5SDimitry Andric }
41380b57cec5SDimitry Andric 
4139480093f4SDimitry Andric void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
4140480093f4SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
4141480093f4SDimitry Andric     if (getCodeGenOpts().hasReducedDebugInfo()) {
4142480093f4SDimitry Andric       QualType ASTTy = D->getType();
4143480093f4SDimitry Andric       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
4144480093f4SDimitry Andric       llvm::PointerType *PTy =
4145480093f4SDimitry Andric           llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
4146480093f4SDimitry Andric       llvm::Constant *GV = GetOrCreateLLVMGlobal(D->getName(), PTy, D);
4147480093f4SDimitry Andric       DI->EmitExternalVariable(
4148480093f4SDimitry Andric           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
4149480093f4SDimitry Andric     }
4150480093f4SDimitry Andric }
4151480093f4SDimitry Andric 
41520b57cec5SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
41530b57cec5SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
41540b57cec5SDimitry Andric                                       bool NoCommon) {
41550b57cec5SDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
41560b57cec5SDimitry Andric   // was overridden by a NoCommon attribute.
41570b57cec5SDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
41580b57cec5SDimitry Andric     return true;
41590b57cec5SDimitry Andric 
41600b57cec5SDimitry Andric   // C11 6.9.2/2:
41610b57cec5SDimitry Andric   //   A declaration of an identifier for an object that has file scope without
41620b57cec5SDimitry Andric   //   an initializer, and without a storage-class specifier or with the
41630b57cec5SDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
41640b57cec5SDimitry Andric   if (D->getInit() || D->hasExternalStorage())
41650b57cec5SDimitry Andric     return true;
41660b57cec5SDimitry Andric 
41670b57cec5SDimitry Andric   // A variable cannot be both common and exist in a section.
41680b57cec5SDimitry Andric   if (D->hasAttr<SectionAttr>())
41690b57cec5SDimitry Andric     return true;
41700b57cec5SDimitry Andric 
41710b57cec5SDimitry Andric   // A variable cannot be both common and exist in a section.
41720b57cec5SDimitry Andric   // We don't try to determine which is the right section in the front-end.
41730b57cec5SDimitry Andric   // If no specialized section name is applicable, it will resort to default.
41740b57cec5SDimitry Andric   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
41750b57cec5SDimitry Andric       D->hasAttr<PragmaClangDataSectionAttr>() ||
4176a7dea167SDimitry Andric       D->hasAttr<PragmaClangRelroSectionAttr>() ||
41770b57cec5SDimitry Andric       D->hasAttr<PragmaClangRodataSectionAttr>())
41780b57cec5SDimitry Andric     return true;
41790b57cec5SDimitry Andric 
41800b57cec5SDimitry Andric   // Thread local vars aren't considered common linkage.
41810b57cec5SDimitry Andric   if (D->getTLSKind())
41820b57cec5SDimitry Andric     return true;
41830b57cec5SDimitry Andric 
41840b57cec5SDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
41850b57cec5SDimitry Andric   if (D->hasAttr<WeakImportAttr>())
41860b57cec5SDimitry Andric     return true;
41870b57cec5SDimitry Andric 
41880b57cec5SDimitry Andric   // A variable cannot be both common and exist in a comdat.
41890b57cec5SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
41900b57cec5SDimitry Andric     return true;
41910b57cec5SDimitry Andric 
41920b57cec5SDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
41930b57cec5SDimitry Andric   // mode.
41940b57cec5SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
41950b57cec5SDimitry Andric     if (D->hasAttr<AlignedAttr>())
41960b57cec5SDimitry Andric       return true;
41970b57cec5SDimitry Andric     QualType VarType = D->getType();
41980b57cec5SDimitry Andric     if (Context.isAlignmentRequired(VarType))
41990b57cec5SDimitry Andric       return true;
42000b57cec5SDimitry Andric 
42010b57cec5SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
42020b57cec5SDimitry Andric       const RecordDecl *RD = RT->getDecl();
42030b57cec5SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
42040b57cec5SDimitry Andric         if (FD->isBitField())
42050b57cec5SDimitry Andric           continue;
42060b57cec5SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
42070b57cec5SDimitry Andric           return true;
42080b57cec5SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
42090b57cec5SDimitry Andric           return true;
42100b57cec5SDimitry Andric       }
42110b57cec5SDimitry Andric     }
42120b57cec5SDimitry Andric   }
42130b57cec5SDimitry Andric 
42140b57cec5SDimitry Andric   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
42150b57cec5SDimitry Andric   // common symbols, so symbols with greater alignment requirements cannot be
42160b57cec5SDimitry Andric   // common.
42170b57cec5SDimitry Andric   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
42180b57cec5SDimitry Andric   // alignments for common symbols via the aligncomm directive, so this
42190b57cec5SDimitry Andric   // restriction only applies to MSVC environments.
42200b57cec5SDimitry Andric   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
42210b57cec5SDimitry Andric       Context.getTypeAlignIfKnown(D->getType()) >
42220b57cec5SDimitry Andric           Context.toBits(CharUnits::fromQuantity(32)))
42230b57cec5SDimitry Andric     return true;
42240b57cec5SDimitry Andric 
42250b57cec5SDimitry Andric   return false;
42260b57cec5SDimitry Andric }
42270b57cec5SDimitry Andric 
42280b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
42290b57cec5SDimitry Andric     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
42300b57cec5SDimitry Andric   if (Linkage == GVA_Internal)
42310b57cec5SDimitry Andric     return llvm::Function::InternalLinkage;
42320b57cec5SDimitry Andric 
42330b57cec5SDimitry Andric   if (D->hasAttr<WeakAttr>()) {
42340b57cec5SDimitry Andric     if (IsConstantVariable)
42350b57cec5SDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
42360b57cec5SDimitry Andric     else
42370b57cec5SDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
42380b57cec5SDimitry Andric   }
42390b57cec5SDimitry Andric 
42400b57cec5SDimitry Andric   if (const auto *FD = D->getAsFunction())
42410b57cec5SDimitry Andric     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
42420b57cec5SDimitry Andric       return llvm::GlobalVariable::LinkOnceAnyLinkage;
42430b57cec5SDimitry Andric 
42440b57cec5SDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
42450b57cec5SDimitry Andric   // so we can use available_externally linkage.
42460b57cec5SDimitry Andric   if (Linkage == GVA_AvailableExternally)
42470b57cec5SDimitry Andric     return llvm::GlobalValue::AvailableExternallyLinkage;
42480b57cec5SDimitry Andric 
42490b57cec5SDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
42500b57cec5SDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
42510b57cec5SDimitry Andric   // Normally, this means we just map to internal, but for explicit
42520b57cec5SDimitry Andric   // instantiations we'll map to external.
42530b57cec5SDimitry Andric 
42540b57cec5SDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
42550b57cec5SDimitry Andric   // that references the function.  We should use linkonce_odr because
42560b57cec5SDimitry Andric   // a) if all references in this translation unit are optimized away, we
42570b57cec5SDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
42580b57cec5SDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
42590b57cec5SDimitry Andric   // definition is dependable.
42600b57cec5SDimitry Andric   if (Linkage == GVA_DiscardableODR)
42610b57cec5SDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
42620b57cec5SDimitry Andric                                             : llvm::Function::InternalLinkage;
42630b57cec5SDimitry Andric 
42640b57cec5SDimitry Andric   // An explicit instantiation of a template has weak linkage, since
42650b57cec5SDimitry Andric   // explicit instantiations can occur in multiple translation units
42660b57cec5SDimitry Andric   // and must all be equivalent. However, we are not allowed to
42670b57cec5SDimitry Andric   // throw away these explicit instantiations.
42680b57cec5SDimitry Andric   //
42690b57cec5SDimitry Andric   // We don't currently support CUDA device code spread out across multiple TUs,
42700b57cec5SDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
42710b57cec5SDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations.
42720b57cec5SDimitry Andric   if (Linkage == GVA_StrongODR) {
42730b57cec5SDimitry Andric     if (Context.getLangOpts().AppleKext)
42740b57cec5SDimitry Andric       return llvm::Function::ExternalLinkage;
42750b57cec5SDimitry Andric     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
42760b57cec5SDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
42770b57cec5SDimitry Andric                                           : llvm::Function::InternalLinkage;
42780b57cec5SDimitry Andric     return llvm::Function::WeakODRLinkage;
42790b57cec5SDimitry Andric   }
42800b57cec5SDimitry Andric 
42810b57cec5SDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
42820b57cec5SDimitry Andric   // linkage.
42830b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
42840b57cec5SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
42850b57cec5SDimitry Andric                                  CodeGenOpts.NoCommon))
42860b57cec5SDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
42870b57cec5SDimitry Andric 
42880b57cec5SDimitry Andric   // selectany symbols are externally visible, so use weak instead of
42890b57cec5SDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
42900b57cec5SDimitry Andric   // all definitions should be the same and ODR linkage should be used.
42910b57cec5SDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
42920b57cec5SDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
42930b57cec5SDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
42940b57cec5SDimitry Andric 
42950b57cec5SDimitry Andric   // Otherwise, we have strong external linkage.
42960b57cec5SDimitry Andric   assert(Linkage == GVA_StrongExternal);
42970b57cec5SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
42980b57cec5SDimitry Andric }
42990b57cec5SDimitry Andric 
43000b57cec5SDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
43010b57cec5SDimitry Andric     const VarDecl *VD, bool IsConstant) {
43020b57cec5SDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
43030b57cec5SDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
43040b57cec5SDimitry Andric }
43050b57cec5SDimitry Andric 
43060b57cec5SDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
43070b57cec5SDimitry Andric /// We want to silently drop extra arguments from call sites
43080b57cec5SDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
43090b57cec5SDimitry Andric                                           llvm::Function *newFn) {
43100b57cec5SDimitry Andric   // Fast path.
43110b57cec5SDimitry Andric   if (old->use_empty()) return;
43120b57cec5SDimitry Andric 
43130b57cec5SDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
43140b57cec5SDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
43150b57cec5SDimitry Andric   SmallVector<llvm::OperandBundleDef, 1> newBundles;
43160b57cec5SDimitry Andric 
43170b57cec5SDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
43180b57cec5SDimitry Andric          ui != ue; ) {
43190b57cec5SDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
43200b57cec5SDimitry Andric     llvm::User *user = use->getUser();
43210b57cec5SDimitry Andric 
43220b57cec5SDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
43230b57cec5SDimitry Andric     // unprototyped functions will use bitcasts.
43240b57cec5SDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
43250b57cec5SDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
43260b57cec5SDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
43270b57cec5SDimitry Andric       continue;
43280b57cec5SDimitry Andric     }
43290b57cec5SDimitry Andric 
43300b57cec5SDimitry Andric     // Recognize calls to the function.
43310b57cec5SDimitry Andric     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
43320b57cec5SDimitry Andric     if (!callSite) continue;
43330b57cec5SDimitry Andric     if (!callSite->isCallee(&*use))
43340b57cec5SDimitry Andric       continue;
43350b57cec5SDimitry Andric 
43360b57cec5SDimitry Andric     // If the return types don't match exactly, then we can't
43370b57cec5SDimitry Andric     // transform this call unless it's dead.
43380b57cec5SDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
43390b57cec5SDimitry Andric       continue;
43400b57cec5SDimitry Andric 
43410b57cec5SDimitry Andric     // Get the call site's attribute list.
43420b57cec5SDimitry Andric     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
43430b57cec5SDimitry Andric     llvm::AttributeList oldAttrs = callSite->getAttributes();
43440b57cec5SDimitry Andric 
43450b57cec5SDimitry Andric     // If the function was passed too few arguments, don't transform.
43460b57cec5SDimitry Andric     unsigned newNumArgs = newFn->arg_size();
43470b57cec5SDimitry Andric     if (callSite->arg_size() < newNumArgs)
43480b57cec5SDimitry Andric       continue;
43490b57cec5SDimitry Andric 
43500b57cec5SDimitry Andric     // If extra arguments were passed, we silently drop them.
43510b57cec5SDimitry Andric     // If any of the types mismatch, we don't transform.
43520b57cec5SDimitry Andric     unsigned argNo = 0;
43530b57cec5SDimitry Andric     bool dontTransform = false;
43540b57cec5SDimitry Andric     for (llvm::Argument &A : newFn->args()) {
43550b57cec5SDimitry Andric       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
43560b57cec5SDimitry Andric         dontTransform = true;
43570b57cec5SDimitry Andric         break;
43580b57cec5SDimitry Andric       }
43590b57cec5SDimitry Andric 
43600b57cec5SDimitry Andric       // Add any parameter attributes.
43610b57cec5SDimitry Andric       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
43620b57cec5SDimitry Andric       argNo++;
43630b57cec5SDimitry Andric     }
43640b57cec5SDimitry Andric     if (dontTransform)
43650b57cec5SDimitry Andric       continue;
43660b57cec5SDimitry Andric 
43670b57cec5SDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
43680b57cec5SDimitry Andric     // over the required information.
43690b57cec5SDimitry Andric     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
43700b57cec5SDimitry Andric 
43710b57cec5SDimitry Andric     // Copy over any operand bundles.
43720b57cec5SDimitry Andric     callSite->getOperandBundlesAsDefs(newBundles);
43730b57cec5SDimitry Andric 
43740b57cec5SDimitry Andric     llvm::CallBase *newCall;
43750b57cec5SDimitry Andric     if (dyn_cast<llvm::CallInst>(callSite)) {
43760b57cec5SDimitry Andric       newCall =
43770b57cec5SDimitry Andric           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
43780b57cec5SDimitry Andric     } else {
43790b57cec5SDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
43800b57cec5SDimitry Andric       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
43810b57cec5SDimitry Andric                                          oldInvoke->getUnwindDest(), newArgs,
43820b57cec5SDimitry Andric                                          newBundles, "", callSite);
43830b57cec5SDimitry Andric     }
43840b57cec5SDimitry Andric     newArgs.clear(); // for the next iteration
43850b57cec5SDimitry Andric 
43860b57cec5SDimitry Andric     if (!newCall->getType()->isVoidTy())
43870b57cec5SDimitry Andric       newCall->takeName(callSite);
43880b57cec5SDimitry Andric     newCall->setAttributes(llvm::AttributeList::get(
43890b57cec5SDimitry Andric         newFn->getContext(), oldAttrs.getFnAttributes(),
43900b57cec5SDimitry Andric         oldAttrs.getRetAttributes(), newArgAttrs));
43910b57cec5SDimitry Andric     newCall->setCallingConv(callSite->getCallingConv());
43920b57cec5SDimitry Andric 
43930b57cec5SDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
43940b57cec5SDimitry Andric     if (!callSite->use_empty())
43950b57cec5SDimitry Andric       callSite->replaceAllUsesWith(newCall);
43960b57cec5SDimitry Andric 
43970b57cec5SDimitry Andric     // Copy debug location attached to CI.
43980b57cec5SDimitry Andric     if (callSite->getDebugLoc())
43990b57cec5SDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
44000b57cec5SDimitry Andric 
44010b57cec5SDimitry Andric     callSite->eraseFromParent();
44020b57cec5SDimitry Andric   }
44030b57cec5SDimitry Andric }
44040b57cec5SDimitry Andric 
44050b57cec5SDimitry Andric /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
44060b57cec5SDimitry Andric /// implement a function with no prototype, e.g. "int foo() {}".  If there are
44070b57cec5SDimitry Andric /// existing call uses of the old function in the module, this adjusts them to
44080b57cec5SDimitry Andric /// call the new function directly.
44090b57cec5SDimitry Andric ///
44100b57cec5SDimitry Andric /// This is not just a cleanup: the always_inline pass requires direct calls to
44110b57cec5SDimitry Andric /// functions to be able to inline them.  If there is a bitcast in the way, it
44120b57cec5SDimitry Andric /// won't inline them.  Instcombine normally deletes these calls, but it isn't
44130b57cec5SDimitry Andric /// run at -O0.
44140b57cec5SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
44150b57cec5SDimitry Andric                                                       llvm::Function *NewFn) {
44160b57cec5SDimitry Andric   // If we're redefining a global as a function, don't transform it.
44170b57cec5SDimitry Andric   if (!isa<llvm::Function>(Old)) return;
44180b57cec5SDimitry Andric 
44190b57cec5SDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
44200b57cec5SDimitry Andric }
44210b57cec5SDimitry Andric 
44220b57cec5SDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
44230b57cec5SDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
44240b57cec5SDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
44250b57cec5SDimitry Andric     return;
44260b57cec5SDimitry Andric 
44270b57cec5SDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
44280b57cec5SDimitry Andric   // If we have a definition, this might be a deferred decl. If the
44290b57cec5SDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
44300b57cec5SDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
44310b57cec5SDimitry Andric     GetAddrOfGlobalVar(VD);
44320b57cec5SDimitry Andric 
44330b57cec5SDimitry Andric   EmitTopLevelDecl(VD);
44340b57cec5SDimitry Andric }
44350b57cec5SDimitry Andric 
44360b57cec5SDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
44370b57cec5SDimitry Andric                                                  llvm::GlobalValue *GV) {
4438a7dea167SDimitry Andric   // Check if this must be emitted as declare variant.
4439a7dea167SDimitry Andric   if (LangOpts.OpenMP && OpenMPRuntime &&
4440a7dea167SDimitry Andric       OpenMPRuntime->emitDeclareVariant(GD, /*IsForDefinition=*/true))
4441a7dea167SDimitry Andric     return;
4442a7dea167SDimitry Andric 
44430b57cec5SDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
44440b57cec5SDimitry Andric 
44450b57cec5SDimitry Andric   // Compute the function info and LLVM type.
44460b57cec5SDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
44470b57cec5SDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
44480b57cec5SDimitry Andric 
44490b57cec5SDimitry Andric   // Get or create the prototype for the function.
44500b57cec5SDimitry Andric   if (!GV || (GV->getType()->getElementType() != Ty))
44510b57cec5SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
44520b57cec5SDimitry Andric                                                    /*DontDefer=*/true,
44530b57cec5SDimitry Andric                                                    ForDefinition));
44540b57cec5SDimitry Andric 
44550b57cec5SDimitry Andric   // Already emitted.
44560b57cec5SDimitry Andric   if (!GV->isDeclaration())
44570b57cec5SDimitry Andric     return;
44580b57cec5SDimitry Andric 
44590b57cec5SDimitry Andric   // We need to set linkage and visibility on the function before
44600b57cec5SDimitry Andric   // generating code for it because various parts of IR generation
44610b57cec5SDimitry Andric   // want to propagate this information down (e.g. to local static
44620b57cec5SDimitry Andric   // declarations).
44630b57cec5SDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
44640b57cec5SDimitry Andric   setFunctionLinkage(GD, Fn);
44650b57cec5SDimitry Andric 
44660b57cec5SDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
44670b57cec5SDimitry Andric   setGVProperties(Fn, GD);
44680b57cec5SDimitry Andric 
44690b57cec5SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
44700b57cec5SDimitry Andric 
44710b57cec5SDimitry Andric 
44720b57cec5SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
44730b57cec5SDimitry Andric 
44740b57cec5SDimitry Andric   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
44750b57cec5SDimitry Andric 
44760b57cec5SDimitry Andric   setNonAliasAttributes(GD, Fn);
44770b57cec5SDimitry Andric   SetLLVMFunctionAttributesForDefinition(D, Fn);
44780b57cec5SDimitry Andric 
44790b57cec5SDimitry Andric   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
44800b57cec5SDimitry Andric     AddGlobalCtor(Fn, CA->getPriority());
44810b57cec5SDimitry Andric   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
44820b57cec5SDimitry Andric     AddGlobalDtor(Fn, DA->getPriority());
44830b57cec5SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
44840b57cec5SDimitry Andric     AddGlobalAnnotations(D, Fn);
44850b57cec5SDimitry Andric }
44860b57cec5SDimitry Andric 
44870b57cec5SDimitry Andric void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
44880b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
44890b57cec5SDimitry Andric   const AliasAttr *AA = D->getAttr<AliasAttr>();
44900b57cec5SDimitry Andric   assert(AA && "Not an alias?");
44910b57cec5SDimitry Andric 
44920b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
44930b57cec5SDimitry Andric 
44940b57cec5SDimitry Andric   if (AA->getAliasee() == MangledName) {
44950b57cec5SDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
44960b57cec5SDimitry Andric     return;
44970b57cec5SDimitry Andric   }
44980b57cec5SDimitry Andric 
44990b57cec5SDimitry Andric   // If there is a definition in the module, then it wins over the alias.
45000b57cec5SDimitry Andric   // This is dubious, but allow it to be safe.  Just ignore the alias.
45010b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
45020b57cec5SDimitry Andric   if (Entry && !Entry->isDeclaration())
45030b57cec5SDimitry Andric     return;
45040b57cec5SDimitry Andric 
45050b57cec5SDimitry Andric   Aliases.push_back(GD);
45060b57cec5SDimitry Andric 
45070b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
45080b57cec5SDimitry Andric 
45090b57cec5SDimitry Andric   // Create a reference to the named value.  This ensures that it is emitted
45100b57cec5SDimitry Andric   // if a deferred decl.
45110b57cec5SDimitry Andric   llvm::Constant *Aliasee;
45120b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
45130b57cec5SDimitry Andric   if (isa<llvm::FunctionType>(DeclTy)) {
45140b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
45150b57cec5SDimitry Andric                                       /*ForVTable=*/false);
45160b57cec5SDimitry Andric     LT = getFunctionLinkage(GD);
45170b57cec5SDimitry Andric   } else {
45180b57cec5SDimitry Andric     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
45190b57cec5SDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
45200b57cec5SDimitry Andric                                     /*D=*/nullptr);
45210b57cec5SDimitry Andric     LT = getLLVMLinkageVarDefinition(cast<VarDecl>(GD.getDecl()),
45220b57cec5SDimitry Andric                                      D->getType().isConstQualified());
45230b57cec5SDimitry Andric   }
45240b57cec5SDimitry Andric 
45250b57cec5SDimitry Andric   // Create the new alias itself, but don't set a name yet.
45260b57cec5SDimitry Andric   auto *GA =
45270b57cec5SDimitry Andric       llvm::GlobalAlias::create(DeclTy, 0, LT, "", Aliasee, &getModule());
45280b57cec5SDimitry Andric 
45290b57cec5SDimitry Andric   if (Entry) {
45300b57cec5SDimitry Andric     if (GA->getAliasee() == Entry) {
45310b57cec5SDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
45320b57cec5SDimitry Andric       return;
45330b57cec5SDimitry Andric     }
45340b57cec5SDimitry Andric 
45350b57cec5SDimitry Andric     assert(Entry->isDeclaration());
45360b57cec5SDimitry Andric 
45370b57cec5SDimitry Andric     // If there is a declaration in the module, then we had an extern followed
45380b57cec5SDimitry Andric     // by the alias, as in:
45390b57cec5SDimitry Andric     //   extern int test6();
45400b57cec5SDimitry Andric     //   ...
45410b57cec5SDimitry Andric     //   int test6() __attribute__((alias("test7")));
45420b57cec5SDimitry Andric     //
45430b57cec5SDimitry Andric     // Remove it and replace uses of it with the alias.
45440b57cec5SDimitry Andric     GA->takeName(Entry);
45450b57cec5SDimitry Andric 
45460b57cec5SDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
45470b57cec5SDimitry Andric                                                           Entry->getType()));
45480b57cec5SDimitry Andric     Entry->eraseFromParent();
45490b57cec5SDimitry Andric   } else {
45500b57cec5SDimitry Andric     GA->setName(MangledName);
45510b57cec5SDimitry Andric   }
45520b57cec5SDimitry Andric 
45530b57cec5SDimitry Andric   // Set attributes which are particular to an alias; this is a
45540b57cec5SDimitry Andric   // specialization of the attributes which may be set on a global
45550b57cec5SDimitry Andric   // variable/function.
45560b57cec5SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
45570b57cec5SDimitry Andric       D->isWeakImported()) {
45580b57cec5SDimitry Andric     GA->setLinkage(llvm::Function::WeakAnyLinkage);
45590b57cec5SDimitry Andric   }
45600b57cec5SDimitry Andric 
45610b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
45620b57cec5SDimitry Andric     if (VD->getTLSKind())
45630b57cec5SDimitry Andric       setTLSMode(GA, *VD);
45640b57cec5SDimitry Andric 
45650b57cec5SDimitry Andric   SetCommonAttributes(GD, GA);
45660b57cec5SDimitry Andric }
45670b57cec5SDimitry Andric 
45680b57cec5SDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
45690b57cec5SDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
45700b57cec5SDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
45710b57cec5SDimitry Andric   assert(IFA && "Not an ifunc?");
45720b57cec5SDimitry Andric 
45730b57cec5SDimitry Andric   StringRef MangledName = getMangledName(GD);
45740b57cec5SDimitry Andric 
45750b57cec5SDimitry Andric   if (IFA->getResolver() == MangledName) {
45760b57cec5SDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
45770b57cec5SDimitry Andric     return;
45780b57cec5SDimitry Andric   }
45790b57cec5SDimitry Andric 
45800b57cec5SDimitry Andric   // Report an error if some definition overrides ifunc.
45810b57cec5SDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
45820b57cec5SDimitry Andric   if (Entry && !Entry->isDeclaration()) {
45830b57cec5SDimitry Andric     GlobalDecl OtherGD;
45840b57cec5SDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
45850b57cec5SDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
45860b57cec5SDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
45870b57cec5SDimitry Andric           << MangledName;
45880b57cec5SDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
45890b57cec5SDimitry Andric                    diag::note_previous_definition);
45900b57cec5SDimitry Andric     }
45910b57cec5SDimitry Andric     return;
45920b57cec5SDimitry Andric   }
45930b57cec5SDimitry Andric 
45940b57cec5SDimitry Andric   Aliases.push_back(GD);
45950b57cec5SDimitry Andric 
45960b57cec5SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
45970b57cec5SDimitry Andric   llvm::Constant *Resolver =
45980b57cec5SDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
45990b57cec5SDimitry Andric                               /*ForVTable=*/false);
46000b57cec5SDimitry Andric   llvm::GlobalIFunc *GIF =
46010b57cec5SDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
46020b57cec5SDimitry Andric                                 "", Resolver, &getModule());
46030b57cec5SDimitry Andric   if (Entry) {
46040b57cec5SDimitry Andric     if (GIF->getResolver() == Entry) {
46050b57cec5SDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
46060b57cec5SDimitry Andric       return;
46070b57cec5SDimitry Andric     }
46080b57cec5SDimitry Andric     assert(Entry->isDeclaration());
46090b57cec5SDimitry Andric 
46100b57cec5SDimitry Andric     // If there is a declaration in the module, then we had an extern followed
46110b57cec5SDimitry Andric     // by the ifunc, as in:
46120b57cec5SDimitry Andric     //   extern int test();
46130b57cec5SDimitry Andric     //   ...
46140b57cec5SDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
46150b57cec5SDimitry Andric     //
46160b57cec5SDimitry Andric     // Remove it and replace uses of it with the ifunc.
46170b57cec5SDimitry Andric     GIF->takeName(Entry);
46180b57cec5SDimitry Andric 
46190b57cec5SDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
46200b57cec5SDimitry Andric                                                           Entry->getType()));
46210b57cec5SDimitry Andric     Entry->eraseFromParent();
46220b57cec5SDimitry Andric   } else
46230b57cec5SDimitry Andric     GIF->setName(MangledName);
46240b57cec5SDimitry Andric 
46250b57cec5SDimitry Andric   SetCommonAttributes(GD, GIF);
46260b57cec5SDimitry Andric }
46270b57cec5SDimitry Andric 
46280b57cec5SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
46290b57cec5SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
46300b57cec5SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
46310b57cec5SDimitry Andric                                          Tys);
46320b57cec5SDimitry Andric }
46330b57cec5SDimitry Andric 
46340b57cec5SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
46350b57cec5SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
46360b57cec5SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
46370b57cec5SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
46380b57cec5SDimitry Andric   StringRef String = Literal->getString();
46390b57cec5SDimitry Andric   unsigned NumBytes = String.size();
46400b57cec5SDimitry Andric 
46410b57cec5SDimitry Andric   // Check for simple case.
46420b57cec5SDimitry Andric   if (!Literal->containsNonAsciiOrNull()) {
46430b57cec5SDimitry Andric     StringLength = NumBytes;
46440b57cec5SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
46450b57cec5SDimitry Andric   }
46460b57cec5SDimitry Andric 
46470b57cec5SDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
46480b57cec5SDimitry Andric   IsUTF16 = true;
46490b57cec5SDimitry Andric 
46500b57cec5SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
46510b57cec5SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
46520b57cec5SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
46530b57cec5SDimitry Andric 
46540b57cec5SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
46550b57cec5SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
46560b57cec5SDimitry Andric 
46570b57cec5SDimitry Andric   // ConvertUTF8toUTF16 returns the length in ToPtr.
46580b57cec5SDimitry Andric   StringLength = ToPtr - &ToBuf[0];
46590b57cec5SDimitry Andric 
46600b57cec5SDimitry Andric   // Add an explicit null.
46610b57cec5SDimitry Andric   *ToPtr = 0;
46620b57cec5SDimitry Andric   return *Map.insert(std::make_pair(
46630b57cec5SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
46640b57cec5SDimitry Andric                                    (StringLength + 1) * 2),
46650b57cec5SDimitry Andric                          nullptr)).first;
46660b57cec5SDimitry Andric }
46670b57cec5SDimitry Andric 
46680b57cec5SDimitry Andric ConstantAddress
46690b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
46700b57cec5SDimitry Andric   unsigned StringLength = 0;
46710b57cec5SDimitry Andric   bool isUTF16 = false;
46720b57cec5SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
46730b57cec5SDimitry Andric       GetConstantCFStringEntry(CFConstantStringMap, Literal,
46740b57cec5SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
46750b57cec5SDimitry Andric                                StringLength);
46760b57cec5SDimitry Andric 
46770b57cec5SDimitry Andric   if (auto *C = Entry.second)
46780b57cec5SDimitry Andric     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
46790b57cec5SDimitry Andric 
46800b57cec5SDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
46810b57cec5SDimitry Andric   llvm::Constant *Zeros[] = { Zero, Zero };
46820b57cec5SDimitry Andric 
46830b57cec5SDimitry Andric   const ASTContext &Context = getContext();
46840b57cec5SDimitry Andric   const llvm::Triple &Triple = getTriple();
46850b57cec5SDimitry Andric 
46860b57cec5SDimitry Andric   const auto CFRuntime = getLangOpts().CFRuntime;
46870b57cec5SDimitry Andric   const bool IsSwiftABI =
46880b57cec5SDimitry Andric       static_cast<unsigned>(CFRuntime) >=
46890b57cec5SDimitry Andric       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
46900b57cec5SDimitry Andric   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
46910b57cec5SDimitry Andric 
46920b57cec5SDimitry Andric   // If we don't already have it, get __CFConstantStringClassReference.
46930b57cec5SDimitry Andric   if (!CFConstantStringClassRef) {
46940b57cec5SDimitry Andric     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
46950b57cec5SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
46960b57cec5SDimitry Andric     Ty = llvm::ArrayType::get(Ty, 0);
46970b57cec5SDimitry Andric 
46980b57cec5SDimitry Andric     switch (CFRuntime) {
46990b57cec5SDimitry Andric     default: break;
47000b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
47010b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift5_0:
47020b57cec5SDimitry Andric       CFConstantStringClassName =
47030b57cec5SDimitry Andric           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
47040b57cec5SDimitry Andric                               : "$s10Foundation19_NSCFConstantStringCN";
47050b57cec5SDimitry Andric       Ty = IntPtrTy;
47060b57cec5SDimitry Andric       break;
47070b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_2:
47080b57cec5SDimitry Andric       CFConstantStringClassName =
47090b57cec5SDimitry Andric           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
47100b57cec5SDimitry Andric                               : "$S10Foundation19_NSCFConstantStringCN";
47110b57cec5SDimitry Andric       Ty = IntPtrTy;
47120b57cec5SDimitry Andric       break;
47130b57cec5SDimitry Andric     case LangOptions::CoreFoundationABI::Swift4_1:
47140b57cec5SDimitry Andric       CFConstantStringClassName =
47150b57cec5SDimitry Andric           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
47160b57cec5SDimitry Andric                               : "__T010Foundation19_NSCFConstantStringCN";
47170b57cec5SDimitry Andric       Ty = IntPtrTy;
47180b57cec5SDimitry Andric       break;
47190b57cec5SDimitry Andric     }
47200b57cec5SDimitry Andric 
47210b57cec5SDimitry Andric     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
47220b57cec5SDimitry Andric 
47230b57cec5SDimitry Andric     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
47240b57cec5SDimitry Andric       llvm::GlobalValue *GV = nullptr;
47250b57cec5SDimitry Andric 
47260b57cec5SDimitry Andric       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
47270b57cec5SDimitry Andric         IdentifierInfo &II = Context.Idents.get(GV->getName());
47280b57cec5SDimitry Andric         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
47290b57cec5SDimitry Andric         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
47300b57cec5SDimitry Andric 
47310b57cec5SDimitry Andric         const VarDecl *VD = nullptr;
47320b57cec5SDimitry Andric         for (const auto &Result : DC->lookup(&II))
47330b57cec5SDimitry Andric           if ((VD = dyn_cast<VarDecl>(Result)))
47340b57cec5SDimitry Andric             break;
47350b57cec5SDimitry Andric 
47360b57cec5SDimitry Andric         if (Triple.isOSBinFormatELF()) {
47370b57cec5SDimitry Andric           if (!VD)
47380b57cec5SDimitry Andric             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
47390b57cec5SDimitry Andric         } else {
47400b57cec5SDimitry Andric           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
47410b57cec5SDimitry Andric           if (!VD || !VD->hasAttr<DLLExportAttr>())
47420b57cec5SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
47430b57cec5SDimitry Andric           else
47440b57cec5SDimitry Andric             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
47450b57cec5SDimitry Andric         }
47460b57cec5SDimitry Andric 
47470b57cec5SDimitry Andric         setDSOLocal(GV);
47480b57cec5SDimitry Andric       }
47490b57cec5SDimitry Andric     }
47500b57cec5SDimitry Andric 
47510b57cec5SDimitry Andric     // Decay array -> ptr
47520b57cec5SDimitry Andric     CFConstantStringClassRef =
47530b57cec5SDimitry Andric         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
47540b57cec5SDimitry Andric                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
47550b57cec5SDimitry Andric   }
47560b57cec5SDimitry Andric 
47570b57cec5SDimitry Andric   QualType CFTy = Context.getCFConstantStringType();
47580b57cec5SDimitry Andric 
47590b57cec5SDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
47600b57cec5SDimitry Andric 
47610b57cec5SDimitry Andric   ConstantInitBuilder Builder(*this);
47620b57cec5SDimitry Andric   auto Fields = Builder.beginStruct(STy);
47630b57cec5SDimitry Andric 
47640b57cec5SDimitry Andric   // Class pointer.
47650b57cec5SDimitry Andric   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
47660b57cec5SDimitry Andric 
47670b57cec5SDimitry Andric   // Flags.
47680b57cec5SDimitry Andric   if (IsSwiftABI) {
47690b57cec5SDimitry Andric     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
47700b57cec5SDimitry Andric     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
47710b57cec5SDimitry Andric   } else {
47720b57cec5SDimitry Andric     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
47730b57cec5SDimitry Andric   }
47740b57cec5SDimitry Andric 
47750b57cec5SDimitry Andric   // String pointer.
47760b57cec5SDimitry Andric   llvm::Constant *C = nullptr;
47770b57cec5SDimitry Andric   if (isUTF16) {
47780b57cec5SDimitry Andric     auto Arr = llvm::makeArrayRef(
47790b57cec5SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
47800b57cec5SDimitry Andric         Entry.first().size() / 2);
47810b57cec5SDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
47820b57cec5SDimitry Andric   } else {
47830b57cec5SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
47840b57cec5SDimitry Andric   }
47850b57cec5SDimitry Andric 
47860b57cec5SDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
47870b57cec5SDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
47880b57cec5SDimitry Andric   auto *GV =
47890b57cec5SDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
47900b57cec5SDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
47910b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
47920b57cec5SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
47930b57cec5SDimitry Andric   // of the string is via this class initializer.
47940b57cec5SDimitry Andric   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
47950b57cec5SDimitry Andric                             : Context.getTypeAlignInChars(Context.CharTy);
4796a7dea167SDimitry Andric   GV->setAlignment(Align.getAsAlign());
47970b57cec5SDimitry Andric 
47980b57cec5SDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
47990b57cec5SDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
48000b57cec5SDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
48010b57cec5SDimitry Andric   if (Triple.isOSBinFormatMachO())
48020b57cec5SDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
48030b57cec5SDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
48040b57cec5SDimitry Andric   // Make sure the literal ends up in .rodata to allow for safe ICF and for
48050b57cec5SDimitry Andric   // the static linker to adjust permissions to read-only later on.
48060b57cec5SDimitry Andric   else if (Triple.isOSBinFormatELF())
48070b57cec5SDimitry Andric     GV->setSection(".rodata");
48080b57cec5SDimitry Andric 
48090b57cec5SDimitry Andric   // String.
48100b57cec5SDimitry Andric   llvm::Constant *Str =
48110b57cec5SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
48120b57cec5SDimitry Andric 
48130b57cec5SDimitry Andric   if (isUTF16)
48140b57cec5SDimitry Andric     // Cast the UTF16 string to the correct type.
48150b57cec5SDimitry Andric     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
48160b57cec5SDimitry Andric   Fields.add(Str);
48170b57cec5SDimitry Andric 
48180b57cec5SDimitry Andric   // String length.
48190b57cec5SDimitry Andric   llvm::IntegerType *LengthTy =
48200b57cec5SDimitry Andric       llvm::IntegerType::get(getModule().getContext(),
48210b57cec5SDimitry Andric                              Context.getTargetInfo().getLongWidth());
48220b57cec5SDimitry Andric   if (IsSwiftABI) {
48230b57cec5SDimitry Andric     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
48240b57cec5SDimitry Andric         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
48250b57cec5SDimitry Andric       LengthTy = Int32Ty;
48260b57cec5SDimitry Andric     else
48270b57cec5SDimitry Andric       LengthTy = IntPtrTy;
48280b57cec5SDimitry Andric   }
48290b57cec5SDimitry Andric   Fields.addInt(LengthTy, StringLength);
48300b57cec5SDimitry Andric 
4831a7dea167SDimitry Andric   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
4832a7dea167SDimitry Andric   // properly aligned on 32-bit platforms.
4833a7dea167SDimitry Andric   CharUnits Alignment =
4834a7dea167SDimitry Andric       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
48350b57cec5SDimitry Andric 
48360b57cec5SDimitry Andric   // The struct.
48370b57cec5SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
48380b57cec5SDimitry Andric                                     /*isConstant=*/false,
48390b57cec5SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
48400b57cec5SDimitry Andric   GV->addAttribute("objc_arc_inert");
48410b57cec5SDimitry Andric   switch (Triple.getObjectFormat()) {
48420b57cec5SDimitry Andric   case llvm::Triple::UnknownObjectFormat:
48430b57cec5SDimitry Andric     llvm_unreachable("unknown file format");
48440b57cec5SDimitry Andric   case llvm::Triple::XCOFF:
48450b57cec5SDimitry Andric     llvm_unreachable("XCOFF is not yet implemented");
48460b57cec5SDimitry Andric   case llvm::Triple::COFF:
48470b57cec5SDimitry Andric   case llvm::Triple::ELF:
48480b57cec5SDimitry Andric   case llvm::Triple::Wasm:
48490b57cec5SDimitry Andric     GV->setSection("cfstring");
48500b57cec5SDimitry Andric     break;
48510b57cec5SDimitry Andric   case llvm::Triple::MachO:
48520b57cec5SDimitry Andric     GV->setSection("__DATA,__cfstring");
48530b57cec5SDimitry Andric     break;
48540b57cec5SDimitry Andric   }
48550b57cec5SDimitry Andric   Entry.second = GV;
48560b57cec5SDimitry Andric 
48570b57cec5SDimitry Andric   return ConstantAddress(GV, Alignment);
48580b57cec5SDimitry Andric }
48590b57cec5SDimitry Andric 
48600b57cec5SDimitry Andric bool CodeGenModule::getExpressionLocationsEnabled() const {
48610b57cec5SDimitry Andric   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
48620b57cec5SDimitry Andric }
48630b57cec5SDimitry Andric 
48640b57cec5SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
48650b57cec5SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
48660b57cec5SDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
48670b57cec5SDimitry Andric     D->startDefinition();
48680b57cec5SDimitry Andric 
48690b57cec5SDimitry Andric     QualType FieldTypes[] = {
48700b57cec5SDimitry Andric       Context.UnsignedLongTy,
48710b57cec5SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
48720b57cec5SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
48730b57cec5SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
4874a7dea167SDimitry Andric                            llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
48750b57cec5SDimitry Andric     };
48760b57cec5SDimitry Andric 
48770b57cec5SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
48780b57cec5SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
48790b57cec5SDimitry Andric                                            D,
48800b57cec5SDimitry Andric                                            SourceLocation(),
48810b57cec5SDimitry Andric                                            SourceLocation(), nullptr,
48820b57cec5SDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
48830b57cec5SDimitry Andric                                            /*BitWidth=*/nullptr,
48840b57cec5SDimitry Andric                                            /*Mutable=*/false,
48850b57cec5SDimitry Andric                                            ICIS_NoInit);
48860b57cec5SDimitry Andric       Field->setAccess(AS_public);
48870b57cec5SDimitry Andric       D->addDecl(Field);
48880b57cec5SDimitry Andric     }
48890b57cec5SDimitry Andric 
48900b57cec5SDimitry Andric     D->completeDefinition();
48910b57cec5SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
48920b57cec5SDimitry Andric   }
48930b57cec5SDimitry Andric 
48940b57cec5SDimitry Andric   return ObjCFastEnumerationStateType;
48950b57cec5SDimitry Andric }
48960b57cec5SDimitry Andric 
48970b57cec5SDimitry Andric llvm::Constant *
48980b57cec5SDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
48990b57cec5SDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
49000b57cec5SDimitry Andric 
49010b57cec5SDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
49020b57cec5SDimitry Andric   // as an inline array.
49030b57cec5SDimitry Andric   if (E->getCharByteWidth() == 1) {
49040b57cec5SDimitry Andric     SmallString<64> Str(E->getString());
49050b57cec5SDimitry Andric 
49060b57cec5SDimitry Andric     // Resize the string to the right size, which is indicated by its type.
49070b57cec5SDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
49080b57cec5SDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
49090b57cec5SDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
49100b57cec5SDimitry Andric   }
49110b57cec5SDimitry Andric 
49120b57cec5SDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
49130b57cec5SDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
49140b57cec5SDimitry Andric   unsigned NumElements = AType->getNumElements();
49150b57cec5SDimitry Andric 
49160b57cec5SDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
49170b57cec5SDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
49180b57cec5SDimitry Andric     SmallVector<uint16_t, 32> Elements;
49190b57cec5SDimitry Andric     Elements.reserve(NumElements);
49200b57cec5SDimitry Andric 
49210b57cec5SDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
49220b57cec5SDimitry Andric       Elements.push_back(E->getCodeUnit(i));
49230b57cec5SDimitry Andric     Elements.resize(NumElements);
49240b57cec5SDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
49250b57cec5SDimitry Andric   }
49260b57cec5SDimitry Andric 
49270b57cec5SDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
49280b57cec5SDimitry Andric   SmallVector<uint32_t, 32> Elements;
49290b57cec5SDimitry Andric   Elements.reserve(NumElements);
49300b57cec5SDimitry Andric 
49310b57cec5SDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
49320b57cec5SDimitry Andric     Elements.push_back(E->getCodeUnit(i));
49330b57cec5SDimitry Andric   Elements.resize(NumElements);
49340b57cec5SDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
49350b57cec5SDimitry Andric }
49360b57cec5SDimitry Andric 
49370b57cec5SDimitry Andric static llvm::GlobalVariable *
49380b57cec5SDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
49390b57cec5SDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
49400b57cec5SDimitry Andric                       CharUnits Alignment) {
49410b57cec5SDimitry Andric   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
49420b57cec5SDimitry Andric       CGM.getStringLiteralAddressSpace());
49430b57cec5SDimitry Andric 
49440b57cec5SDimitry Andric   llvm::Module &M = CGM.getModule();
49450b57cec5SDimitry Andric   // Create a global variable for this string
49460b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
49470b57cec5SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
49480b57cec5SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
4949a7dea167SDimitry Andric   GV->setAlignment(Alignment.getAsAlign());
49500b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
49510b57cec5SDimitry Andric   if (GV->isWeakForLinker()) {
49520b57cec5SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
49530b57cec5SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
49540b57cec5SDimitry Andric   }
49550b57cec5SDimitry Andric   CGM.setDSOLocal(GV);
49560b57cec5SDimitry Andric 
49570b57cec5SDimitry Andric   return GV;
49580b57cec5SDimitry Andric }
49590b57cec5SDimitry Andric 
49600b57cec5SDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
49610b57cec5SDimitry Andric /// constant array for the given string literal.
49620b57cec5SDimitry Andric ConstantAddress
49630b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
49640b57cec5SDimitry Andric                                                   StringRef Name) {
49650b57cec5SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
49660b57cec5SDimitry Andric 
49670b57cec5SDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
49680b57cec5SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
49690b57cec5SDimitry Andric   if (!LangOpts.WritableStrings) {
49700b57cec5SDimitry Andric     Entry = &ConstantStringMap[C];
49710b57cec5SDimitry Andric     if (auto GV = *Entry) {
49720b57cec5SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
4973a7dea167SDimitry Andric         GV->setAlignment(Alignment.getAsAlign());
49740b57cec5SDimitry Andric       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
49750b57cec5SDimitry Andric                              Alignment);
49760b57cec5SDimitry Andric     }
49770b57cec5SDimitry Andric   }
49780b57cec5SDimitry Andric 
49790b57cec5SDimitry Andric   SmallString<256> MangledNameBuffer;
49800b57cec5SDimitry Andric   StringRef GlobalVariableName;
49810b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
49820b57cec5SDimitry Andric 
49830b57cec5SDimitry Andric   // Mangle the string literal if that's how the ABI merges duplicate strings.
49840b57cec5SDimitry Andric   // Don't do it if they are writable, since we don't want writes in one TU to
49850b57cec5SDimitry Andric   // affect strings in another.
49860b57cec5SDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
49870b57cec5SDimitry Andric       !LangOpts.WritableStrings) {
49880b57cec5SDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
49890b57cec5SDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
49900b57cec5SDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
49910b57cec5SDimitry Andric     GlobalVariableName = MangledNameBuffer;
49920b57cec5SDimitry Andric   } else {
49930b57cec5SDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
49940b57cec5SDimitry Andric     GlobalVariableName = Name;
49950b57cec5SDimitry Andric   }
49960b57cec5SDimitry Andric 
49970b57cec5SDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
49980b57cec5SDimitry Andric   if (Entry)
49990b57cec5SDimitry Andric     *Entry = GV;
50000b57cec5SDimitry Andric 
50010b57cec5SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
50020b57cec5SDimitry Andric                                   QualType());
50030b57cec5SDimitry Andric 
50040b57cec5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
50050b57cec5SDimitry Andric                          Alignment);
50060b57cec5SDimitry Andric }
50070b57cec5SDimitry Andric 
50080b57cec5SDimitry Andric /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
50090b57cec5SDimitry Andric /// array for the given ObjCEncodeExpr node.
50100b57cec5SDimitry Andric ConstantAddress
50110b57cec5SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
50120b57cec5SDimitry Andric   std::string Str;
50130b57cec5SDimitry Andric   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
50140b57cec5SDimitry Andric 
50150b57cec5SDimitry Andric   return GetAddrOfConstantCString(Str);
50160b57cec5SDimitry Andric }
50170b57cec5SDimitry Andric 
50180b57cec5SDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
50190b57cec5SDimitry Andric /// the literal and a terminating '\0' character.
50200b57cec5SDimitry Andric /// The result has pointer to array type.
50210b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
50220b57cec5SDimitry Andric     const std::string &Str, const char *GlobalName) {
50230b57cec5SDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
50240b57cec5SDimitry Andric   CharUnits Alignment =
50250b57cec5SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
50260b57cec5SDimitry Andric 
50270b57cec5SDimitry Andric   llvm::Constant *C =
50280b57cec5SDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
50290b57cec5SDimitry Andric 
50300b57cec5SDimitry Andric   // Don't share any string literals if strings aren't constant.
50310b57cec5SDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
50320b57cec5SDimitry Andric   if (!LangOpts.WritableStrings) {
50330b57cec5SDimitry Andric     Entry = &ConstantStringMap[C];
50340b57cec5SDimitry Andric     if (auto GV = *Entry) {
50350b57cec5SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
5036a7dea167SDimitry Andric         GV->setAlignment(Alignment.getAsAlign());
50370b57cec5SDimitry Andric       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
50380b57cec5SDimitry Andric                              Alignment);
50390b57cec5SDimitry Andric     }
50400b57cec5SDimitry Andric   }
50410b57cec5SDimitry Andric 
50420b57cec5SDimitry Andric   // Get the default prefix if a name wasn't specified.
50430b57cec5SDimitry Andric   if (!GlobalName)
50440b57cec5SDimitry Andric     GlobalName = ".str";
50450b57cec5SDimitry Andric   // Create a global variable for this.
50460b57cec5SDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
50470b57cec5SDimitry Andric                                   GlobalName, Alignment);
50480b57cec5SDimitry Andric   if (Entry)
50490b57cec5SDimitry Andric     *Entry = GV;
50500b57cec5SDimitry Andric 
50510b57cec5SDimitry Andric   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
50520b57cec5SDimitry Andric                          Alignment);
50530b57cec5SDimitry Andric }
50540b57cec5SDimitry Andric 
50550b57cec5SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
50560b57cec5SDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
50570b57cec5SDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
50580b57cec5SDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
50590b57cec5SDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
50600b57cec5SDimitry Andric 
50610b57cec5SDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
50620b57cec5SDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
50630b57cec5SDimitry Andric   QualType MaterializedType = Init->getType();
5064480093f4SDimitry Andric   if (Init == E->getSubExpr())
50650b57cec5SDimitry Andric     MaterializedType = E->getType();
50660b57cec5SDimitry Andric 
50670b57cec5SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
50680b57cec5SDimitry Andric 
50690b57cec5SDimitry Andric   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
50700b57cec5SDimitry Andric     return ConstantAddress(Slot, Align);
50710b57cec5SDimitry Andric 
50720b57cec5SDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
50730b57cec5SDimitry Andric   // we need to give each temporary the same name in every translation unit (and
50740b57cec5SDimitry Andric   // we also need to make the temporaries externally-visible).
50750b57cec5SDimitry Andric   SmallString<256> Name;
50760b57cec5SDimitry Andric   llvm::raw_svector_ostream Out(Name);
50770b57cec5SDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
50780b57cec5SDimitry Andric       VD, E->getManglingNumber(), Out);
50790b57cec5SDimitry Andric 
50800b57cec5SDimitry Andric   APValue *Value = nullptr;
5081a7dea167SDimitry Andric   if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
5082a7dea167SDimitry Andric     // If the initializer of the extending declaration is a constant
5083a7dea167SDimitry Andric     // initializer, we should have a cached constant initializer for this
5084a7dea167SDimitry Andric     // temporary. Note that this might have a different value from the value
5085a7dea167SDimitry Andric     // computed by evaluating the initializer if the surrounding constant
5086a7dea167SDimitry Andric     // expression modifies the temporary.
5087480093f4SDimitry Andric     Value = E->getOrCreateValue(false);
50880b57cec5SDimitry Andric   }
50890b57cec5SDimitry Andric 
50900b57cec5SDimitry Andric   // Try evaluating it now, it might have a constant initializer.
50910b57cec5SDimitry Andric   Expr::EvalResult EvalResult;
50920b57cec5SDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
50930b57cec5SDimitry Andric       !EvalResult.hasSideEffects())
50940b57cec5SDimitry Andric     Value = &EvalResult.Val;
50950b57cec5SDimitry Andric 
50960b57cec5SDimitry Andric   LangAS AddrSpace =
50970b57cec5SDimitry Andric       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
50980b57cec5SDimitry Andric 
50990b57cec5SDimitry Andric   Optional<ConstantEmitter> emitter;
51000b57cec5SDimitry Andric   llvm::Constant *InitialValue = nullptr;
51010b57cec5SDimitry Andric   bool Constant = false;
51020b57cec5SDimitry Andric   llvm::Type *Type;
51030b57cec5SDimitry Andric   if (Value) {
51040b57cec5SDimitry Andric     // The temporary has a constant initializer, use it.
51050b57cec5SDimitry Andric     emitter.emplace(*this);
51060b57cec5SDimitry Andric     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
51070b57cec5SDimitry Andric                                                MaterializedType);
51080b57cec5SDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
51090b57cec5SDimitry Andric     Type = InitialValue->getType();
51100b57cec5SDimitry Andric   } else {
51110b57cec5SDimitry Andric     // No initializer, the initialization will be provided when we
51120b57cec5SDimitry Andric     // initialize the declaration which performed lifetime extension.
51130b57cec5SDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
51140b57cec5SDimitry Andric   }
51150b57cec5SDimitry Andric 
51160b57cec5SDimitry Andric   // Create a global variable for this lifetime-extended temporary.
51170b57cec5SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
51180b57cec5SDimitry Andric       getLLVMLinkageVarDefinition(VD, Constant);
51190b57cec5SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
51200b57cec5SDimitry Andric     const VarDecl *InitVD;
51210b57cec5SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
51220b57cec5SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
51230b57cec5SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
51240b57cec5SDimitry Andric       // class can be defined in multiple translation units.
51250b57cec5SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
51260b57cec5SDimitry Andric     } else {
51270b57cec5SDimitry Andric       // There is no need for this temporary to have external linkage if the
51280b57cec5SDimitry Andric       // VarDecl has external linkage.
51290b57cec5SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
51300b57cec5SDimitry Andric     }
51310b57cec5SDimitry Andric   }
51320b57cec5SDimitry Andric   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
51330b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
51340b57cec5SDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
51350b57cec5SDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
51360b57cec5SDimitry Andric   if (emitter) emitter->finalize(GV);
51370b57cec5SDimitry Andric   setGVProperties(GV, VD);
5138a7dea167SDimitry Andric   GV->setAlignment(Align.getAsAlign());
51390b57cec5SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
51400b57cec5SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
51410b57cec5SDimitry Andric   if (VD->getTLSKind())
51420b57cec5SDimitry Andric     setTLSMode(GV, *VD);
51430b57cec5SDimitry Andric   llvm::Constant *CV = GV;
51440b57cec5SDimitry Andric   if (AddrSpace != LangAS::Default)
51450b57cec5SDimitry Andric     CV = getTargetCodeGenInfo().performAddrSpaceCast(
51460b57cec5SDimitry Andric         *this, GV, AddrSpace, LangAS::Default,
51470b57cec5SDimitry Andric         Type->getPointerTo(
51480b57cec5SDimitry Andric             getContext().getTargetAddressSpace(LangAS::Default)));
51490b57cec5SDimitry Andric   MaterializedGlobalTemporaryMap[E] = CV;
51500b57cec5SDimitry Andric   return ConstantAddress(CV, Align);
51510b57cec5SDimitry Andric }
51520b57cec5SDimitry Andric 
51530b57cec5SDimitry Andric /// EmitObjCPropertyImplementations - Emit information for synthesized
51540b57cec5SDimitry Andric /// properties for an implementation.
51550b57cec5SDimitry Andric void CodeGenModule::EmitObjCPropertyImplementations(const
51560b57cec5SDimitry Andric                                                     ObjCImplementationDecl *D) {
51570b57cec5SDimitry Andric   for (const auto *PID : D->property_impls()) {
51580b57cec5SDimitry Andric     // Dynamic is just for type-checking.
51590b57cec5SDimitry Andric     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
51600b57cec5SDimitry Andric       ObjCPropertyDecl *PD = PID->getPropertyDecl();
51610b57cec5SDimitry Andric 
51620b57cec5SDimitry Andric       // Determine which methods need to be implemented, some may have
51630b57cec5SDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
51640b57cec5SDimitry Andric       // we want, that just indicates if the decl came from a
51650b57cec5SDimitry Andric       // property. What we want to know is if the method is defined in
51660b57cec5SDimitry Andric       // this implementation.
5167480093f4SDimitry Andric       auto *Getter = PID->getGetterMethodDecl();
5168480093f4SDimitry Andric       if (!Getter || Getter->isSynthesizedAccessorStub())
51690b57cec5SDimitry Andric         CodeGenFunction(*this).GenerateObjCGetter(
51700b57cec5SDimitry Andric             const_cast<ObjCImplementationDecl *>(D), PID);
5171480093f4SDimitry Andric       auto *Setter = PID->getSetterMethodDecl();
5172480093f4SDimitry Andric       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
51730b57cec5SDimitry Andric         CodeGenFunction(*this).GenerateObjCSetter(
51740b57cec5SDimitry Andric                                  const_cast<ObjCImplementationDecl *>(D), PID);
51750b57cec5SDimitry Andric     }
51760b57cec5SDimitry Andric   }
51770b57cec5SDimitry Andric }
51780b57cec5SDimitry Andric 
51790b57cec5SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
51800b57cec5SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
51810b57cec5SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
51820b57cec5SDimitry Andric        ivar; ivar = ivar->getNextIvar())
51830b57cec5SDimitry Andric     if (ivar->getType().isDestructedType())
51840b57cec5SDimitry Andric       return true;
51850b57cec5SDimitry Andric 
51860b57cec5SDimitry Andric   return false;
51870b57cec5SDimitry Andric }
51880b57cec5SDimitry Andric 
51890b57cec5SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
51900b57cec5SDimitry Andric                                    ObjCImplementationDecl *D) {
51910b57cec5SDimitry Andric   CodeGenFunction CGF(CGM);
51920b57cec5SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
51930b57cec5SDimitry Andric        E = D->init_end(); B != E; ++B) {
51940b57cec5SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
51950b57cec5SDimitry Andric     Expr *Init = CtorInitExp->getInit();
51960b57cec5SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
51970b57cec5SDimitry Andric       return false;
51980b57cec5SDimitry Andric   }
51990b57cec5SDimitry Andric   return true;
52000b57cec5SDimitry Andric }
52010b57cec5SDimitry Andric 
52020b57cec5SDimitry Andric /// EmitObjCIvarInitializations - Emit information for ivar initialization
52030b57cec5SDimitry Andric /// for an implementation.
52040b57cec5SDimitry Andric void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
52050b57cec5SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
52060b57cec5SDimitry Andric   if (needsDestructMethod(D)) {
52070b57cec5SDimitry Andric     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
52080b57cec5SDimitry Andric     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5209480093f4SDimitry Andric     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
5210480093f4SDimitry Andric         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5211480093f4SDimitry Andric         getContext().VoidTy, nullptr, D,
52120b57cec5SDimitry Andric         /*isInstance=*/true, /*isVariadic=*/false,
5213480093f4SDimitry Andric         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5214480093f4SDimitry Andric         /*isImplicitlyDeclared=*/true,
52150b57cec5SDimitry Andric         /*isDefined=*/false, ObjCMethodDecl::Required);
52160b57cec5SDimitry Andric     D->addInstanceMethod(DTORMethod);
52170b57cec5SDimitry Andric     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
52180b57cec5SDimitry Andric     D->setHasDestructors(true);
52190b57cec5SDimitry Andric   }
52200b57cec5SDimitry Andric 
52210b57cec5SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
52220b57cec5SDimitry Andric   // a .cxx_construct.
52230b57cec5SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
52240b57cec5SDimitry Andric       AllTrivialInitializers(*this, D))
52250b57cec5SDimitry Andric     return;
52260b57cec5SDimitry Andric 
52270b57cec5SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
52280b57cec5SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
52290b57cec5SDimitry Andric   // The constructor returns 'self'.
5230480093f4SDimitry Andric   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
5231480093f4SDimitry Andric       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5232480093f4SDimitry Andric       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
52330b57cec5SDimitry Andric       /*isVariadic=*/false,
5234480093f4SDimitry Andric       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
52350b57cec5SDimitry Andric       /*isImplicitlyDeclared=*/true,
5236480093f4SDimitry Andric       /*isDefined=*/false, ObjCMethodDecl::Required);
52370b57cec5SDimitry Andric   D->addInstanceMethod(CTORMethod);
52380b57cec5SDimitry Andric   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
52390b57cec5SDimitry Andric   D->setHasNonZeroConstructors(true);
52400b57cec5SDimitry Andric }
52410b57cec5SDimitry Andric 
52420b57cec5SDimitry Andric // EmitLinkageSpec - Emit all declarations in a linkage spec.
52430b57cec5SDimitry Andric void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
52440b57cec5SDimitry Andric   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5245480093f4SDimitry Andric       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
52460b57cec5SDimitry Andric     ErrorUnsupported(LSD, "linkage spec");
52470b57cec5SDimitry Andric     return;
52480b57cec5SDimitry Andric   }
52490b57cec5SDimitry Andric 
52500b57cec5SDimitry Andric   EmitDeclContext(LSD);
52510b57cec5SDimitry Andric }
52520b57cec5SDimitry Andric 
52530b57cec5SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
52540b57cec5SDimitry Andric   for (auto *I : DC->decls()) {
52550b57cec5SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
52560b57cec5SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
52570b57cec5SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
52580b57cec5SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
52590b57cec5SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
52600b57cec5SDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
52610b57cec5SDimitry Andric       for (auto *M : OID->methods())
52620b57cec5SDimitry Andric         EmitTopLevelDecl(M);
52630b57cec5SDimitry Andric     }
52640b57cec5SDimitry Andric 
52650b57cec5SDimitry Andric     EmitTopLevelDecl(I);
52660b57cec5SDimitry Andric   }
52670b57cec5SDimitry Andric }
52680b57cec5SDimitry Andric 
52690b57cec5SDimitry Andric /// EmitTopLevelDecl - Emit code for a single top level declaration.
52700b57cec5SDimitry Andric void CodeGenModule::EmitTopLevelDecl(Decl *D) {
52710b57cec5SDimitry Andric   // Ignore dependent declarations.
52720b57cec5SDimitry Andric   if (D->isTemplated())
52730b57cec5SDimitry Andric     return;
52740b57cec5SDimitry Andric 
52750b57cec5SDimitry Andric   switch (D->getKind()) {
52760b57cec5SDimitry Andric   case Decl::CXXConversion:
52770b57cec5SDimitry Andric   case Decl::CXXMethod:
52780b57cec5SDimitry Andric   case Decl::Function:
52790b57cec5SDimitry Andric     EmitGlobal(cast<FunctionDecl>(D));
52800b57cec5SDimitry Andric     // Always provide some coverage mapping
52810b57cec5SDimitry Andric     // even for the functions that aren't emitted.
52820b57cec5SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
52830b57cec5SDimitry Andric     break;
52840b57cec5SDimitry Andric 
52850b57cec5SDimitry Andric   case Decl::CXXDeductionGuide:
52860b57cec5SDimitry Andric     // Function-like, but does not result in code emission.
52870b57cec5SDimitry Andric     break;
52880b57cec5SDimitry Andric 
52890b57cec5SDimitry Andric   case Decl::Var:
52900b57cec5SDimitry Andric   case Decl::Decomposition:
52910b57cec5SDimitry Andric   case Decl::VarTemplateSpecialization:
52920b57cec5SDimitry Andric     EmitGlobal(cast<VarDecl>(D));
52930b57cec5SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
52940b57cec5SDimitry Andric       for (auto *B : DD->bindings())
52950b57cec5SDimitry Andric         if (auto *HD = B->getHoldingVar())
52960b57cec5SDimitry Andric           EmitGlobal(HD);
52970b57cec5SDimitry Andric     break;
52980b57cec5SDimitry Andric 
52990b57cec5SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
53000b57cec5SDimitry Andric   // ignored; only the actual variable requires IR gen support.
53010b57cec5SDimitry Andric   case Decl::IndirectField:
53020b57cec5SDimitry Andric     break;
53030b57cec5SDimitry Andric 
53040b57cec5SDimitry Andric   // C++ Decls
53050b57cec5SDimitry Andric   case Decl::Namespace:
53060b57cec5SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
53070b57cec5SDimitry Andric     break;
53080b57cec5SDimitry Andric   case Decl::ClassTemplateSpecialization: {
53090b57cec5SDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
53100b57cec5SDimitry Andric     if (DebugInfo &&
53110b57cec5SDimitry Andric         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
53120b57cec5SDimitry Andric         Spec->hasDefinition())
53130b57cec5SDimitry Andric       DebugInfo->completeTemplateDefinition(*Spec);
53140b57cec5SDimitry Andric   } LLVM_FALLTHROUGH;
53150b57cec5SDimitry Andric   case Decl::CXXRecord:
53160b57cec5SDimitry Andric     if (DebugInfo) {
53170b57cec5SDimitry Andric       if (auto *ES = D->getASTContext().getExternalSource())
53180b57cec5SDimitry Andric         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
53190b57cec5SDimitry Andric           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
53200b57cec5SDimitry Andric     }
53210b57cec5SDimitry Andric     // Emit any static data members, they may be definitions.
53220b57cec5SDimitry Andric     for (auto *I : cast<CXXRecordDecl>(D)->decls())
53230b57cec5SDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
53240b57cec5SDimitry Andric         EmitTopLevelDecl(I);
53250b57cec5SDimitry Andric     break;
53260b57cec5SDimitry Andric     // No code generation needed.
53270b57cec5SDimitry Andric   case Decl::UsingShadow:
53280b57cec5SDimitry Andric   case Decl::ClassTemplate:
53290b57cec5SDimitry Andric   case Decl::VarTemplate:
53300b57cec5SDimitry Andric   case Decl::Concept:
53310b57cec5SDimitry Andric   case Decl::VarTemplatePartialSpecialization:
53320b57cec5SDimitry Andric   case Decl::FunctionTemplate:
53330b57cec5SDimitry Andric   case Decl::TypeAliasTemplate:
53340b57cec5SDimitry Andric   case Decl::Block:
53350b57cec5SDimitry Andric   case Decl::Empty:
53360b57cec5SDimitry Andric   case Decl::Binding:
53370b57cec5SDimitry Andric     break;
53380b57cec5SDimitry Andric   case Decl::Using:          // using X; [C++]
53390b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
53400b57cec5SDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
53410b57cec5SDimitry Andric     return;
53420b57cec5SDimitry Andric   case Decl::NamespaceAlias:
53430b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
53440b57cec5SDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
53450b57cec5SDimitry Andric     return;
53460b57cec5SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
53470b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
53480b57cec5SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
53490b57cec5SDimitry Andric     return;
53500b57cec5SDimitry Andric   case Decl::CXXConstructor:
53510b57cec5SDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
53520b57cec5SDimitry Andric     break;
53530b57cec5SDimitry Andric   case Decl::CXXDestructor:
53540b57cec5SDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
53550b57cec5SDimitry Andric     break;
53560b57cec5SDimitry Andric 
53570b57cec5SDimitry Andric   case Decl::StaticAssert:
53580b57cec5SDimitry Andric     // Nothing to do.
53590b57cec5SDimitry Andric     break;
53600b57cec5SDimitry Andric 
53610b57cec5SDimitry Andric   // Objective-C Decls
53620b57cec5SDimitry Andric 
53630b57cec5SDimitry Andric   // Forward declarations, no (immediate) code generation.
53640b57cec5SDimitry Andric   case Decl::ObjCInterface:
53650b57cec5SDimitry Andric   case Decl::ObjCCategory:
53660b57cec5SDimitry Andric     break;
53670b57cec5SDimitry Andric 
53680b57cec5SDimitry Andric   case Decl::ObjCProtocol: {
53690b57cec5SDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
53700b57cec5SDimitry Andric     if (Proto->isThisDeclarationADefinition())
53710b57cec5SDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
53720b57cec5SDimitry Andric     break;
53730b57cec5SDimitry Andric   }
53740b57cec5SDimitry Andric 
53750b57cec5SDimitry Andric   case Decl::ObjCCategoryImpl:
53760b57cec5SDimitry Andric     // Categories have properties but don't support synthesize so we
53770b57cec5SDimitry Andric     // can ignore them here.
53780b57cec5SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
53790b57cec5SDimitry Andric     break;
53800b57cec5SDimitry Andric 
53810b57cec5SDimitry Andric   case Decl::ObjCImplementation: {
53820b57cec5SDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
53830b57cec5SDimitry Andric     EmitObjCPropertyImplementations(OMD);
53840b57cec5SDimitry Andric     EmitObjCIvarInitializations(OMD);
53850b57cec5SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
53860b57cec5SDimitry Andric     // Emit global variable debug information.
53870b57cec5SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
5388480093f4SDimitry Andric       if (getCodeGenOpts().hasReducedDebugInfo())
53890b57cec5SDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
53900b57cec5SDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
53910b57cec5SDimitry Andric     break;
53920b57cec5SDimitry Andric   }
53930b57cec5SDimitry Andric   case Decl::ObjCMethod: {
53940b57cec5SDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
53950b57cec5SDimitry Andric     // If this is not a prototype, emit the body.
53960b57cec5SDimitry Andric     if (OMD->getBody())
53970b57cec5SDimitry Andric       CodeGenFunction(*this).GenerateObjCMethod(OMD);
53980b57cec5SDimitry Andric     break;
53990b57cec5SDimitry Andric   }
54000b57cec5SDimitry Andric   case Decl::ObjCCompatibleAlias:
54010b57cec5SDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
54020b57cec5SDimitry Andric     break;
54030b57cec5SDimitry Andric 
54040b57cec5SDimitry Andric   case Decl::PragmaComment: {
54050b57cec5SDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
54060b57cec5SDimitry Andric     switch (PCD->getCommentKind()) {
54070b57cec5SDimitry Andric     case PCK_Unknown:
54080b57cec5SDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
54090b57cec5SDimitry Andric     case PCK_Linker:
54100b57cec5SDimitry Andric       AppendLinkerOptions(PCD->getArg());
54110b57cec5SDimitry Andric       break;
54120b57cec5SDimitry Andric     case PCK_Lib:
54130b57cec5SDimitry Andric         AddDependentLib(PCD->getArg());
54140b57cec5SDimitry Andric       break;
54150b57cec5SDimitry Andric     case PCK_Compiler:
54160b57cec5SDimitry Andric     case PCK_ExeStr:
54170b57cec5SDimitry Andric     case PCK_User:
54180b57cec5SDimitry Andric       break; // We ignore all of these.
54190b57cec5SDimitry Andric     }
54200b57cec5SDimitry Andric     break;
54210b57cec5SDimitry Andric   }
54220b57cec5SDimitry Andric 
54230b57cec5SDimitry Andric   case Decl::PragmaDetectMismatch: {
54240b57cec5SDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
54250b57cec5SDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
54260b57cec5SDimitry Andric     break;
54270b57cec5SDimitry Andric   }
54280b57cec5SDimitry Andric 
54290b57cec5SDimitry Andric   case Decl::LinkageSpec:
54300b57cec5SDimitry Andric     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
54310b57cec5SDimitry Andric     break;
54320b57cec5SDimitry Andric 
54330b57cec5SDimitry Andric   case Decl::FileScopeAsm: {
54340b57cec5SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
54350b57cec5SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
54360b57cec5SDimitry Andric       break;
54370b57cec5SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
54380b57cec5SDimitry Andric     if (LangOpts.OpenMPIsDevice)
54390b57cec5SDimitry Andric       break;
54400b57cec5SDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
54410b57cec5SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
54420b57cec5SDimitry Andric     break;
54430b57cec5SDimitry Andric   }
54440b57cec5SDimitry Andric 
54450b57cec5SDimitry Andric   case Decl::Import: {
54460b57cec5SDimitry Andric     auto *Import = cast<ImportDecl>(D);
54470b57cec5SDimitry Andric 
54480b57cec5SDimitry Andric     // If we've already imported this module, we're done.
54490b57cec5SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
54500b57cec5SDimitry Andric       break;
54510b57cec5SDimitry Andric 
54520b57cec5SDimitry Andric     // Emit debug information for direct imports.
54530b57cec5SDimitry Andric     if (!Import->getImportedOwningModule()) {
54540b57cec5SDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
54550b57cec5SDimitry Andric         DI->EmitImportDecl(*Import);
54560b57cec5SDimitry Andric     }
54570b57cec5SDimitry Andric 
54580b57cec5SDimitry Andric     // Find all of the submodules and emit the module initializers.
54590b57cec5SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
54600b57cec5SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
54610b57cec5SDimitry Andric     Visited.insert(Import->getImportedModule());
54620b57cec5SDimitry Andric     Stack.push_back(Import->getImportedModule());
54630b57cec5SDimitry Andric 
54640b57cec5SDimitry Andric     while (!Stack.empty()) {
54650b57cec5SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
54660b57cec5SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
54670b57cec5SDimitry Andric         continue;
54680b57cec5SDimitry Andric 
54690b57cec5SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
54700b57cec5SDimitry Andric         EmitTopLevelDecl(D);
54710b57cec5SDimitry Andric 
54720b57cec5SDimitry Andric       // Visit the submodules of this module.
54730b57cec5SDimitry Andric       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
54740b57cec5SDimitry Andric                                              SubEnd = Mod->submodule_end();
54750b57cec5SDimitry Andric            Sub != SubEnd; ++Sub) {
54760b57cec5SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
54770b57cec5SDimitry Andric         // the initializers.
54780b57cec5SDimitry Andric         if ((*Sub)->IsExplicit)
54790b57cec5SDimitry Andric           continue;
54800b57cec5SDimitry Andric 
54810b57cec5SDimitry Andric         if (Visited.insert(*Sub).second)
54820b57cec5SDimitry Andric           Stack.push_back(*Sub);
54830b57cec5SDimitry Andric       }
54840b57cec5SDimitry Andric     }
54850b57cec5SDimitry Andric     break;
54860b57cec5SDimitry Andric   }
54870b57cec5SDimitry Andric 
54880b57cec5SDimitry Andric   case Decl::Export:
54890b57cec5SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
54900b57cec5SDimitry Andric     break;
54910b57cec5SDimitry Andric 
54920b57cec5SDimitry Andric   case Decl::OMPThreadPrivate:
54930b57cec5SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
54940b57cec5SDimitry Andric     break;
54950b57cec5SDimitry Andric 
54960b57cec5SDimitry Andric   case Decl::OMPAllocate:
54970b57cec5SDimitry Andric     break;
54980b57cec5SDimitry Andric 
54990b57cec5SDimitry Andric   case Decl::OMPDeclareReduction:
55000b57cec5SDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
55010b57cec5SDimitry Andric     break;
55020b57cec5SDimitry Andric 
55030b57cec5SDimitry Andric   case Decl::OMPDeclareMapper:
55040b57cec5SDimitry Andric     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
55050b57cec5SDimitry Andric     break;
55060b57cec5SDimitry Andric 
55070b57cec5SDimitry Andric   case Decl::OMPRequires:
55080b57cec5SDimitry Andric     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
55090b57cec5SDimitry Andric     break;
55100b57cec5SDimitry Andric 
55110b57cec5SDimitry Andric   default:
55120b57cec5SDimitry Andric     // Make sure we handled everything we should, every other kind is a
55130b57cec5SDimitry Andric     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
55140b57cec5SDimitry Andric     // function. Need to recode Decl::Kind to do that easily.
55150b57cec5SDimitry Andric     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
55160b57cec5SDimitry Andric     break;
55170b57cec5SDimitry Andric   }
55180b57cec5SDimitry Andric }
55190b57cec5SDimitry Andric 
55200b57cec5SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
55210b57cec5SDimitry Andric   // Do we need to generate coverage mapping?
55220b57cec5SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
55230b57cec5SDimitry Andric     return;
55240b57cec5SDimitry Andric   switch (D->getKind()) {
55250b57cec5SDimitry Andric   case Decl::CXXConversion:
55260b57cec5SDimitry Andric   case Decl::CXXMethod:
55270b57cec5SDimitry Andric   case Decl::Function:
55280b57cec5SDimitry Andric   case Decl::ObjCMethod:
55290b57cec5SDimitry Andric   case Decl::CXXConstructor:
55300b57cec5SDimitry Andric   case Decl::CXXDestructor: {
55310b57cec5SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
55320b57cec5SDimitry Andric       return;
55330b57cec5SDimitry Andric     SourceManager &SM = getContext().getSourceManager();
55340b57cec5SDimitry Andric     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
55350b57cec5SDimitry Andric       return;
55360b57cec5SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
55370b57cec5SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
55380b57cec5SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
55390b57cec5SDimitry Andric     break;
55400b57cec5SDimitry Andric   }
55410b57cec5SDimitry Andric   default:
55420b57cec5SDimitry Andric     break;
55430b57cec5SDimitry Andric   };
55440b57cec5SDimitry Andric }
55450b57cec5SDimitry Andric 
55460b57cec5SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
55470b57cec5SDimitry Andric   // Do we need to generate coverage mapping?
55480b57cec5SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
55490b57cec5SDimitry Andric     return;
55500b57cec5SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
55510b57cec5SDimitry Andric     if (Fn->isTemplateInstantiation())
55520b57cec5SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
55530b57cec5SDimitry Andric   }
55540b57cec5SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
55550b57cec5SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
55560b57cec5SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
55570b57cec5SDimitry Andric   else
55580b57cec5SDimitry Andric     I->second = false;
55590b57cec5SDimitry Andric }
55600b57cec5SDimitry Andric 
55610b57cec5SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
55620b57cec5SDimitry Andric   // We call takeVector() here to avoid use-after-free.
55630b57cec5SDimitry Andric   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
55640b57cec5SDimitry Andric   // we deserialize function bodies to emit coverage info for them, and that
55650b57cec5SDimitry Andric   // deserializes more declarations. How should we handle that case?
55660b57cec5SDimitry Andric   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
55670b57cec5SDimitry Andric     if (!Entry.second)
55680b57cec5SDimitry Andric       continue;
55690b57cec5SDimitry Andric     const Decl *D = Entry.first;
55700b57cec5SDimitry Andric     switch (D->getKind()) {
55710b57cec5SDimitry Andric     case Decl::CXXConversion:
55720b57cec5SDimitry Andric     case Decl::CXXMethod:
55730b57cec5SDimitry Andric     case Decl::Function:
55740b57cec5SDimitry Andric     case Decl::ObjCMethod: {
55750b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
55760b57cec5SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
55770b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
55780b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
55790b57cec5SDimitry Andric       break;
55800b57cec5SDimitry Andric     }
55810b57cec5SDimitry Andric     case Decl::CXXConstructor: {
55820b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
55830b57cec5SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
55840b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
55850b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
55860b57cec5SDimitry Andric       break;
55870b57cec5SDimitry Andric     }
55880b57cec5SDimitry Andric     case Decl::CXXDestructor: {
55890b57cec5SDimitry Andric       CodeGenPGO PGO(*this);
55900b57cec5SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
55910b57cec5SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
55920b57cec5SDimitry Andric                                   getFunctionLinkage(GD));
55930b57cec5SDimitry Andric       break;
55940b57cec5SDimitry Andric     }
55950b57cec5SDimitry Andric     default:
55960b57cec5SDimitry Andric       break;
55970b57cec5SDimitry Andric     };
55980b57cec5SDimitry Andric   }
55990b57cec5SDimitry Andric }
56000b57cec5SDimitry Andric 
56010b57cec5SDimitry Andric /// Turns the given pointer into a constant.
56020b57cec5SDimitry Andric static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
56030b57cec5SDimitry Andric                                           const void *Ptr) {
56040b57cec5SDimitry Andric   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
56050b57cec5SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
56060b57cec5SDimitry Andric   return llvm::ConstantInt::get(i64, PtrInt);
56070b57cec5SDimitry Andric }
56080b57cec5SDimitry Andric 
56090b57cec5SDimitry Andric static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
56100b57cec5SDimitry Andric                                    llvm::NamedMDNode *&GlobalMetadata,
56110b57cec5SDimitry Andric                                    GlobalDecl D,
56120b57cec5SDimitry Andric                                    llvm::GlobalValue *Addr) {
56130b57cec5SDimitry Andric   if (!GlobalMetadata)
56140b57cec5SDimitry Andric     GlobalMetadata =
56150b57cec5SDimitry Andric       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
56160b57cec5SDimitry Andric 
56170b57cec5SDimitry Andric   // TODO: should we report variant information for ctors/dtors?
56180b57cec5SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
56190b57cec5SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
56200b57cec5SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
56210b57cec5SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
56220b57cec5SDimitry Andric }
56230b57cec5SDimitry Andric 
56240b57cec5SDimitry Andric /// For each function which is declared within an extern "C" region and marked
56250b57cec5SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
56260b57cec5SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
56270b57cec5SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
56280b57cec5SDimitry Andric /// same translation unit.
56290b57cec5SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
56300b57cec5SDimitry Andric   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
56310b57cec5SDimitry Andric     return;
56320b57cec5SDimitry Andric   for (auto &I : StaticExternCValues) {
56330b57cec5SDimitry Andric     IdentifierInfo *Name = I.first;
56340b57cec5SDimitry Andric     llvm::GlobalValue *Val = I.second;
56350b57cec5SDimitry Andric     if (Val && !getModule().getNamedValue(Name->getName()))
56360b57cec5SDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
56370b57cec5SDimitry Andric   }
56380b57cec5SDimitry Andric }
56390b57cec5SDimitry Andric 
56400b57cec5SDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
56410b57cec5SDimitry Andric                                              GlobalDecl &Result) const {
56420b57cec5SDimitry Andric   auto Res = Manglings.find(MangledName);
56430b57cec5SDimitry Andric   if (Res == Manglings.end())
56440b57cec5SDimitry Andric     return false;
56450b57cec5SDimitry Andric   Result = Res->getValue();
56460b57cec5SDimitry Andric   return true;
56470b57cec5SDimitry Andric }
56480b57cec5SDimitry Andric 
56490b57cec5SDimitry Andric /// Emits metadata nodes associating all the global values in the
56500b57cec5SDimitry Andric /// current module with the Decls they came from.  This is useful for
56510b57cec5SDimitry Andric /// projects using IR gen as a subroutine.
56520b57cec5SDimitry Andric ///
56530b57cec5SDimitry Andric /// Since there's currently no way to associate an MDNode directly
56540b57cec5SDimitry Andric /// with an llvm::GlobalValue, we create a global named metadata
56550b57cec5SDimitry Andric /// with the name 'clang.global.decl.ptrs'.
56560b57cec5SDimitry Andric void CodeGenModule::EmitDeclMetadata() {
56570b57cec5SDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
56580b57cec5SDimitry Andric 
56590b57cec5SDimitry Andric   for (auto &I : MangledDeclNames) {
56600b57cec5SDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
56610b57cec5SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
56620b57cec5SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
56630b57cec5SDimitry Andric     if (Addr)
56640b57cec5SDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
56650b57cec5SDimitry Andric   }
56660b57cec5SDimitry Andric }
56670b57cec5SDimitry Andric 
56680b57cec5SDimitry Andric /// Emits metadata nodes for all the local variables in the current
56690b57cec5SDimitry Andric /// function.
56700b57cec5SDimitry Andric void CodeGenFunction::EmitDeclMetadata() {
56710b57cec5SDimitry Andric   if (LocalDeclMap.empty()) return;
56720b57cec5SDimitry Andric 
56730b57cec5SDimitry Andric   llvm::LLVMContext &Context = getLLVMContext();
56740b57cec5SDimitry Andric 
56750b57cec5SDimitry Andric   // Find the unique metadata ID for this name.
56760b57cec5SDimitry Andric   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
56770b57cec5SDimitry Andric 
56780b57cec5SDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
56790b57cec5SDimitry Andric 
56800b57cec5SDimitry Andric   for (auto &I : LocalDeclMap) {
56810b57cec5SDimitry Andric     const Decl *D = I.first;
56820b57cec5SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
56830b57cec5SDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
56840b57cec5SDimitry Andric       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
56850b57cec5SDimitry Andric       Alloca->setMetadata(
56860b57cec5SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
56870b57cec5SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
56880b57cec5SDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
56890b57cec5SDimitry Andric       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
56900b57cec5SDimitry Andric       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
56910b57cec5SDimitry Andric     }
56920b57cec5SDimitry Andric   }
56930b57cec5SDimitry Andric }
56940b57cec5SDimitry Andric 
56950b57cec5SDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
56960b57cec5SDimitry Andric   llvm::NamedMDNode *IdentMetadata =
56970b57cec5SDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
56980b57cec5SDimitry Andric   std::string Version = getClangFullVersion();
56990b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
57000b57cec5SDimitry Andric 
57010b57cec5SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
57020b57cec5SDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
57030b57cec5SDimitry Andric }
57040b57cec5SDimitry Andric 
57050b57cec5SDimitry Andric void CodeGenModule::EmitCommandLineMetadata() {
57060b57cec5SDimitry Andric   llvm::NamedMDNode *CommandLineMetadata =
57070b57cec5SDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.commandline");
57080b57cec5SDimitry Andric   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
57090b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
57100b57cec5SDimitry Andric 
57110b57cec5SDimitry Andric   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
57120b57cec5SDimitry Andric   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
57130b57cec5SDimitry Andric }
57140b57cec5SDimitry Andric 
57150b57cec5SDimitry Andric void CodeGenModule::EmitTargetMetadata() {
57160b57cec5SDimitry Andric   // Warning, new MangledDeclNames may be appended within this loop.
57170b57cec5SDimitry Andric   // We rely on MapVector insertions adding new elements to the end
57180b57cec5SDimitry Andric   // of the container.
57190b57cec5SDimitry Andric   // FIXME: Move this loop into the one target that needs it, and only
57200b57cec5SDimitry Andric   // loop over those declarations for which we couldn't emit the target
57210b57cec5SDimitry Andric   // metadata when we emitted the declaration.
57220b57cec5SDimitry Andric   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
57230b57cec5SDimitry Andric     auto Val = *(MangledDeclNames.begin() + I);
57240b57cec5SDimitry Andric     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
57250b57cec5SDimitry Andric     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
57260b57cec5SDimitry Andric     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
57270b57cec5SDimitry Andric   }
57280b57cec5SDimitry Andric }
57290b57cec5SDimitry Andric 
57300b57cec5SDimitry Andric void CodeGenModule::EmitCoverageFile() {
57310b57cec5SDimitry Andric   if (getCodeGenOpts().CoverageDataFile.empty() &&
57320b57cec5SDimitry Andric       getCodeGenOpts().CoverageNotesFile.empty())
57330b57cec5SDimitry Andric     return;
57340b57cec5SDimitry Andric 
57350b57cec5SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
57360b57cec5SDimitry Andric   if (!CUNode)
57370b57cec5SDimitry Andric     return;
57380b57cec5SDimitry Andric 
57390b57cec5SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
57400b57cec5SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
57410b57cec5SDimitry Andric   auto *CoverageDataFile =
57420b57cec5SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
57430b57cec5SDimitry Andric   auto *CoverageNotesFile =
57440b57cec5SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
57450b57cec5SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
57460b57cec5SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
57470b57cec5SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
57480b57cec5SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
57490b57cec5SDimitry Andric   }
57500b57cec5SDimitry Andric }
57510b57cec5SDimitry Andric 
57520b57cec5SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
57530b57cec5SDimitry Andric   // Sema has checked that all uuid strings are of the form
57540b57cec5SDimitry Andric   // "12345678-1234-1234-1234-1234567890ab".
57550b57cec5SDimitry Andric   assert(Uuid.size() == 36);
57560b57cec5SDimitry Andric   for (unsigned i = 0; i < 36; ++i) {
57570b57cec5SDimitry Andric     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
57580b57cec5SDimitry Andric     else                                         assert(isHexDigit(Uuid[i]));
57590b57cec5SDimitry Andric   }
57600b57cec5SDimitry Andric 
57610b57cec5SDimitry Andric   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
57620b57cec5SDimitry Andric   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
57630b57cec5SDimitry Andric 
57640b57cec5SDimitry Andric   llvm::Constant *Field3[8];
57650b57cec5SDimitry Andric   for (unsigned Idx = 0; Idx < 8; ++Idx)
57660b57cec5SDimitry Andric     Field3[Idx] = llvm::ConstantInt::get(
57670b57cec5SDimitry Andric         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
57680b57cec5SDimitry Andric 
57690b57cec5SDimitry Andric   llvm::Constant *Fields[4] = {
57700b57cec5SDimitry Andric     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
57710b57cec5SDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
57720b57cec5SDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
57730b57cec5SDimitry Andric     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
57740b57cec5SDimitry Andric   };
57750b57cec5SDimitry Andric 
57760b57cec5SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
57770b57cec5SDimitry Andric }
57780b57cec5SDimitry Andric 
57790b57cec5SDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
57800b57cec5SDimitry Andric                                                        bool ForEH) {
57810b57cec5SDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
57820b57cec5SDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
57830b57cec5SDimitry Andric   // and it's not for EH?
57840b57cec5SDimitry Andric   if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
57850b57cec5SDimitry Andric     return llvm::Constant::getNullValue(Int8PtrTy);
57860b57cec5SDimitry Andric 
57870b57cec5SDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
57880b57cec5SDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
57890b57cec5SDimitry Andric     return ObjCRuntime->GetEHType(Ty);
57900b57cec5SDimitry Andric 
57910b57cec5SDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
57920b57cec5SDimitry Andric }
57930b57cec5SDimitry Andric 
57940b57cec5SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
57950b57cec5SDimitry Andric   // Do not emit threadprivates in simd-only mode.
57960b57cec5SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
57970b57cec5SDimitry Andric     return;
57980b57cec5SDimitry Andric   for (auto RefExpr : D->varlists()) {
57990b57cec5SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
58000b57cec5SDimitry Andric     bool PerformInit =
58010b57cec5SDimitry Andric         VD->getAnyInitializer() &&
58020b57cec5SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
58030b57cec5SDimitry Andric                                                         /*ForRef=*/false);
58040b57cec5SDimitry Andric 
58050b57cec5SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
58060b57cec5SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
58070b57cec5SDimitry Andric             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
58080b57cec5SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
58090b57cec5SDimitry Andric   }
58100b57cec5SDimitry Andric }
58110b57cec5SDimitry Andric 
58120b57cec5SDimitry Andric llvm::Metadata *
58130b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
58140b57cec5SDimitry Andric                                             StringRef Suffix) {
58150b57cec5SDimitry Andric   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
58160b57cec5SDimitry Andric   if (InternalId)
58170b57cec5SDimitry Andric     return InternalId;
58180b57cec5SDimitry Andric 
58190b57cec5SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
58200b57cec5SDimitry Andric     std::string OutName;
58210b57cec5SDimitry Andric     llvm::raw_string_ostream Out(OutName);
58220b57cec5SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
58230b57cec5SDimitry Andric     Out << Suffix;
58240b57cec5SDimitry Andric 
58250b57cec5SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
58260b57cec5SDimitry Andric   } else {
58270b57cec5SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
58280b57cec5SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
58290b57cec5SDimitry Andric   }
58300b57cec5SDimitry Andric 
58310b57cec5SDimitry Andric   return InternalId;
58320b57cec5SDimitry Andric }
58330b57cec5SDimitry Andric 
58340b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
58350b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
58360b57cec5SDimitry Andric }
58370b57cec5SDimitry Andric 
58380b57cec5SDimitry Andric llvm::Metadata *
58390b57cec5SDimitry Andric CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
58400b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
58410b57cec5SDimitry Andric }
58420b57cec5SDimitry Andric 
58430b57cec5SDimitry Andric // Generalize pointer types to a void pointer with the qualifiers of the
58440b57cec5SDimitry Andric // originally pointed-to type, e.g. 'const char *' and 'char * const *'
58450b57cec5SDimitry Andric // generalize to 'const void *' while 'char *' and 'const char **' generalize to
58460b57cec5SDimitry Andric // 'void *'.
58470b57cec5SDimitry Andric static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
58480b57cec5SDimitry Andric   if (!Ty->isPointerType())
58490b57cec5SDimitry Andric     return Ty;
58500b57cec5SDimitry Andric 
58510b57cec5SDimitry Andric   return Ctx.getPointerType(
58520b57cec5SDimitry Andric       QualType(Ctx.VoidTy).withCVRQualifiers(
58530b57cec5SDimitry Andric           Ty->getPointeeType().getCVRQualifiers()));
58540b57cec5SDimitry Andric }
58550b57cec5SDimitry Andric 
58560b57cec5SDimitry Andric // Apply type generalization to a FunctionType's return and argument types
58570b57cec5SDimitry Andric static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
58580b57cec5SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
58590b57cec5SDimitry Andric     SmallVector<QualType, 8> GeneralizedParams;
58600b57cec5SDimitry Andric     for (auto &Param : FnType->param_types())
58610b57cec5SDimitry Andric       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
58620b57cec5SDimitry Andric 
58630b57cec5SDimitry Andric     return Ctx.getFunctionType(
58640b57cec5SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()),
58650b57cec5SDimitry Andric         GeneralizedParams, FnType->getExtProtoInfo());
58660b57cec5SDimitry Andric   }
58670b57cec5SDimitry Andric 
58680b57cec5SDimitry Andric   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
58690b57cec5SDimitry Andric     return Ctx.getFunctionNoProtoType(
58700b57cec5SDimitry Andric         GeneralizeType(Ctx, FnType->getReturnType()));
58710b57cec5SDimitry Andric 
58720b57cec5SDimitry Andric   llvm_unreachable("Encountered unknown FunctionType");
58730b57cec5SDimitry Andric }
58740b57cec5SDimitry Andric 
58750b57cec5SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
58760b57cec5SDimitry Andric   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
58770b57cec5SDimitry Andric                                       GeneralizedMetadataIdMap, ".generalized");
58780b57cec5SDimitry Andric }
58790b57cec5SDimitry Andric 
58800b57cec5SDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
58810b57cec5SDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
58820b57cec5SDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
58830b57cec5SDimitry Andric   // is not in the trapping mode.
58840b57cec5SDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
58850b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
58860b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
58870b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
58880b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
58890b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
58900b57cec5SDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
58910b57cec5SDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
58920b57cec5SDimitry Andric }
58930b57cec5SDimitry Andric 
58940b57cec5SDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
58950b57cec5SDimitry Andric                                           CharUnits Offset,
58960b57cec5SDimitry Andric                                           const CXXRecordDecl *RD) {
58970b57cec5SDimitry Andric   llvm::Metadata *MD =
58980b57cec5SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
58990b57cec5SDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
59000b57cec5SDimitry Andric 
59010b57cec5SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
59020b57cec5SDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
59030b57cec5SDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
59040b57cec5SDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
59050b57cec5SDimitry Andric 
59060b57cec5SDimitry Andric   if (NeedAllVtablesTypeId()) {
59070b57cec5SDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
59080b57cec5SDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
59090b57cec5SDimitry Andric   }
59100b57cec5SDimitry Andric }
59110b57cec5SDimitry Andric 
59120b57cec5SDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
59130b57cec5SDimitry Andric   if (!SanStats)
5914a7dea167SDimitry Andric     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
59150b57cec5SDimitry Andric 
59160b57cec5SDimitry Andric   return *SanStats;
59170b57cec5SDimitry Andric }
59180b57cec5SDimitry Andric llvm::Value *
59190b57cec5SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
59200b57cec5SDimitry Andric                                                   CodeGenFunction &CGF) {
59210b57cec5SDimitry Andric   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
59220b57cec5SDimitry Andric   auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
59230b57cec5SDimitry Andric   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
59240b57cec5SDimitry Andric   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
59250b57cec5SDimitry Andric                                 "__translate_sampler_initializer"),
59260b57cec5SDimitry Andric                                 {C});
59270b57cec5SDimitry Andric }
5928