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"
15df5ef871STeresa Johnson #include "llvm/IR/InstIterator.h"
16488a800aSTeresa Johnson using namespace llvm;
17488a800aSTeresa Johnson 
18488a800aSTeresa Johnson /// Checks if we should import SGV as a definition, otherwise import as a
19488a800aSTeresa Johnson /// declaration.
20488a800aSTeresa Johnson bool FunctionImportGlobalProcessing::doImportAsDefinition(
216d8f817fSPeter Collingbourne     const GlobalValue *SGV, SetVector<GlobalValue *> *GlobalsToImport) {
228d05185aSMehdi Amini 
238d05185aSMehdi Amini   // Only import the globals requested for importing.
2472c0b1ccSDavid Blaikie   if (!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)))
2572c0b1ccSDavid Blaikie     return false;
262f0cc477SDavid Blaikie 
272f0cc477SDavid Blaikie   assert(!isa<GlobalAlias>(SGV) &&
282f0cc477SDavid Blaikie          "Unexpected global alias in the import list.");
292f0cc477SDavid Blaikie 
3072c0b1ccSDavid Blaikie   // Otherwise yes.
3172c0b1ccSDavid Blaikie   return true;
32488a800aSTeresa Johnson }
33488a800aSTeresa Johnson 
34488a800aSTeresa Johnson bool FunctionImportGlobalProcessing::doImportAsDefinition(
35488a800aSTeresa Johnson     const GlobalValue *SGV) {
36488a800aSTeresa Johnson   if (!isPerformingImport())
37488a800aSTeresa Johnson     return false;
388d05185aSMehdi Amini   return FunctionImportGlobalProcessing::doImportAsDefinition(SGV,
398d05185aSMehdi Amini                                                               GlobalsToImport);
40488a800aSTeresa Johnson }
41488a800aSTeresa Johnson 
4238d4df71STeresa Johnson bool FunctionImportGlobalProcessing::shouldPromoteLocalToGlobal(
43488a800aSTeresa Johnson     const GlobalValue *SGV) {
44488a800aSTeresa Johnson   assert(SGV->hasLocalLinkage());
45488a800aSTeresa Johnson   // Both the imported references and the original local variable must
46488a800aSTeresa Johnson   // be promoted.
47488a800aSTeresa Johnson   if (!isPerformingImport() && !isModuleExporting())
48488a800aSTeresa Johnson     return false;
49488a800aSTeresa Johnson 
504fef68cbSTeresa Johnson   if (isPerformingImport()) {
516d8f817fSPeter Collingbourne     assert((!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)) ||
526d8f817fSPeter Collingbourne             !isNonRenamableLocal(*SGV)) &&
53519465b9STeresa Johnson            "Attempting to promote non-renamable local");
544fef68cbSTeresa Johnson     // We don't know for sure yet if we are importing this value (as either
554fef68cbSTeresa Johnson     // a reference or a def), since we are simply walking all values in the
564fef68cbSTeresa Johnson     // module. But by necessity if we end up importing it and it is local,
574fef68cbSTeresa Johnson     // it must be promoted, so unconditionally promote all values in the
584fef68cbSTeresa Johnson     // importing module.
594fef68cbSTeresa Johnson     return true;
600515fb8dSTeresa Johnson   }
61b4e1e829SMehdi Amini 
629006d526STeresa Johnson   // When exporting, consult the index. We can have more than one local
639006d526STeresa Johnson   // with the same GUID, in the case of same-named locals in different but
649006d526STeresa Johnson   // same-named source files that were compiled in their respective directories
659006d526STeresa Johnson   // (so the source file name and resulting GUID is the same). Find the one
669006d526STeresa Johnson   // in this module.
679006d526STeresa Johnson   auto Summary = ImportIndex.findSummaryInModule(
689006d526STeresa Johnson       SGV->getGUID(), SGV->getParent()->getModuleIdentifier());
699006d526STeresa Johnson   assert(Summary && "Missing summary for global value when exporting");
709006d526STeresa Johnson   auto Linkage = Summary->linkage();
714fef68cbSTeresa Johnson   if (!GlobalValue::isLocalLinkage(Linkage)) {
72519465b9STeresa Johnson     assert(!isNonRenamableLocal(*SGV) &&
73519465b9STeresa Johnson            "Attempting to promote non-renamable local");
74488a800aSTeresa Johnson     return true;
75488a800aSTeresa Johnson   }
76488a800aSTeresa Johnson 
774fef68cbSTeresa Johnson   return false;
784fef68cbSTeresa Johnson }
794fef68cbSTeresa Johnson 
80519465b9STeresa Johnson #ifndef NDEBUG
81519465b9STeresa Johnson bool FunctionImportGlobalProcessing::isNonRenamableLocal(
82519465b9STeresa Johnson     const GlobalValue &GV) const {
83519465b9STeresa Johnson   if (!GV.hasLocalLinkage())
84519465b9STeresa Johnson     return false;
85519465b9STeresa Johnson   // This needs to stay in sync with the logic in buildModuleSummaryIndex.
86519465b9STeresa Johnson   if (GV.hasSection())
87519465b9STeresa Johnson     return true;
88519465b9STeresa Johnson   if (Used.count(const_cast<GlobalValue *>(&GV)))
89519465b9STeresa Johnson     return true;
90519465b9STeresa Johnson   return false;
91519465b9STeresa Johnson }
92519465b9STeresa Johnson #endif
93519465b9STeresa Johnson 
941b9c2be8STeresa Johnson std::string FunctionImportGlobalProcessing::getName(const GlobalValue *SGV,
951b9c2be8STeresa Johnson                                                     bool DoPromote) {
96488a800aSTeresa Johnson   // For locals that must be promoted to global scope, ensure that
97488a800aSTeresa Johnson   // the promoted name uniquely identifies the copy in the original module,
98488a800aSTeresa Johnson   // using the ID assigned during combined index creation. When importing,
99488a800aSTeresa Johnson   // we rename all locals (not just those that are promoted) in order to
100488a800aSTeresa Johnson   // avoid naming conflicts between locals imported from different modules.
1011b9c2be8STeresa Johnson   if (SGV->hasLocalLinkage() && (DoPromote || isPerformingImport()))
10226ab5772STeresa Johnson     return ModuleSummaryIndex::getGlobalNameForLocal(
103488a800aSTeresa Johnson         SGV->getName(),
104ae280e54SMehdi Amini         ImportIndex.getModuleHash(SGV->getParent()->getModuleIdentifier()));
105488a800aSTeresa Johnson   return SGV->getName();
106488a800aSTeresa Johnson }
107488a800aSTeresa Johnson 
108488a800aSTeresa Johnson GlobalValue::LinkageTypes
1091b9c2be8STeresa Johnson FunctionImportGlobalProcessing::getLinkage(const GlobalValue *SGV,
1101b9c2be8STeresa Johnson                                            bool DoPromote) {
111488a800aSTeresa Johnson   // Any local variable that is referenced by an exported function needs
112488a800aSTeresa Johnson   // to be promoted to global scope. Since we don't currently know which
113488a800aSTeresa Johnson   // functions reference which local variables/functions, we must treat
114488a800aSTeresa Johnson   // all as potentially exported if this module is exporting anything.
115488a800aSTeresa Johnson   if (isModuleExporting()) {
1161b9c2be8STeresa Johnson     if (SGV->hasLocalLinkage() && DoPromote)
117488a800aSTeresa Johnson       return GlobalValue::ExternalLinkage;
118488a800aSTeresa Johnson     return SGV->getLinkage();
119488a800aSTeresa Johnson   }
120488a800aSTeresa Johnson 
121488a800aSTeresa Johnson   // Otherwise, if we aren't importing, no linkage change is needed.
122488a800aSTeresa Johnson   if (!isPerformingImport())
123488a800aSTeresa Johnson     return SGV->getLinkage();
124488a800aSTeresa Johnson 
125488a800aSTeresa Johnson   switch (SGV->getLinkage()) {
1262f0cc477SDavid Blaikie   case GlobalValue::LinkOnceODRLinkage:
127488a800aSTeresa Johnson   case GlobalValue::ExternalLinkage:
1282f0cc477SDavid Blaikie     // External and linkonce definitions are converted to available_externally
129488a800aSTeresa Johnson     // definitions upon import, so that they are available for inlining
130488a800aSTeresa Johnson     // and/or optimization, but are turned into declarations later
131488a800aSTeresa Johnson     // during the EliminateAvailableExternally pass.
1322c5c12c0SFangrui Song     if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
133488a800aSTeresa Johnson       return GlobalValue::AvailableExternallyLinkage;
134488a800aSTeresa Johnson     // An imported external declaration stays external.
135488a800aSTeresa Johnson     return SGV->getLinkage();
136488a800aSTeresa Johnson 
137488a800aSTeresa Johnson   case GlobalValue::AvailableExternallyLinkage:
138488a800aSTeresa Johnson     // An imported available_externally definition converts
139488a800aSTeresa Johnson     // to external if imported as a declaration.
140488a800aSTeresa Johnson     if (!doImportAsDefinition(SGV))
141488a800aSTeresa Johnson       return GlobalValue::ExternalLinkage;
142488a800aSTeresa Johnson     // An imported available_externally declaration stays that way.
143488a800aSTeresa Johnson     return SGV->getLinkage();
144488a800aSTeresa Johnson 
14553e52e47SXin Tong   case GlobalValue::LinkOnceAnyLinkage:
146488a800aSTeresa Johnson   case GlobalValue::WeakAnyLinkage:
14753e52e47SXin Tong     // Can't import linkonce_any/weak_any definitions correctly, or we might
14853e52e47SXin Tong     // change the program semantics, since the linker will pick the first
14953e52e47SXin Tong     // linkonce_any/weak_any definition and importing would change the order
15053e52e47SXin Tong     // they are seen by the linker. The module linking caller needs to enforce
15153e52e47SXin Tong     // this.
152488a800aSTeresa Johnson     assert(!doImportAsDefinition(SGV));
153488a800aSTeresa Johnson     // If imported as a declaration, it becomes external_weak.
154bb3a1d92SMehdi Amini     return SGV->getLinkage();
155488a800aSTeresa Johnson 
156488a800aSTeresa Johnson   case GlobalValue::WeakODRLinkage:
157488a800aSTeresa Johnson     // For weak_odr linkage, there is a guarantee that all copies will be
158488a800aSTeresa Johnson     // equivalent, so the issue described above for weak_any does not exist,
159488a800aSTeresa Johnson     // and the definition can be imported. It can be treated similarly
160488a800aSTeresa Johnson     // to an imported externally visible global value.
1612c5c12c0SFangrui Song     if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
162488a800aSTeresa Johnson       return GlobalValue::AvailableExternallyLinkage;
163488a800aSTeresa Johnson     else
164488a800aSTeresa Johnson       return GlobalValue::ExternalLinkage;
165488a800aSTeresa Johnson 
166488a800aSTeresa Johnson   case GlobalValue::AppendingLinkage:
167488a800aSTeresa Johnson     // It would be incorrect to import an appending linkage variable,
168488a800aSTeresa Johnson     // since it would cause global constructors/destructors to be
169488a800aSTeresa Johnson     // executed multiple times. This should have already been handled
170488a800aSTeresa Johnson     // by linkIfNeeded, and we will assert in shouldLinkFromSource
171488a800aSTeresa Johnson     // if we try to import, so we simply return AppendingLinkage.
172488a800aSTeresa Johnson     return GlobalValue::AppendingLinkage;
173488a800aSTeresa Johnson 
174488a800aSTeresa Johnson   case GlobalValue::InternalLinkage:
175488a800aSTeresa Johnson   case GlobalValue::PrivateLinkage:
176488a800aSTeresa Johnson     // If we are promoting the local to global scope, it is handled
177488a800aSTeresa Johnson     // similarly to a normal externally visible global.
1781b9c2be8STeresa Johnson     if (DoPromote) {
1792c5c12c0SFangrui Song       if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
180488a800aSTeresa Johnson         return GlobalValue::AvailableExternallyLinkage;
181488a800aSTeresa Johnson       else
182488a800aSTeresa Johnson         return GlobalValue::ExternalLinkage;
183488a800aSTeresa Johnson     }
184488a800aSTeresa Johnson     // A non-promoted imported local definition stays local.
185488a800aSTeresa Johnson     // The ThinLTO pass will eventually force-import their definitions.
186488a800aSTeresa Johnson     return SGV->getLinkage();
187488a800aSTeresa Johnson 
188488a800aSTeresa Johnson   case GlobalValue::ExternalWeakLinkage:
189488a800aSTeresa Johnson     // External weak doesn't apply to definitions, must be a declaration.
190488a800aSTeresa Johnson     assert(!doImportAsDefinition(SGV));
191488a800aSTeresa Johnson     // Linkage stays external_weak.
192488a800aSTeresa Johnson     return SGV->getLinkage();
193488a800aSTeresa Johnson 
194488a800aSTeresa Johnson   case GlobalValue::CommonLinkage:
195488a800aSTeresa Johnson     // Linkage stays common on definitions.
196488a800aSTeresa Johnson     // The ThinLTO pass will eventually force-import their definitions.
197488a800aSTeresa Johnson     return SGV->getLinkage();
198488a800aSTeresa Johnson   }
199488a800aSTeresa Johnson 
200488a800aSTeresa Johnson   llvm_unreachable("unknown linkage type");
201488a800aSTeresa Johnson }
202488a800aSTeresa Johnson 
203488a800aSTeresa Johnson void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) {
2044595a915SSean Fertile 
205bf46e741SEugene Leviant   ValueInfo VI;
2064595a915SSean Fertile   if (GV.hasName()) {
207bf46e741SEugene Leviant     VI = ImportIndex.getValueInfo(GV.getGUID());
2085a7056faSEaswaran Raman     // Set synthetic function entry counts.
2095a7056faSEaswaran Raman     if (VI && ImportIndex.hasSyntheticEntryCounts()) {
2105a7056faSEaswaran Raman       if (Function *F = dyn_cast<Function>(&GV)) {
2115a7056faSEaswaran Raman         if (!F->isDeclaration()) {
2125a7056faSEaswaran Raman           for (auto &S : VI.getSummaryList()) {
213f71f23d1SSimon Pilgrim             auto *FS = cast<FunctionSummary>(S->getBaseObject());
2145a7056faSEaswaran Raman             if (FS->modulePath() == M.getModuleIdentifier()) {
2155a7056faSEaswaran Raman               F->setEntryCount(Function::ProfileCount(FS->entryCount(),
2165a7056faSEaswaran Raman                                                       Function::PCT_Synthetic));
2175a7056faSEaswaran Raman               break;
2185a7056faSEaswaran Raman             }
2195a7056faSEaswaran Raman           }
2205a7056faSEaswaran Raman         }
2215a7056faSEaswaran Raman       }
2225a7056faSEaswaran Raman     }
2235a7056faSEaswaran Raman     // Check the summaries to see if the symbol gets resolved to a known local
2245a7056faSEaswaran Raman     // definition.
225f5220fb6SRafael Espindola     if (VI && VI.isDSOLocal()) {
2264595a915SSean Fertile       GV.setDSOLocal(true);
227f5220fb6SRafael Espindola       if (GV.hasDLLImportStorageClass())
228f5220fb6SRafael Espindola         GV.setDLLStorageClass(GlobalValue::DefaultStorageClass);
229f5220fb6SRafael Espindola     }
2304595a915SSean Fertile   }
2314595a915SSean Fertile 
2323aef3528SEugene Leviant   // Mark read/write-only variables which can be imported with specific
2333aef3528SEugene Leviant   // attribute. We can't internalize them now because IRMover will fail
2343aef3528SEugene Leviant   // to link variable definitions to their external declarations during
2353aef3528SEugene Leviant   // ThinLTO import. We'll internalize read-only variables later, after
2363aef3528SEugene Leviant   // import is finished. See internalizeGVsAfterImport.
237bf46e741SEugene Leviant   //
238bf46e741SEugene Leviant   // If global value dead stripping is not enabled in summary then
239bf46e741SEugene Leviant   // propagateConstants hasn't been run. We can't internalize GV
240bf46e741SEugene Leviant   // in such case.
241bf46e741SEugene Leviant   if (!GV.isDeclaration() && VI && ImportIndex.withGlobalValueDeadStripping()) {
242*16ec00eeSTeresa Johnson     if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
243*16ec00eeSTeresa Johnson       // We can have more than one local with the same GUID, in the case of
244*16ec00eeSTeresa Johnson       // same-named locals in different but same-named source files that were
245*16ec00eeSTeresa Johnson       // compiled in their respective directories (so the source file name
246*16ec00eeSTeresa Johnson       // and resulting GUID is the same). Find the one in this module.
247*16ec00eeSTeresa Johnson       // Handle the case where there is no summary found in this module. That
248*16ec00eeSTeresa Johnson       // can happen in the distributed ThinLTO backend, because the index only
249*16ec00eeSTeresa Johnson       // contains summaries from the source modules if they are being imported.
250*16ec00eeSTeresa Johnson       // We might have a non-null VI and get here even in that case if the name
251*16ec00eeSTeresa Johnson       // matches one in this module (e.g. weak or appending linkage).
252*16ec00eeSTeresa Johnson       auto* GVS = dyn_cast_or_null<GlobalVarSummary>(
253*16ec00eeSTeresa Johnson           ImportIndex.findSummaryInModule(VI, M.getModuleIdentifier()));
2543aef3528SEugene Leviant       // At this stage "maybe" is "definitely"
2553aef3528SEugene Leviant       if (GVS && (GVS->maybeReadOnly() || GVS->maybeWriteOnly()))
256*16ec00eeSTeresa Johnson         V->addAttribute("thinlto-internalize");
257*16ec00eeSTeresa Johnson     }
258bf46e741SEugene Leviant   }
259bf46e741SEugene Leviant 
2601b9c2be8STeresa Johnson   bool DoPromote = false;
261488a800aSTeresa Johnson   if (GV.hasLocalLinkage() &&
26238d4df71STeresa Johnson       ((DoPromote = shouldPromoteLocalToGlobal(&GV)) || isPerformingImport())) {
263f59242e5STeresa Johnson     // Save the original name string before we rename GV below.
264f59242e5STeresa Johnson     auto Name = GV.getName().str();
2651b9c2be8STeresa Johnson     // Once we change the name or linkage it is difficult to determine
26638d4df71STeresa Johnson     // again whether we should promote since shouldPromoteLocalToGlobal needs
2671b9c2be8STeresa Johnson     // to locate the summary (based on GUID from name and linkage). Therefore,
2681b9c2be8STeresa Johnson     // use DoPromote result saved above.
2691b9c2be8STeresa Johnson     GV.setName(getName(&GV, DoPromote));
2701b9c2be8STeresa Johnson     GV.setLinkage(getLinkage(&GV, DoPromote));
271488a800aSTeresa Johnson     if (!GV.hasLocalLinkage())
272488a800aSTeresa Johnson       GV.setVisibility(GlobalValue::HiddenVisibility);
273f59242e5STeresa Johnson 
274f59242e5STeresa Johnson     // If we are renaming a COMDAT leader, ensure that we record the COMDAT
275f59242e5STeresa Johnson     // for later renaming as well. This is required for COFF.
276f59242e5STeresa Johnson     if (const auto *C = GV.getComdat())
277f59242e5STeresa Johnson       if (C->getName() == Name)
278f59242e5STeresa Johnson         RenamedComdats.try_emplace(C, M.getOrInsertComdat(GV.getName()));
279488a800aSTeresa Johnson   } else
2801b9c2be8STeresa Johnson     GV.setLinkage(getLinkage(&GV, /* DoPromote */ false));
281488a800aSTeresa Johnson 
282488a800aSTeresa Johnson   // Remove functions imported as available externally defs from comdats,
283488a800aSTeresa Johnson   // as this is a declaration for the linker, and will be dropped eventually.
284488a800aSTeresa Johnson   // It is illegal for comdats to contain declarations.
285bf46e741SEugene Leviant   auto *GO = dyn_cast<GlobalObject>(&GV);
286488a800aSTeresa Johnson   if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
287488a800aSTeresa Johnson     // The IRMover should not have placed any imported declarations in
288488a800aSTeresa Johnson     // a comdat, so the only declaration that should be in a comdat
289488a800aSTeresa Johnson     // at this point would be a definition imported as available_externally.
290488a800aSTeresa Johnson     assert(GO->hasAvailableExternallyLinkage() &&
291488a800aSTeresa Johnson            "Expected comdat on definition (possibly available external)");
292488a800aSTeresa Johnson     GO->setComdat(nullptr);
293488a800aSTeresa Johnson   }
294488a800aSTeresa Johnson }
295488a800aSTeresa Johnson 
296488a800aSTeresa Johnson void FunctionImportGlobalProcessing::processGlobalsForThinLTO() {
297488a800aSTeresa Johnson   for (GlobalVariable &GV : M.globals())
298488a800aSTeresa Johnson     processGlobalForThinLTO(GV);
299488a800aSTeresa Johnson   for (Function &SF : M)
300488a800aSTeresa Johnson     processGlobalForThinLTO(SF);
301488a800aSTeresa Johnson   for (GlobalAlias &GA : M.aliases())
302488a800aSTeresa Johnson     processGlobalForThinLTO(GA);
303f59242e5STeresa Johnson 
304f59242e5STeresa Johnson   // Replace any COMDATS that required renaming (because the COMDAT leader was
305f59242e5STeresa Johnson   // promoted and renamed).
306f59242e5STeresa Johnson   if (!RenamedComdats.empty())
307f59242e5STeresa Johnson     for (auto &GO : M.global_objects())
308f59242e5STeresa Johnson       if (auto *C = GO.getComdat()) {
309f59242e5STeresa Johnson         auto Replacement = RenamedComdats.find(C);
310f59242e5STeresa Johnson         if (Replacement != RenamedComdats.end())
311f59242e5STeresa Johnson           GO.setComdat(Replacement->second);
312f59242e5STeresa Johnson       }
313488a800aSTeresa Johnson }
314488a800aSTeresa Johnson 
315488a800aSTeresa Johnson bool FunctionImportGlobalProcessing::run() {
316488a800aSTeresa Johnson   processGlobalsForThinLTO();
317488a800aSTeresa Johnson   return false;
318488a800aSTeresa Johnson }
319488a800aSTeresa Johnson 
3206d8f817fSPeter Collingbourne bool llvm::renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index,
3216d8f817fSPeter Collingbourne                                   SetVector<GlobalValue *> *GlobalsToImport) {
3228d05185aSMehdi Amini   FunctionImportGlobalProcessing ThinLTOProcessing(M, Index, GlobalsToImport);
323488a800aSTeresa Johnson   return ThinLTOProcessing.run();
324488a800aSTeresa Johnson }
325