xref: /openbsd-src/gnu/llvm/llvm/lib/Transforms/Utils/FunctionImportUtils.cpp (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
109467b48Spatrick //===- lib/Transforms/Utils/FunctionImportUtils.cpp - Importing utilities -===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file implements the FunctionImportGlobalProcessing class, used
1009467b48Spatrick // to perform the necessary global value handling for function importing.
1109467b48Spatrick //
1209467b48Spatrick //===----------------------------------------------------------------------===//
1309467b48Spatrick 
1409467b48Spatrick #include "llvm/Transforms/Utils/FunctionImportUtils.h"
15*d415bd75Srobert #include "llvm/Support/CommandLine.h"
1609467b48Spatrick using namespace llvm;
1709467b48Spatrick 
18*d415bd75Srobert /// Uses the "source_filename" instead of a Module hash ID for the suffix of
19*d415bd75Srobert /// promoted locals during LTO. NOTE: This requires that the source filename
20*d415bd75Srobert /// has a unique name / path to avoid name collisions.
21*d415bd75Srobert static cl::opt<bool> UseSourceFilenameForPromotedLocals(
22*d415bd75Srobert     "use-source-filename-for-promoted-locals", cl::Hidden,
23*d415bd75Srobert     cl::desc("Uses the source file name instead of the Module hash. "
24*d415bd75Srobert              "This requires that the source filename has a unique name / "
25*d415bd75Srobert              "path to avoid name collisions."));
26*d415bd75Srobert 
2709467b48Spatrick /// Checks if we should import SGV as a definition, otherwise import as a
2809467b48Spatrick /// declaration.
doImportAsDefinition(const GlobalValue * SGV)2909467b48Spatrick bool FunctionImportGlobalProcessing::doImportAsDefinition(
3009467b48Spatrick     const GlobalValue *SGV) {
3109467b48Spatrick   if (!isPerformingImport())
3209467b48Spatrick     return false;
3309467b48Spatrick 
3409467b48Spatrick   // Only import the globals requested for importing.
3509467b48Spatrick   if (!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)))
3609467b48Spatrick     return false;
3709467b48Spatrick 
3809467b48Spatrick   assert(!isa<GlobalAlias>(SGV) &&
3909467b48Spatrick          "Unexpected global alias in the import list.");
4009467b48Spatrick 
4109467b48Spatrick   // Otherwise yes.
4209467b48Spatrick   return true;
4309467b48Spatrick }
4409467b48Spatrick 
shouldPromoteLocalToGlobal(const GlobalValue * SGV,ValueInfo VI)4509467b48Spatrick bool FunctionImportGlobalProcessing::shouldPromoteLocalToGlobal(
4609467b48Spatrick     const GlobalValue *SGV, ValueInfo VI) {
4709467b48Spatrick   assert(SGV->hasLocalLinkage());
48*d415bd75Srobert 
49*d415bd75Srobert   // Ifuncs and ifunc alias does not have summary.
50*d415bd75Srobert   if (isa<GlobalIFunc>(SGV) ||
51*d415bd75Srobert       (isa<GlobalAlias>(SGV) &&
52*d415bd75Srobert        isa<GlobalIFunc>(cast<GlobalAlias>(SGV)->getAliaseeObject())))
53*d415bd75Srobert     return false;
54*d415bd75Srobert 
5509467b48Spatrick   // Both the imported references and the original local variable must
5609467b48Spatrick   // be promoted.
5709467b48Spatrick   if (!isPerformingImport() && !isModuleExporting())
5809467b48Spatrick     return false;
5909467b48Spatrick 
6009467b48Spatrick   if (isPerformingImport()) {
6109467b48Spatrick     assert((!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)) ||
6209467b48Spatrick             !isNonRenamableLocal(*SGV)) &&
6309467b48Spatrick            "Attempting to promote non-renamable local");
6409467b48Spatrick     // We don't know for sure yet if we are importing this value (as either
6509467b48Spatrick     // a reference or a def), since we are simply walking all values in the
6609467b48Spatrick     // module. But by necessity if we end up importing it and it is local,
6709467b48Spatrick     // it must be promoted, so unconditionally promote all values in the
6809467b48Spatrick     // importing module.
6909467b48Spatrick     return true;
7009467b48Spatrick   }
7109467b48Spatrick 
7209467b48Spatrick   // When exporting, consult the index. We can have more than one local
7309467b48Spatrick   // with the same GUID, in the case of same-named locals in different but
7409467b48Spatrick   // same-named source files that were compiled in their respective directories
7509467b48Spatrick   // (so the source file name and resulting GUID is the same). Find the one
7609467b48Spatrick   // in this module.
7709467b48Spatrick   auto Summary = ImportIndex.findSummaryInModule(
7809467b48Spatrick       VI, SGV->getParent()->getModuleIdentifier());
7909467b48Spatrick   assert(Summary && "Missing summary for global value when exporting");
8009467b48Spatrick   auto Linkage = Summary->linkage();
8109467b48Spatrick   if (!GlobalValue::isLocalLinkage(Linkage)) {
8209467b48Spatrick     assert(!isNonRenamableLocal(*SGV) &&
8309467b48Spatrick            "Attempting to promote non-renamable local");
8409467b48Spatrick     return true;
8509467b48Spatrick   }
8609467b48Spatrick 
8709467b48Spatrick   return false;
8809467b48Spatrick }
8909467b48Spatrick 
9009467b48Spatrick #ifndef NDEBUG
isNonRenamableLocal(const GlobalValue & GV) const9109467b48Spatrick bool FunctionImportGlobalProcessing::isNonRenamableLocal(
9209467b48Spatrick     const GlobalValue &GV) const {
9309467b48Spatrick   if (!GV.hasLocalLinkage())
9409467b48Spatrick     return false;
9509467b48Spatrick   // This needs to stay in sync with the logic in buildModuleSummaryIndex.
9609467b48Spatrick   if (GV.hasSection())
9709467b48Spatrick     return true;
9809467b48Spatrick   if (Used.count(const_cast<GlobalValue *>(&GV)))
9909467b48Spatrick     return true;
10009467b48Spatrick   return false;
10109467b48Spatrick }
10209467b48Spatrick #endif
10309467b48Spatrick 
10409467b48Spatrick std::string
getPromotedName(const GlobalValue * SGV)10509467b48Spatrick FunctionImportGlobalProcessing::getPromotedName(const GlobalValue *SGV) {
10609467b48Spatrick   assert(SGV->hasLocalLinkage());
107*d415bd75Srobert 
10809467b48Spatrick   // For locals that must be promoted to global scope, ensure that
10909467b48Spatrick   // the promoted name uniquely identifies the copy in the original module,
11009467b48Spatrick   // using the ID assigned during combined index creation.
111*d415bd75Srobert   if (UseSourceFilenameForPromotedLocals &&
112*d415bd75Srobert       !SGV->getParent()->getSourceFileName().empty()) {
113*d415bd75Srobert     SmallString<256> Suffix(SGV->getParent()->getSourceFileName());
114*d415bd75Srobert     std::replace_if(std::begin(Suffix), std::end(Suffix),
115*d415bd75Srobert                     [&](char ch) { return !isAlnum(ch); }, '_');
116*d415bd75Srobert     return ModuleSummaryIndex::getGlobalNameForLocal(
117*d415bd75Srobert         SGV->getName(), Suffix);
118*d415bd75Srobert   }
119*d415bd75Srobert 
12009467b48Spatrick   return ModuleSummaryIndex::getGlobalNameForLocal(
12109467b48Spatrick       SGV->getName(),
12209467b48Spatrick       ImportIndex.getModuleHash(SGV->getParent()->getModuleIdentifier()));
12309467b48Spatrick }
12409467b48Spatrick 
12509467b48Spatrick GlobalValue::LinkageTypes
getLinkage(const GlobalValue * SGV,bool DoPromote)12609467b48Spatrick FunctionImportGlobalProcessing::getLinkage(const GlobalValue *SGV,
12709467b48Spatrick                                            bool DoPromote) {
12809467b48Spatrick   // Any local variable that is referenced by an exported function needs
12909467b48Spatrick   // to be promoted to global scope. Since we don't currently know which
13009467b48Spatrick   // functions reference which local variables/functions, we must treat
13109467b48Spatrick   // all as potentially exported if this module is exporting anything.
13209467b48Spatrick   if (isModuleExporting()) {
13309467b48Spatrick     if (SGV->hasLocalLinkage() && DoPromote)
13409467b48Spatrick       return GlobalValue::ExternalLinkage;
13509467b48Spatrick     return SGV->getLinkage();
13609467b48Spatrick   }
13709467b48Spatrick 
13809467b48Spatrick   // Otherwise, if we aren't importing, no linkage change is needed.
13909467b48Spatrick   if (!isPerformingImport())
14009467b48Spatrick     return SGV->getLinkage();
14109467b48Spatrick 
14209467b48Spatrick   switch (SGV->getLinkage()) {
14309467b48Spatrick   case GlobalValue::LinkOnceODRLinkage:
14409467b48Spatrick   case GlobalValue::ExternalLinkage:
14509467b48Spatrick     // External and linkonce definitions are converted to available_externally
14609467b48Spatrick     // definitions upon import, so that they are available for inlining
14709467b48Spatrick     // and/or optimization, but are turned into declarations later
14809467b48Spatrick     // during the EliminateAvailableExternally pass.
14909467b48Spatrick     if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
15009467b48Spatrick       return GlobalValue::AvailableExternallyLinkage;
15109467b48Spatrick     // An imported external declaration stays external.
15209467b48Spatrick     return SGV->getLinkage();
15309467b48Spatrick 
15409467b48Spatrick   case GlobalValue::AvailableExternallyLinkage:
15509467b48Spatrick     // An imported available_externally definition converts
15609467b48Spatrick     // to external if imported as a declaration.
15709467b48Spatrick     if (!doImportAsDefinition(SGV))
15809467b48Spatrick       return GlobalValue::ExternalLinkage;
15909467b48Spatrick     // An imported available_externally declaration stays that way.
16009467b48Spatrick     return SGV->getLinkage();
16109467b48Spatrick 
16209467b48Spatrick   case GlobalValue::LinkOnceAnyLinkage:
16309467b48Spatrick   case GlobalValue::WeakAnyLinkage:
16409467b48Spatrick     // Can't import linkonce_any/weak_any definitions correctly, or we might
16509467b48Spatrick     // change the program semantics, since the linker will pick the first
16609467b48Spatrick     // linkonce_any/weak_any definition and importing would change the order
16709467b48Spatrick     // they are seen by the linker. The module linking caller needs to enforce
16809467b48Spatrick     // this.
16909467b48Spatrick     assert(!doImportAsDefinition(SGV));
17009467b48Spatrick     // If imported as a declaration, it becomes external_weak.
17109467b48Spatrick     return SGV->getLinkage();
17209467b48Spatrick 
17309467b48Spatrick   case GlobalValue::WeakODRLinkage:
17409467b48Spatrick     // For weak_odr linkage, there is a guarantee that all copies will be
17509467b48Spatrick     // equivalent, so the issue described above for weak_any does not exist,
17609467b48Spatrick     // and the definition can be imported. It can be treated similarly
17709467b48Spatrick     // to an imported externally visible global value.
17809467b48Spatrick     if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
17909467b48Spatrick       return GlobalValue::AvailableExternallyLinkage;
18009467b48Spatrick     else
18109467b48Spatrick       return GlobalValue::ExternalLinkage;
18209467b48Spatrick 
18309467b48Spatrick   case GlobalValue::AppendingLinkage:
18409467b48Spatrick     // It would be incorrect to import an appending linkage variable,
18509467b48Spatrick     // since it would cause global constructors/destructors to be
18609467b48Spatrick     // executed multiple times. This should have already been handled
18709467b48Spatrick     // by linkIfNeeded, and we will assert in shouldLinkFromSource
18809467b48Spatrick     // if we try to import, so we simply return AppendingLinkage.
18909467b48Spatrick     return GlobalValue::AppendingLinkage;
19009467b48Spatrick 
19109467b48Spatrick   case GlobalValue::InternalLinkage:
19209467b48Spatrick   case GlobalValue::PrivateLinkage:
19309467b48Spatrick     // If we are promoting the local to global scope, it is handled
19409467b48Spatrick     // similarly to a normal externally visible global.
19509467b48Spatrick     if (DoPromote) {
19609467b48Spatrick       if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
19709467b48Spatrick         return GlobalValue::AvailableExternallyLinkage;
19809467b48Spatrick       else
19909467b48Spatrick         return GlobalValue::ExternalLinkage;
20009467b48Spatrick     }
20109467b48Spatrick     // A non-promoted imported local definition stays local.
20209467b48Spatrick     // The ThinLTO pass will eventually force-import their definitions.
20309467b48Spatrick     return SGV->getLinkage();
20409467b48Spatrick 
20509467b48Spatrick   case GlobalValue::ExternalWeakLinkage:
20609467b48Spatrick     // External weak doesn't apply to definitions, must be a declaration.
20709467b48Spatrick     assert(!doImportAsDefinition(SGV));
20809467b48Spatrick     // Linkage stays external_weak.
20909467b48Spatrick     return SGV->getLinkage();
21009467b48Spatrick 
21109467b48Spatrick   case GlobalValue::CommonLinkage:
21209467b48Spatrick     // Linkage stays common on definitions.
21309467b48Spatrick     // The ThinLTO pass will eventually force-import their definitions.
21409467b48Spatrick     return SGV->getLinkage();
21509467b48Spatrick   }
21609467b48Spatrick 
21709467b48Spatrick   llvm_unreachable("unknown linkage type");
21809467b48Spatrick }
21909467b48Spatrick 
processGlobalForThinLTO(GlobalValue & GV)22009467b48Spatrick void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) {
22109467b48Spatrick 
22209467b48Spatrick   ValueInfo VI;
22309467b48Spatrick   if (GV.hasName()) {
22409467b48Spatrick     VI = ImportIndex.getValueInfo(GV.getGUID());
22509467b48Spatrick     // Set synthetic function entry counts.
22609467b48Spatrick     if (VI && ImportIndex.hasSyntheticEntryCounts()) {
22709467b48Spatrick       if (Function *F = dyn_cast<Function>(&GV)) {
22809467b48Spatrick         if (!F->isDeclaration()) {
229*d415bd75Srobert           for (const auto &S : VI.getSummaryList()) {
23009467b48Spatrick             auto *FS = cast<FunctionSummary>(S->getBaseObject());
23109467b48Spatrick             if (FS->modulePath() == M.getModuleIdentifier()) {
23209467b48Spatrick               F->setEntryCount(Function::ProfileCount(FS->entryCount(),
23309467b48Spatrick                                                       Function::PCT_Synthetic));
23409467b48Spatrick               break;
23509467b48Spatrick             }
23609467b48Spatrick           }
23709467b48Spatrick         }
23809467b48Spatrick       }
23909467b48Spatrick     }
24009467b48Spatrick   }
24109467b48Spatrick 
24209467b48Spatrick   // We should always have a ValueInfo (i.e. GV in index) for definitions when
24309467b48Spatrick   // we are exporting, and also when importing that value.
24409467b48Spatrick   assert(VI || GV.isDeclaration() ||
24509467b48Spatrick          (isPerformingImport() && !doImportAsDefinition(&GV)));
24609467b48Spatrick 
24709467b48Spatrick   // Mark read/write-only variables which can be imported with specific
24809467b48Spatrick   // attribute. We can't internalize them now because IRMover will fail
24909467b48Spatrick   // to link variable definitions to their external declarations during
25009467b48Spatrick   // ThinLTO import. We'll internalize read-only variables later, after
25109467b48Spatrick   // import is finished. See internalizeGVsAfterImport.
25209467b48Spatrick   //
25309467b48Spatrick   // If global value dead stripping is not enabled in summary then
25409467b48Spatrick   // propagateConstants hasn't been run. We can't internalize GV
25509467b48Spatrick   // in such case.
25609467b48Spatrick   if (!GV.isDeclaration() && VI && ImportIndex.withAttributePropagation()) {
25709467b48Spatrick     if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
25809467b48Spatrick       // We can have more than one local with the same GUID, in the case of
25909467b48Spatrick       // same-named locals in different but same-named source files that were
26009467b48Spatrick       // compiled in their respective directories (so the source file name
26109467b48Spatrick       // and resulting GUID is the same). Find the one in this module.
26209467b48Spatrick       // Handle the case where there is no summary found in this module. That
26309467b48Spatrick       // can happen in the distributed ThinLTO backend, because the index only
26409467b48Spatrick       // contains summaries from the source modules if they are being imported.
26509467b48Spatrick       // We might have a non-null VI and get here even in that case if the name
26609467b48Spatrick       // matches one in this module (e.g. weak or appending linkage).
26709467b48Spatrick       auto *GVS = dyn_cast_or_null<GlobalVarSummary>(
26809467b48Spatrick           ImportIndex.findSummaryInModule(VI, M.getModuleIdentifier()));
26909467b48Spatrick       if (GVS &&
27009467b48Spatrick           (ImportIndex.isReadOnly(GVS) || ImportIndex.isWriteOnly(GVS))) {
27109467b48Spatrick         V->addAttribute("thinlto-internalize");
27209467b48Spatrick         // Objects referenced by writeonly GV initializer should not be
27309467b48Spatrick         // promoted, because there is no any kind of read access to them
27409467b48Spatrick         // on behalf of this writeonly GV. To avoid promotion we convert
27509467b48Spatrick         // GV initializer to 'zeroinitializer'. This effectively drops
27609467b48Spatrick         // references in IR module (not in combined index), so we can
27709467b48Spatrick         // ignore them when computing import. We do not export references
27809467b48Spatrick         // of writeonly object. See computeImportForReferencedGlobals
27909467b48Spatrick         if (ImportIndex.isWriteOnly(GVS))
28009467b48Spatrick           V->setInitializer(Constant::getNullValue(V->getValueType()));
28109467b48Spatrick       }
28209467b48Spatrick     }
28309467b48Spatrick   }
28409467b48Spatrick 
28509467b48Spatrick   if (GV.hasLocalLinkage() && shouldPromoteLocalToGlobal(&GV, VI)) {
28609467b48Spatrick     // Save the original name string before we rename GV below.
28709467b48Spatrick     auto Name = GV.getName().str();
28809467b48Spatrick     GV.setName(getPromotedName(&GV));
28909467b48Spatrick     GV.setLinkage(getLinkage(&GV, /* DoPromote */ true));
29009467b48Spatrick     assert(!GV.hasLocalLinkage());
29109467b48Spatrick     GV.setVisibility(GlobalValue::HiddenVisibility);
29209467b48Spatrick 
29309467b48Spatrick     // If we are renaming a COMDAT leader, ensure that we record the COMDAT
29409467b48Spatrick     // for later renaming as well. This is required for COFF.
29509467b48Spatrick     if (const auto *C = GV.getComdat())
29609467b48Spatrick       if (C->getName() == Name)
29709467b48Spatrick         RenamedComdats.try_emplace(C, M.getOrInsertComdat(GV.getName()));
29809467b48Spatrick   } else
29909467b48Spatrick     GV.setLinkage(getLinkage(&GV, /* DoPromote */ false));
30009467b48Spatrick 
301097a140dSpatrick   // When ClearDSOLocalOnDeclarations is true, clear dso_local if GV is
302097a140dSpatrick   // converted to a declaration, to disable direct access. Don't do this if GV
303097a140dSpatrick   // is implicitly dso_local due to a non-default visibility.
30473471bf0Spatrick   if (ClearDSOLocalOnDeclarations &&
30573471bf0Spatrick       (GV.isDeclarationForLinker() ||
30673471bf0Spatrick        (isPerformingImport() && !doImportAsDefinition(&GV))) &&
307097a140dSpatrick       !GV.isImplicitDSOLocal()) {
308097a140dSpatrick     GV.setDSOLocal(false);
30973471bf0Spatrick   } else if (VI && VI.isDSOLocal(ImportIndex.withDSOLocalPropagation())) {
310097a140dSpatrick     // If all summaries are dso_local, symbol gets resolved to a known local
311097a140dSpatrick     // definition.
312097a140dSpatrick     GV.setDSOLocal(true);
313097a140dSpatrick     if (GV.hasDLLImportStorageClass())
314097a140dSpatrick       GV.setDLLStorageClass(GlobalValue::DefaultStorageClass);
315097a140dSpatrick   }
316097a140dSpatrick 
31709467b48Spatrick   // Remove functions imported as available externally defs from comdats,
31809467b48Spatrick   // as this is a declaration for the linker, and will be dropped eventually.
31909467b48Spatrick   // It is illegal for comdats to contain declarations.
32009467b48Spatrick   auto *GO = dyn_cast<GlobalObject>(&GV);
32109467b48Spatrick   if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
32209467b48Spatrick     // The IRMover should not have placed any imported declarations in
32309467b48Spatrick     // a comdat, so the only declaration that should be in a comdat
32409467b48Spatrick     // at this point would be a definition imported as available_externally.
32509467b48Spatrick     assert(GO->hasAvailableExternallyLinkage() &&
32609467b48Spatrick            "Expected comdat on definition (possibly available external)");
32709467b48Spatrick     GO->setComdat(nullptr);
32809467b48Spatrick   }
32909467b48Spatrick }
33009467b48Spatrick 
processGlobalsForThinLTO()33109467b48Spatrick void FunctionImportGlobalProcessing::processGlobalsForThinLTO() {
33209467b48Spatrick   for (GlobalVariable &GV : M.globals())
33309467b48Spatrick     processGlobalForThinLTO(GV);
33409467b48Spatrick   for (Function &SF : M)
33509467b48Spatrick     processGlobalForThinLTO(SF);
33609467b48Spatrick   for (GlobalAlias &GA : M.aliases())
33709467b48Spatrick     processGlobalForThinLTO(GA);
33809467b48Spatrick 
33909467b48Spatrick   // Replace any COMDATS that required renaming (because the COMDAT leader was
34009467b48Spatrick   // promoted and renamed).
34109467b48Spatrick   if (!RenamedComdats.empty())
34209467b48Spatrick     for (auto &GO : M.global_objects())
34309467b48Spatrick       if (auto *C = GO.getComdat()) {
34409467b48Spatrick         auto Replacement = RenamedComdats.find(C);
34509467b48Spatrick         if (Replacement != RenamedComdats.end())
34609467b48Spatrick           GO.setComdat(Replacement->second);
34709467b48Spatrick       }
34809467b48Spatrick }
34909467b48Spatrick 
run()35009467b48Spatrick bool FunctionImportGlobalProcessing::run() {
35109467b48Spatrick   processGlobalsForThinLTO();
35209467b48Spatrick   return false;
35309467b48Spatrick }
35409467b48Spatrick 
renameModuleForThinLTO(Module & M,const ModuleSummaryIndex & Index,bool ClearDSOLocalOnDeclarations,SetVector<GlobalValue * > * GlobalsToImport)35509467b48Spatrick bool llvm::renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index,
356097a140dSpatrick                                   bool ClearDSOLocalOnDeclarations,
35709467b48Spatrick                                   SetVector<GlobalValue *> *GlobalsToImport) {
358097a140dSpatrick   FunctionImportGlobalProcessing ThinLTOProcessing(M, Index, GlobalsToImport,
359097a140dSpatrick                                                    ClearDSOLocalOnDeclarations);
36009467b48Spatrick   return ThinLTOProcessing.run();
36109467b48Spatrick }
362