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(
22*cc1b0bc2STeresa Johnson     const GlobalValue *SGV) {
23*cc1b0bc2STeresa Johnson   if (!isPerformingImport())
24*cc1b0bc2STeresa 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(
38*cc1b0bc2STeresa 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(
63*cc1b0bc2STeresa 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     }
2155a7056faSEaswaran Raman     // Check the summaries to see if the symbol gets resolved to a known local
2165a7056faSEaswaran Raman     // definition.
217f5220fb6SRafael Espindola     if (VI && VI.isDSOLocal()) {
2184595a915SSean Fertile       GV.setDSOLocal(true);
219f5220fb6SRafael Espindola       if (GV.hasDLLImportStorageClass())
220f5220fb6SRafael Espindola         GV.setDLLStorageClass(GlobalValue::DefaultStorageClass);
221f5220fb6SRafael Espindola     }
2224595a915SSean Fertile   }
2234595a915SSean Fertile 
224*cc1b0bc2STeresa Johnson   // We should always have a ValueInfo (i.e. GV in index) for definitions when
225*cc1b0bc2STeresa Johnson   // we are exporting, and also when importing that value.
226*cc1b0bc2STeresa Johnson   assert(VI || GV.isDeclaration() ||
227*cc1b0bc2STeresa Johnson          (isPerformingImport() && !doImportAsDefinition(&GV)));
228*cc1b0bc2STeresa Johnson 
2293aef3528SEugene Leviant   // Mark read/write-only variables which can be imported with specific
2303aef3528SEugene Leviant   // attribute. We can't internalize them now because IRMover will fail
2313aef3528SEugene Leviant   // to link variable definitions to their external declarations during
2323aef3528SEugene Leviant   // ThinLTO import. We'll internalize read-only variables later, after
2333aef3528SEugene Leviant   // import is finished. See internalizeGVsAfterImport.
234bf46e741SEugene Leviant   //
235bf46e741SEugene Leviant   // If global value dead stripping is not enabled in summary then
236bf46e741SEugene Leviant   // propagateConstants hasn't been run. We can't internalize GV
237bf46e741SEugene Leviant   // in such case.
238dde58938Sevgeny   if (!GV.isDeclaration() && VI && ImportIndex.withAttributePropagation()) {
23916ec00eeSTeresa Johnson     if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
24016ec00eeSTeresa Johnson       // We can have more than one local with the same GUID, in the case of
24116ec00eeSTeresa Johnson       // same-named locals in different but same-named source files that were
24216ec00eeSTeresa Johnson       // compiled in their respective directories (so the source file name
24316ec00eeSTeresa Johnson       // and resulting GUID is the same). Find the one in this module.
24416ec00eeSTeresa Johnson       // Handle the case where there is no summary found in this module. That
24516ec00eeSTeresa Johnson       // can happen in the distributed ThinLTO backend, because the index only
24616ec00eeSTeresa Johnson       // contains summaries from the source modules if they are being imported.
24716ec00eeSTeresa Johnson       // We might have a non-null VI and get here even in that case if the name
24816ec00eeSTeresa Johnson       // matches one in this module (e.g. weak or appending linkage).
24916ec00eeSTeresa Johnson       auto *GVS = dyn_cast_or_null<GlobalVarSummary>(
25016ec00eeSTeresa Johnson           ImportIndex.findSummaryInModule(VI, M.getModuleIdentifier()));
2517f92d66fSevgeny       if (GVS &&
2527f92d66fSevgeny           (ImportIndex.isReadOnly(GVS) || ImportIndex.isWriteOnly(GVS))) {
25316ec00eeSTeresa Johnson         V->addAttribute("thinlto-internalize");
2547f92d66fSevgeny         // Objects referenced by writeonly GV initializer should not be
2557f92d66fSevgeny         // promoted, because there is no any kind of read access to them
2567f92d66fSevgeny         // on behalf of this writeonly GV. To avoid promotion we convert
2577f92d66fSevgeny         // GV initializer to 'zeroinitializer'. This effectively drops
2587f92d66fSevgeny         // references in IR module (not in combined index), so we can
2597f92d66fSevgeny         // ignore them when computing import. We do not export references
2607f92d66fSevgeny         // of writeonly object. See computeImportForReferencedGlobals
2617f92d66fSevgeny         if (ImportIndex.isWriteOnly(GVS) && GVS->refs().size())
2627f92d66fSevgeny           V->setInitializer(Constant::getNullValue(V->getValueType()));
2637f92d66fSevgeny       }
26416ec00eeSTeresa Johnson     }
265bf46e741SEugene Leviant   }
266bf46e741SEugene Leviant 
267*cc1b0bc2STeresa Johnson   if (GV.hasLocalLinkage() && shouldPromoteLocalToGlobal(&GV, VI)) {
268f59242e5STeresa Johnson     // Save the original name string before we rename GV below.
269f59242e5STeresa Johnson     auto Name = GV.getName().str();
2703be6dbcaSTeresa Johnson     GV.setName(getPromotedName(&GV));
2713be6dbcaSTeresa Johnson     GV.setLinkage(getLinkage(&GV, /* DoPromote */ true));
2723be6dbcaSTeresa Johnson     assert(!GV.hasLocalLinkage());
273488a800aSTeresa Johnson     GV.setVisibility(GlobalValue::HiddenVisibility);
274f59242e5STeresa Johnson 
275f59242e5STeresa Johnson     // If we are renaming a COMDAT leader, ensure that we record the COMDAT
276f59242e5STeresa Johnson     // for later renaming as well. This is required for COFF.
277f59242e5STeresa Johnson     if (const auto *C = GV.getComdat())
278f59242e5STeresa Johnson       if (C->getName() == Name)
279f59242e5STeresa Johnson         RenamedComdats.try_emplace(C, M.getOrInsertComdat(GV.getName()));
280488a800aSTeresa Johnson   } else
2811b9c2be8STeresa Johnson     GV.setLinkage(getLinkage(&GV, /* DoPromote */ false));
282488a800aSTeresa Johnson 
283488a800aSTeresa Johnson   // Remove functions imported as available externally defs from comdats,
284488a800aSTeresa Johnson   // as this is a declaration for the linker, and will be dropped eventually.
285488a800aSTeresa Johnson   // It is illegal for comdats to contain declarations.
286bf46e741SEugene Leviant   auto *GO = dyn_cast<GlobalObject>(&GV);
287488a800aSTeresa Johnson   if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
288488a800aSTeresa Johnson     // The IRMover should not have placed any imported declarations in
289488a800aSTeresa Johnson     // a comdat, so the only declaration that should be in a comdat
290488a800aSTeresa Johnson     // at this point would be a definition imported as available_externally.
291488a800aSTeresa Johnson     assert(GO->hasAvailableExternallyLinkage() &&
292488a800aSTeresa Johnson            "Expected comdat on definition (possibly available external)");
293488a800aSTeresa Johnson     GO->setComdat(nullptr);
294488a800aSTeresa Johnson   }
295488a800aSTeresa Johnson }
296488a800aSTeresa Johnson 
297488a800aSTeresa Johnson void FunctionImportGlobalProcessing::processGlobalsForThinLTO() {
298488a800aSTeresa Johnson   for (GlobalVariable &GV : M.globals())
299488a800aSTeresa Johnson     processGlobalForThinLTO(GV);
300488a800aSTeresa Johnson   for (Function &SF : M)
301488a800aSTeresa Johnson     processGlobalForThinLTO(SF);
302488a800aSTeresa Johnson   for (GlobalAlias &GA : M.aliases())
303488a800aSTeresa Johnson     processGlobalForThinLTO(GA);
304f59242e5STeresa Johnson 
305f59242e5STeresa Johnson   // Replace any COMDATS that required renaming (because the COMDAT leader was
306f59242e5STeresa Johnson   // promoted and renamed).
307f59242e5STeresa Johnson   if (!RenamedComdats.empty())
308f59242e5STeresa Johnson     for (auto &GO : M.global_objects())
309f59242e5STeresa Johnson       if (auto *C = GO.getComdat()) {
310f59242e5STeresa Johnson         auto Replacement = RenamedComdats.find(C);
311f59242e5STeresa Johnson         if (Replacement != RenamedComdats.end())
312f59242e5STeresa Johnson           GO.setComdat(Replacement->second);
313f59242e5STeresa Johnson       }
314488a800aSTeresa Johnson }
315488a800aSTeresa Johnson 
316488a800aSTeresa Johnson bool FunctionImportGlobalProcessing::run() {
317488a800aSTeresa Johnson   processGlobalsForThinLTO();
318488a800aSTeresa Johnson   return false;
319488a800aSTeresa Johnson }
320488a800aSTeresa Johnson 
3216d8f817fSPeter Collingbourne bool llvm::renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index,
3226d8f817fSPeter Collingbourne                                   SetVector<GlobalValue *> *GlobalsToImport) {
3238d05185aSMehdi Amini   FunctionImportGlobalProcessing ThinLTOProcessing(M, Index, GlobalsToImport);
324488a800aSTeresa Johnson   return ThinLTOProcessing.run();
325488a800aSTeresa Johnson }
326