1488a800aSTeresa Johnson //===- lib/Transforms/Utils/FunctionImportUtils.cpp - Importing utilities -===// 2488a800aSTeresa Johnson // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6488a800aSTeresa Johnson // 7488a800aSTeresa Johnson //===----------------------------------------------------------------------===// 8488a800aSTeresa Johnson // 9488a800aSTeresa Johnson // This file implements the FunctionImportGlobalProcessing class, used 10488a800aSTeresa Johnson // to perform the necessary global value handling for function importing. 11488a800aSTeresa Johnson // 12488a800aSTeresa Johnson //===----------------------------------------------------------------------===// 13488a800aSTeresa Johnson 14488a800aSTeresa Johnson #include "llvm/Transforms/Utils/FunctionImportUtils.h" 157f92d66fSevgeny #include "llvm/IR/Constants.h" 16df5ef871STeresa Johnson #include "llvm/IR/InstIterator.h" 17488a800aSTeresa Johnson using namespace llvm; 18488a800aSTeresa Johnson 19488a800aSTeresa Johnson /// Checks if we should import SGV as a definition, otherwise import as a 20488a800aSTeresa Johnson /// declaration. 21488a800aSTeresa Johnson bool FunctionImportGlobalProcessing::doImportAsDefinition( 22cc1b0bc2STeresa Johnson const GlobalValue *SGV) { 23cc1b0bc2STeresa Johnson if (!isPerformingImport()) 24cc1b0bc2STeresa Johnson return false; 258d05185aSMehdi Amini 268d05185aSMehdi Amini // Only import the globals requested for importing. 2772c0b1ccSDavid Blaikie if (!GlobalsToImport->count(const_cast<GlobalValue *>(SGV))) 2872c0b1ccSDavid Blaikie return false; 292f0cc477SDavid Blaikie 302f0cc477SDavid Blaikie assert(!isa<GlobalAlias>(SGV) && 312f0cc477SDavid Blaikie "Unexpected global alias in the import list."); 322f0cc477SDavid Blaikie 3372c0b1ccSDavid Blaikie // Otherwise yes. 3472c0b1ccSDavid Blaikie return true; 35488a800aSTeresa Johnson } 36488a800aSTeresa Johnson 3738d4df71STeresa Johnson bool FunctionImportGlobalProcessing::shouldPromoteLocalToGlobal( 38cc1b0bc2STeresa Johnson const GlobalValue *SGV, ValueInfo VI) { 39488a800aSTeresa Johnson assert(SGV->hasLocalLinkage()); 40488a800aSTeresa Johnson // Both the imported references and the original local variable must 41488a800aSTeresa Johnson // be promoted. 42488a800aSTeresa Johnson if (!isPerformingImport() && !isModuleExporting()) 43488a800aSTeresa Johnson return false; 44488a800aSTeresa Johnson 454fef68cbSTeresa Johnson if (isPerformingImport()) { 466d8f817fSPeter Collingbourne assert((!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)) || 476d8f817fSPeter Collingbourne !isNonRenamableLocal(*SGV)) && 48519465b9STeresa Johnson "Attempting to promote non-renamable local"); 494fef68cbSTeresa Johnson // We don't know for sure yet if we are importing this value (as either 504fef68cbSTeresa Johnson // a reference or a def), since we are simply walking all values in the 514fef68cbSTeresa Johnson // module. But by necessity if we end up importing it and it is local, 524fef68cbSTeresa Johnson // it must be promoted, so unconditionally promote all values in the 534fef68cbSTeresa Johnson // importing module. 544fef68cbSTeresa Johnson return true; 550515fb8dSTeresa Johnson } 56b4e1e829SMehdi Amini 579006d526STeresa Johnson // When exporting, consult the index. We can have more than one local 589006d526STeresa Johnson // with the same GUID, in the case of same-named locals in different but 599006d526STeresa Johnson // same-named source files that were compiled in their respective directories 609006d526STeresa Johnson // (so the source file name and resulting GUID is the same). Find the one 619006d526STeresa Johnson // in this module. 629006d526STeresa Johnson auto Summary = ImportIndex.findSummaryInModule( 63cc1b0bc2STeresa Johnson VI, SGV->getParent()->getModuleIdentifier()); 649006d526STeresa Johnson assert(Summary && "Missing summary for global value when exporting"); 659006d526STeresa Johnson auto Linkage = Summary->linkage(); 664fef68cbSTeresa Johnson if (!GlobalValue::isLocalLinkage(Linkage)) { 67519465b9STeresa Johnson assert(!isNonRenamableLocal(*SGV) && 68519465b9STeresa Johnson "Attempting to promote non-renamable local"); 69488a800aSTeresa Johnson return true; 70488a800aSTeresa Johnson } 71488a800aSTeresa Johnson 724fef68cbSTeresa Johnson return false; 734fef68cbSTeresa Johnson } 744fef68cbSTeresa Johnson 75519465b9STeresa Johnson #ifndef NDEBUG 76519465b9STeresa Johnson bool FunctionImportGlobalProcessing::isNonRenamableLocal( 77519465b9STeresa Johnson const GlobalValue &GV) const { 78519465b9STeresa Johnson if (!GV.hasLocalLinkage()) 79519465b9STeresa Johnson return false; 80519465b9STeresa Johnson // This needs to stay in sync with the logic in buildModuleSummaryIndex. 81519465b9STeresa Johnson if (GV.hasSection()) 82519465b9STeresa Johnson return true; 83519465b9STeresa Johnson if (Used.count(const_cast<GlobalValue *>(&GV))) 84519465b9STeresa Johnson return true; 85519465b9STeresa Johnson return false; 86519465b9STeresa Johnson } 87519465b9STeresa Johnson #endif 88519465b9STeresa Johnson 893be6dbcaSTeresa Johnson std::string 903be6dbcaSTeresa Johnson FunctionImportGlobalProcessing::getPromotedName(const GlobalValue *SGV) { 913be6dbcaSTeresa Johnson assert(SGV->hasLocalLinkage()); 92488a800aSTeresa Johnson // For locals that must be promoted to global scope, ensure that 93488a800aSTeresa Johnson // the promoted name uniquely identifies the copy in the original module, 943be6dbcaSTeresa Johnson // using the ID assigned during combined index creation. 9526ab5772STeresa Johnson return ModuleSummaryIndex::getGlobalNameForLocal( 96488a800aSTeresa Johnson SGV->getName(), 97ae280e54SMehdi Amini ImportIndex.getModuleHash(SGV->getParent()->getModuleIdentifier())); 98488a800aSTeresa Johnson } 99488a800aSTeresa Johnson 100488a800aSTeresa Johnson GlobalValue::LinkageTypes 1011b9c2be8STeresa Johnson FunctionImportGlobalProcessing::getLinkage(const GlobalValue *SGV, 1021b9c2be8STeresa Johnson bool DoPromote) { 103488a800aSTeresa Johnson // Any local variable that is referenced by an exported function needs 104488a800aSTeresa Johnson // to be promoted to global scope. Since we don't currently know which 105488a800aSTeresa Johnson // functions reference which local variables/functions, we must treat 106488a800aSTeresa Johnson // all as potentially exported if this module is exporting anything. 107488a800aSTeresa Johnson if (isModuleExporting()) { 1081b9c2be8STeresa Johnson if (SGV->hasLocalLinkage() && DoPromote) 109488a800aSTeresa Johnson return GlobalValue::ExternalLinkage; 110488a800aSTeresa Johnson return SGV->getLinkage(); 111488a800aSTeresa Johnson } 112488a800aSTeresa Johnson 113488a800aSTeresa Johnson // Otherwise, if we aren't importing, no linkage change is needed. 114488a800aSTeresa Johnson if (!isPerformingImport()) 115488a800aSTeresa Johnson return SGV->getLinkage(); 116488a800aSTeresa Johnson 117488a800aSTeresa Johnson switch (SGV->getLinkage()) { 1182f0cc477SDavid Blaikie case GlobalValue::LinkOnceODRLinkage: 119488a800aSTeresa Johnson case GlobalValue::ExternalLinkage: 1202f0cc477SDavid Blaikie // External and linkonce definitions are converted to available_externally 121488a800aSTeresa Johnson // definitions upon import, so that they are available for inlining 122488a800aSTeresa Johnson // and/or optimization, but are turned into declarations later 123488a800aSTeresa Johnson // during the EliminateAvailableExternally pass. 1242c5c12c0SFangrui Song if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV)) 125488a800aSTeresa Johnson return GlobalValue::AvailableExternallyLinkage; 126488a800aSTeresa Johnson // An imported external declaration stays external. 127488a800aSTeresa Johnson return SGV->getLinkage(); 128488a800aSTeresa Johnson 129488a800aSTeresa Johnson case GlobalValue::AvailableExternallyLinkage: 130488a800aSTeresa Johnson // An imported available_externally definition converts 131488a800aSTeresa Johnson // to external if imported as a declaration. 132488a800aSTeresa Johnson if (!doImportAsDefinition(SGV)) 133488a800aSTeresa Johnson return GlobalValue::ExternalLinkage; 134488a800aSTeresa Johnson // An imported available_externally declaration stays that way. 135488a800aSTeresa Johnson return SGV->getLinkage(); 136488a800aSTeresa Johnson 13753e52e47SXin Tong case GlobalValue::LinkOnceAnyLinkage: 138488a800aSTeresa Johnson case GlobalValue::WeakAnyLinkage: 13953e52e47SXin Tong // Can't import linkonce_any/weak_any definitions correctly, or we might 14053e52e47SXin Tong // change the program semantics, since the linker will pick the first 14153e52e47SXin Tong // linkonce_any/weak_any definition and importing would change the order 14253e52e47SXin Tong // they are seen by the linker. The module linking caller needs to enforce 14353e52e47SXin Tong // this. 144488a800aSTeresa Johnson assert(!doImportAsDefinition(SGV)); 145488a800aSTeresa Johnson // If imported as a declaration, it becomes external_weak. 146bb3a1d92SMehdi Amini return SGV->getLinkage(); 147488a800aSTeresa Johnson 148488a800aSTeresa Johnson case GlobalValue::WeakODRLinkage: 149488a800aSTeresa Johnson // For weak_odr linkage, there is a guarantee that all copies will be 150488a800aSTeresa Johnson // equivalent, so the issue described above for weak_any does not exist, 151488a800aSTeresa Johnson // and the definition can be imported. It can be treated similarly 152488a800aSTeresa Johnson // to an imported externally visible global value. 1532c5c12c0SFangrui Song if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV)) 154488a800aSTeresa Johnson return GlobalValue::AvailableExternallyLinkage; 155488a800aSTeresa Johnson else 156488a800aSTeresa Johnson return GlobalValue::ExternalLinkage; 157488a800aSTeresa Johnson 158488a800aSTeresa Johnson case GlobalValue::AppendingLinkage: 159488a800aSTeresa Johnson // It would be incorrect to import an appending linkage variable, 160488a800aSTeresa Johnson // since it would cause global constructors/destructors to be 161488a800aSTeresa Johnson // executed multiple times. This should have already been handled 162488a800aSTeresa Johnson // by linkIfNeeded, and we will assert in shouldLinkFromSource 163488a800aSTeresa Johnson // if we try to import, so we simply return AppendingLinkage. 164488a800aSTeresa Johnson return GlobalValue::AppendingLinkage; 165488a800aSTeresa Johnson 166488a800aSTeresa Johnson case GlobalValue::InternalLinkage: 167488a800aSTeresa Johnson case GlobalValue::PrivateLinkage: 168488a800aSTeresa Johnson // If we are promoting the local to global scope, it is handled 169488a800aSTeresa Johnson // similarly to a normal externally visible global. 1701b9c2be8STeresa Johnson if (DoPromote) { 1712c5c12c0SFangrui Song if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV)) 172488a800aSTeresa Johnson return GlobalValue::AvailableExternallyLinkage; 173488a800aSTeresa Johnson else 174488a800aSTeresa Johnson return GlobalValue::ExternalLinkage; 175488a800aSTeresa Johnson } 176488a800aSTeresa Johnson // A non-promoted imported local definition stays local. 177488a800aSTeresa Johnson // The ThinLTO pass will eventually force-import their definitions. 178488a800aSTeresa Johnson return SGV->getLinkage(); 179488a800aSTeresa Johnson 180488a800aSTeresa Johnson case GlobalValue::ExternalWeakLinkage: 181488a800aSTeresa Johnson // External weak doesn't apply to definitions, must be a declaration. 182488a800aSTeresa Johnson assert(!doImportAsDefinition(SGV)); 183488a800aSTeresa Johnson // Linkage stays external_weak. 184488a800aSTeresa Johnson return SGV->getLinkage(); 185488a800aSTeresa Johnson 186488a800aSTeresa Johnson case GlobalValue::CommonLinkage: 187488a800aSTeresa Johnson // Linkage stays common on definitions. 188488a800aSTeresa Johnson // The ThinLTO pass will eventually force-import their definitions. 189488a800aSTeresa Johnson return SGV->getLinkage(); 190488a800aSTeresa Johnson } 191488a800aSTeresa Johnson 192488a800aSTeresa Johnson llvm_unreachable("unknown linkage type"); 193488a800aSTeresa Johnson } 194488a800aSTeresa Johnson 195488a800aSTeresa Johnson void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) { 1964595a915SSean Fertile 197bf46e741SEugene Leviant ValueInfo VI; 1984595a915SSean Fertile if (GV.hasName()) { 199bf46e741SEugene Leviant VI = ImportIndex.getValueInfo(GV.getGUID()); 2005a7056faSEaswaran Raman // Set synthetic function entry counts. 2015a7056faSEaswaran Raman if (VI && ImportIndex.hasSyntheticEntryCounts()) { 2025a7056faSEaswaran Raman if (Function *F = dyn_cast<Function>(&GV)) { 2035a7056faSEaswaran Raman if (!F->isDeclaration()) { 2045a7056faSEaswaran Raman for (auto &S : VI.getSummaryList()) { 205f71f23d1SSimon Pilgrim auto *FS = cast<FunctionSummary>(S->getBaseObject()); 2065a7056faSEaswaran Raman if (FS->modulePath() == M.getModuleIdentifier()) { 2075a7056faSEaswaran Raman F->setEntryCount(Function::ProfileCount(FS->entryCount(), 2085a7056faSEaswaran Raman Function::PCT_Synthetic)); 2095a7056faSEaswaran Raman break; 2105a7056faSEaswaran Raman } 2115a7056faSEaswaran Raman } 2125a7056faSEaswaran Raman } 2135a7056faSEaswaran Raman } 2145a7056faSEaswaran Raman } 2154595a915SSean Fertile } 2164595a915SSean Fertile 217cc1b0bc2STeresa Johnson // We should always have a ValueInfo (i.e. GV in index) for definitions when 218cc1b0bc2STeresa Johnson // we are exporting, and also when importing that value. 219cc1b0bc2STeresa Johnson assert(VI || GV.isDeclaration() || 220cc1b0bc2STeresa Johnson (isPerformingImport() && !doImportAsDefinition(&GV))); 221cc1b0bc2STeresa Johnson 2223aef3528SEugene Leviant // Mark read/write-only variables which can be imported with specific 2233aef3528SEugene Leviant // attribute. We can't internalize them now because IRMover will fail 2243aef3528SEugene Leviant // to link variable definitions to their external declarations during 2253aef3528SEugene Leviant // ThinLTO import. We'll internalize read-only variables later, after 2263aef3528SEugene Leviant // import is finished. See internalizeGVsAfterImport. 227bf46e741SEugene Leviant // 228bf46e741SEugene Leviant // If global value dead stripping is not enabled in summary then 229bf46e741SEugene Leviant // propagateConstants hasn't been run. We can't internalize GV 230bf46e741SEugene Leviant // in such case. 231dde58938Sevgeny if (!GV.isDeclaration() && VI && ImportIndex.withAttributePropagation()) { 23216ec00eeSTeresa Johnson if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) { 23316ec00eeSTeresa Johnson // We can have more than one local with the same GUID, in the case of 23416ec00eeSTeresa Johnson // same-named locals in different but same-named source files that were 23516ec00eeSTeresa Johnson // compiled in their respective directories (so the source file name 23616ec00eeSTeresa Johnson // and resulting GUID is the same). Find the one in this module. 23716ec00eeSTeresa Johnson // Handle the case where there is no summary found in this module. That 23816ec00eeSTeresa Johnson // can happen in the distributed ThinLTO backend, because the index only 23916ec00eeSTeresa Johnson // contains summaries from the source modules if they are being imported. 24016ec00eeSTeresa Johnson // We might have a non-null VI and get here even in that case if the name 24116ec00eeSTeresa Johnson // matches one in this module (e.g. weak or appending linkage). 24216ec00eeSTeresa Johnson auto *GVS = dyn_cast_or_null<GlobalVarSummary>( 24316ec00eeSTeresa Johnson ImportIndex.findSummaryInModule(VI, M.getModuleIdentifier())); 2447f92d66fSevgeny if (GVS && 2457f92d66fSevgeny (ImportIndex.isReadOnly(GVS) || ImportIndex.isWriteOnly(GVS))) { 24616ec00eeSTeresa Johnson V->addAttribute("thinlto-internalize"); 2477f92d66fSevgeny // Objects referenced by writeonly GV initializer should not be 2487f92d66fSevgeny // promoted, because there is no any kind of read access to them 2497f92d66fSevgeny // on behalf of this writeonly GV. To avoid promotion we convert 2507f92d66fSevgeny // GV initializer to 'zeroinitializer'. This effectively drops 2517f92d66fSevgeny // references in IR module (not in combined index), so we can 2527f92d66fSevgeny // ignore them when computing import. We do not export references 2537f92d66fSevgeny // of writeonly object. See computeImportForReferencedGlobals 254e420c0c7STeresa Johnson if (ImportIndex.isWriteOnly(GVS)) 2557f92d66fSevgeny V->setInitializer(Constant::getNullValue(V->getValueType())); 2567f92d66fSevgeny } 25716ec00eeSTeresa Johnson } 258bf46e741SEugene Leviant } 259bf46e741SEugene Leviant 260cc1b0bc2STeresa Johnson if (GV.hasLocalLinkage() && shouldPromoteLocalToGlobal(&GV, VI)) { 261f59242e5STeresa Johnson // Save the original name string before we rename GV below. 262f59242e5STeresa Johnson auto Name = GV.getName().str(); 2633be6dbcaSTeresa Johnson GV.setName(getPromotedName(&GV)); 2643be6dbcaSTeresa Johnson GV.setLinkage(getLinkage(&GV, /* DoPromote */ true)); 2653be6dbcaSTeresa Johnson assert(!GV.hasLocalLinkage()); 266488a800aSTeresa Johnson GV.setVisibility(GlobalValue::HiddenVisibility); 267f59242e5STeresa Johnson 268f59242e5STeresa Johnson // If we are renaming a COMDAT leader, ensure that we record the COMDAT 269f59242e5STeresa Johnson // for later renaming as well. This is required for COFF. 270f59242e5STeresa Johnson if (const auto *C = GV.getComdat()) 271f59242e5STeresa Johnson if (C->getName() == Name) 272f59242e5STeresa Johnson RenamedComdats.try_emplace(C, M.getOrInsertComdat(GV.getName())); 273488a800aSTeresa Johnson } else 2741b9c2be8STeresa Johnson GV.setLinkage(getLinkage(&GV, /* DoPromote */ false)); 275488a800aSTeresa Johnson 276d2ef8c1fSFangrui Song // When ClearDSOLocalOnDeclarations is true, clear dso_local if GV is 277d2ef8c1fSFangrui Song // converted to a declaration, to disable direct access. Don't do this if GV 278d2ef8c1fSFangrui Song // is implicitly dso_local due to a non-default visibility. 279*252a1eecSFangrui Song if (ClearDSOLocalOnDeclarations && 280*252a1eecSFangrui Song (GV.isDeclarationForLinker() || 281*252a1eecSFangrui Song (isPerformingImport() && !doImportAsDefinition(&GV))) && 282d2ef8c1fSFangrui Song !GV.isImplicitDSOLocal()) { 283d2ef8c1fSFangrui Song GV.setDSOLocal(false); 28480dc0661SWei Wang } else if (VI && VI.isDSOLocal(ImportIndex.withDSOLocalPropagation())) { 285d2ef8c1fSFangrui Song // If all summaries are dso_local, symbol gets resolved to a known local 286d2ef8c1fSFangrui Song // definition. 287d2ef8c1fSFangrui Song GV.setDSOLocal(true); 288d2ef8c1fSFangrui Song if (GV.hasDLLImportStorageClass()) 289d2ef8c1fSFangrui Song GV.setDLLStorageClass(GlobalValue::DefaultStorageClass); 290d2ef8c1fSFangrui Song } 291d2ef8c1fSFangrui Song 292488a800aSTeresa Johnson // Remove functions imported as available externally defs from comdats, 293488a800aSTeresa Johnson // as this is a declaration for the linker, and will be dropped eventually. 294488a800aSTeresa Johnson // It is illegal for comdats to contain declarations. 295bf46e741SEugene Leviant auto *GO = dyn_cast<GlobalObject>(&GV); 296488a800aSTeresa Johnson if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) { 297488a800aSTeresa Johnson // The IRMover should not have placed any imported declarations in 298488a800aSTeresa Johnson // a comdat, so the only declaration that should be in a comdat 299488a800aSTeresa Johnson // at this point would be a definition imported as available_externally. 300488a800aSTeresa Johnson assert(GO->hasAvailableExternallyLinkage() && 301488a800aSTeresa Johnson "Expected comdat on definition (possibly available external)"); 302488a800aSTeresa Johnson GO->setComdat(nullptr); 303488a800aSTeresa Johnson } 304488a800aSTeresa Johnson } 305488a800aSTeresa Johnson 306488a800aSTeresa Johnson void FunctionImportGlobalProcessing::processGlobalsForThinLTO() { 307488a800aSTeresa Johnson for (GlobalVariable &GV : M.globals()) 308488a800aSTeresa Johnson processGlobalForThinLTO(GV); 309488a800aSTeresa Johnson for (Function &SF : M) 310488a800aSTeresa Johnson processGlobalForThinLTO(SF); 311488a800aSTeresa Johnson for (GlobalAlias &GA : M.aliases()) 312488a800aSTeresa Johnson processGlobalForThinLTO(GA); 313f59242e5STeresa Johnson 314f59242e5STeresa Johnson // Replace any COMDATS that required renaming (because the COMDAT leader was 315f59242e5STeresa Johnson // promoted and renamed). 316f59242e5STeresa Johnson if (!RenamedComdats.empty()) 317f59242e5STeresa Johnson for (auto &GO : M.global_objects()) 318f59242e5STeresa Johnson if (auto *C = GO.getComdat()) { 319f59242e5STeresa Johnson auto Replacement = RenamedComdats.find(C); 320f59242e5STeresa Johnson if (Replacement != RenamedComdats.end()) 321f59242e5STeresa Johnson GO.setComdat(Replacement->second); 322f59242e5STeresa Johnson } 323488a800aSTeresa Johnson } 324488a800aSTeresa Johnson 325488a800aSTeresa Johnson bool FunctionImportGlobalProcessing::run() { 326488a800aSTeresa Johnson processGlobalsForThinLTO(); 327488a800aSTeresa Johnson return false; 328488a800aSTeresa Johnson } 329488a800aSTeresa Johnson 3306d8f817fSPeter Collingbourne bool llvm::renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, 331d2ef8c1fSFangrui Song bool ClearDSOLocalOnDeclarations, 3326d8f817fSPeter Collingbourne SetVector<GlobalValue *> *GlobalsToImport) { 333d2ef8c1fSFangrui Song FunctionImportGlobalProcessing ThinLTOProcessing(M, Index, GlobalsToImport, 334d2ef8c1fSFangrui Song ClearDSOLocalOnDeclarations); 335488a800aSTeresa Johnson return ThinLTOProcessing.run(); 336488a800aSTeresa Johnson } 337