LLVM 23.0.0git
FunctionImportUtils.cpp
Go to the documentation of this file.
1//===- lib/Transforms/Utils/FunctionImportUtils.cpp - Importing utilities -===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the FunctionImportGlobalProcessing class, used
10// to perform the necessary global value handling for function importing.
11//
12//===----------------------------------------------------------------------===//
13
17
18using namespace llvm;
19
20namespace llvm {
21
22/// Uses the "source_filename" instead of a Module hash ID for the suffix of
23/// promoted locals during LTO. NOTE: This requires that the source filename
24/// has a unique name / path to avoid name collisions.
26 "use-source-filename-for-promoted-locals", cl::Hidden,
27 cl::desc("Uses the source file name instead of the Module hash. "
28 "This requires that the source filename has a unique name / "
29 "path to avoid name collisions."));
30
32
34 "thinlto-move-symbols",
36 "Move the symbols with the given name. This will delete these symbols "
37 "wherever they are originally defined, and make sure their "
38 "linkage is External where they are imported. It is meant to be "
39 "used with the name of contextual profiling roots."),
41
42} // end namespace llvm
43
45 Module &M, const ModuleSummaryIndex &Index,
46 SetVector<GlobalValue *> *GlobalsToImport, bool ClearDSOLocalOnDeclarations)
47 : M(M), ImportIndex(Index), GlobalsToImport(GlobalsToImport),
48 ClearDSOLocalOnDeclarations(ClearDSOLocalOnDeclarations) {
49 // If we have a ModuleSummaryIndex but no function to import,
50 // then this is the primary module being compiled in a ThinLTO
51 // backend compilation, and we need to see if it has functions that
52 // may be exported to another backend compilation.
53 if (!GlobalsToImport)
54 HasExportedFunctions = ImportIndex.hasExportedFunctions(M);
55
56#ifndef NDEBUG
58 // First collect those in the llvm.used set.
59 collectUsedGlobalVariables(M, Vec, /*CompilerUsed=*/false);
60 // Next collect those in the llvm.compiler.used set.
61 collectUsedGlobalVariables(M, Vec, /*CompilerUsed=*/true);
62 Used = {llvm::from_range, Vec};
63#endif
64 SymbolsToMove.insert_range(MoveSymbolGUID);
65}
66
67/// Checks if we should import SGV as a definition, otherwise import as a
68/// declaration.
69bool FunctionImportGlobalProcessing::doImportAsDefinition(
70 const GlobalValue *SGV) {
71 if (!isPerformingImport())
72 return false;
73
74 // Only import the globals requested for importing.
75 if (!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)))
76 return false;
77
79 "Unexpected global alias in the import list.");
80
81 // Otherwise yes.
82 return true;
83}
84
85bool FunctionImportGlobalProcessing::shouldPromoteLocalToGlobal(
86 const GlobalValue *SGV, GlobalValueSummary *Summary) {
87 assert(SGV->hasLocalLinkage());
88
89 // Ifuncs and ifunc alias does not have summary.
90 if (isa<GlobalIFunc>(SGV) ||
91 (isa<GlobalAlias>(SGV) &&
92 isa<GlobalIFunc>(cast<GlobalAlias>(SGV)->getAliaseeObject())))
93 return false;
94
95 // Both the imported references and the original local variable must
96 // be promoted.
97 if (!isPerformingImport() && !isModuleExporting())
98 return false;
99
100 if (isPerformingImport()) {
101 assert((!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)) ||
102 !isNonRenamableLocal(*SGV)) &&
103 "Attempting to promote non-renamable local");
104 // We don't know for sure yet if we are importing this value (as either
105 // a reference or a def), since we are simply walking all values in the
106 // module. But by necessity if we end up importing it and it is local,
107 // it must be promoted, so unconditionally promote all values in the
108 // importing module.
109 return true;
110 }
111
112 // When exporting, consult the index. We can have more than one local
113 // with the same GUID, in the case of same-named locals in different but
114 // same-named source files that were compiled in their respective directories
115 // (so the source file name and resulting GUID is the same). Find the one
116 // in this module.
117 assert(Summary && "Missing summary for global value when exporting");
118 auto Linkage = Summary->linkage();
120 assert(!isNonRenamableLocal(*SGV) &&
121 "Attempting to promote non-renamable local");
122 return true;
123 }
124
125 return false;
126}
127
128#ifndef NDEBUG
129bool FunctionImportGlobalProcessing::isNonRenamableLocal(
130 const GlobalValue &GV) const {
131 if (!GV.hasLocalLinkage())
132 return false;
133 // This needs to stay in sync with the logic in buildModuleSummaryIndex.
134 if (GV.hasSection())
135 return true;
136 if (Used.count(const_cast<GlobalValue *>(&GV)))
137 return true;
138 return false;
139}
140#endif
141
142std::string
143FunctionImportGlobalProcessing::getPromotedName(const GlobalValue *SGV) {
144 assert(SGV->hasLocalLinkage());
145
146 // For locals that must be promoted to global scope, ensure that
147 // the promoted name uniquely identifies the copy in the original module,
148 // using the ID assigned during combined index creation.
150 !SGV->getParent()->getSourceFileName().empty()) {
151 SmallString<256> Suffix(SGV->getParent()->getSourceFileName());
152 std::replace_if(std::begin(Suffix), std::end(Suffix),
153 [&](char ch) { return !isAlnum(ch); }, '_');
155 SGV->getName(), Suffix);
156 }
157
159 SGV->getName(),
160 ImportIndex.getModuleHash(SGV->getParent()->getModuleIdentifier()));
161}
162
164FunctionImportGlobalProcessing::getLinkage(const GlobalValue *SGV,
165 bool DoPromote) {
166 // Any local variable that is referenced by an exported function needs
167 // to be promoted to global scope. Since we don't currently know which
168 // functions reference which local variables/functions, we must treat
169 // all as potentially exported if this module is exporting anything.
170 if (isModuleExporting()) {
171 if (SGV->hasLocalLinkage() && DoPromote)
173 return SGV->getLinkage();
174 }
175
176 // Otherwise, if we aren't importing, no linkage change is needed.
177 if (!isPerformingImport())
178 return SGV->getLinkage();
179
180 switch (SGV->getLinkage()) {
183 // External and linkonce definitions are converted to available_externally
184 // definitions upon import, so that they are available for inlining
185 // and/or optimization, but are turned into declarations later
186 // during the EliminateAvailableExternally pass.
187 if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
188 return SymbolsToMove.contains(SGV->getGUIDOrFallback())
191 // An imported external declaration stays external.
192 return SGV->getLinkage();
193
195 // An imported available_externally definition converts
196 // to external if imported as a declaration.
197 if (!doImportAsDefinition(SGV))
199 // An imported available_externally declaration stays that way.
200 return SGV->getLinkage();
201
204 // Can't import linkonce_any/weak_any definitions correctly, or we might
205 // change the program semantics, since the linker will pick the first
206 // linkonce_any/weak_any definition and importing would change the order
207 // they are seen by the linker. The module linking caller needs to enforce
208 // this.
209 assert(!doImportAsDefinition(SGV));
210 // If imported as a declaration, it becomes external_weak.
211 return SGV->getLinkage();
212
214 // For weak_odr linkage, there is a guarantee that all copies will be
215 // equivalent, so the issue described above for weak_any does not exist,
216 // and the definition can be imported. It can be treated similarly
217 // to an imported externally visible global value.
218 if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
220 else
222
224 // It would be incorrect to import an appending linkage variable,
225 // since it would cause global constructors/destructors to be
226 // executed multiple times. This should have already been handled
227 // by linkIfNeeded, and we will assert in shouldLinkFromSource
228 // if we try to import, so we simply return AppendingLinkage.
230
233 // If we are promoting the local to global scope, it is handled
234 // similarly to a normal externally visible global.
235 if (DoPromote) {
236 if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
238 else
240 }
241 // A non-promoted imported local definition stays local.
242 // The ThinLTO pass will eventually force-import their definitions.
243 return SGV->getLinkage();
244
246 // External weak doesn't apply to definitions, must be a declaration.
247 assert(!doImportAsDefinition(SGV));
248 // Linkage stays external_weak.
249 return SGV->getLinkage();
250
252 // Linkage stays common on definitions.
253 // The ThinLTO pass will eventually force-import their definitions.
254 return SGV->getLinkage();
255 }
256
257 llvm_unreachable("unknown linkage type");
258}
259
260void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) {
261
262 ValueInfo VI;
263 if (GV.hasName())
264 VI = ImportIndex.getValueInfo(GV.getGUIDOrFallback());
265
266 // We should always have a ValueInfo (i.e. GV in index) for definitions when
267 // we are exporting, and also when importing that value.
268 assert(VI || GV.isDeclaration() ||
269 (isPerformingImport() && !doImportAsDefinition(&GV)));
270
271 // Mark read/write-only variables which can be imported with specific
272 // attribute. We can't internalize them now because IRMover will fail
273 // to link variable definitions to their external declarations during
274 // ThinLTO import. We'll internalize read-only variables later, after
275 // import is finished. See internalizeGVsAfterImport.
276 //
277 // If global value dead stripping is not enabled in summary then
278 // propagateConstants hasn't been run. We can't internalize GV
279 // in such case.
280 if (!GV.isDeclaration() && VI && ImportIndex.withAttributePropagation()) {
281 if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
282 // We can have more than one local with the same GUID, in the case of
283 // same-named locals in different but same-named source files that were
284 // compiled in their respective directories (so the source file name
285 // and resulting GUID is the same). Find the one in this module.
286 // Handle the case where there is no summary found in this module. That
287 // can happen in the distributed ThinLTO backend, because the index only
288 // contains summaries from the source modules if they are being imported.
289 // We might have a non-null VI and get here even in that case if the name
290 // matches one in this module (e.g. weak or appending linkage).
292 ImportIndex.findSummaryInModule(VI, M.getModuleIdentifier()));
293 if (GVS &&
294 (ImportIndex.isReadOnly(GVS) || ImportIndex.isWriteOnly(GVS))) {
295 V->addAttribute("thinlto-internalize");
296 // Objects referenced by writeonly GV initializer should not be
297 // promoted, because there is no any kind of read access to them
298 // on behalf of this writeonly GV. To avoid promotion we convert
299 // GV initializer to 'zeroinitializer'. This effectively drops
300 // references in IR module (not in combined index), so we can
301 // ignore them when computing import. We do not export references
302 // of writeonly object. See computeImportForReferencedGlobals
303 if (ImportIndex.isWriteOnly(GVS))
304 V->setInitializer(Constant::getNullValue(V->getValueType()));
305 }
306 }
307 }
308
309 GlobalValueSummary *Summary = nullptr;
310 if (VI && GV.hasLocalLinkage())
311 Summary = ImportIndex.findSummaryInModule(
312 VI, GV.getParent()->getModuleIdentifier());
313
314 assert((!Summary || !Summary->noRenameOnPromotion() ||
315 shouldPromoteLocalToGlobal(&GV, Summary)) &&
316 "noRenameOnPromotion requires promotion to external linkage");
317
318 if (GV.hasLocalLinkage() && shouldPromoteLocalToGlobal(&GV, Summary)) {
319 // Save the original name string before we rename GV below.
320 auto Name = GV.getName().str();
321 if (AlwaysRenamePromotedLocals || !Summary ||
322 !Summary->noRenameOnPromotion())
323 GV.setName(getPromotedName(&GV));
324
325 GV.setLinkage(getLinkage(&GV, /* DoPromote */ true));
326 assert(!GV.hasLocalLinkage());
328
329 // If we are renaming a COMDAT leader, ensure that we record the COMDAT
330 // for later renaming as well. This is required for COFF.
331 if (const auto *C = GV.getComdat())
332 if (C->getName() == Name)
333 RenamedComdats.try_emplace(C, M.getOrInsertComdat(GV.getName()));
334 } else
335 GV.setLinkage(getLinkage(&GV, /* DoPromote */ false));
336
337 // When ClearDSOLocalOnDeclarations is true, clear dso_local if GV is
338 // converted to a declaration, to disable direct access. Don't do this if GV
339 // is implicitly dso_local due to a non-default visibility.
340 if (ClearDSOLocalOnDeclarations &&
342 (isPerformingImport() && !doImportAsDefinition(&GV))) &&
343 !GV.isImplicitDSOLocal()) {
344 GV.setDSOLocal(false);
345 } else if (VI && VI.isDSOLocal(ImportIndex.withDSOLocalPropagation())) {
346 // If all summaries are dso_local, symbol gets resolved to a known local
347 // definition.
348 GV.setDSOLocal(true);
351 }
352
353 // Remove functions imported as available externally defs from comdats,
354 // as this is a declaration for the linker, and will be dropped eventually.
355 // It is illegal for comdats to contain declarations.
356 auto *GO = dyn_cast<GlobalObject>(&GV);
357 if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
358 // The IRMover should not have placed any imported declarations in
359 // a comdat, so the only declaration that should be in a comdat
360 // at this point would be a definition imported as available_externally.
361 assert(GO->hasAvailableExternallyLinkage() &&
362 "Expected comdat on definition (possibly available external)");
363 GO->setComdat(nullptr);
364 }
365}
366
367void FunctionImportGlobalProcessing::processGlobalsForThinLTO() {
368 for (GlobalVariable &GV : M.globals())
369 processGlobalForThinLTO(GV);
370 for (Function &SF : M)
371 processGlobalForThinLTO(SF);
372 for (GlobalAlias &GA : M.aliases())
373 processGlobalForThinLTO(GA);
374
375 // Replace any COMDATS that required renaming (because the COMDAT leader was
376 // promoted and renamed).
377 if (!RenamedComdats.empty())
378 for (auto &GO : M.global_objects())
379 if (auto *C = GO.getComdat()) {
380 auto Replacement = RenamedComdats.find(C);
381 if (Replacement != RenamedComdats.end())
382 GO.setComdat(Replacement->second);
383 }
384}
385
386void FunctionImportGlobalProcessing::run() { processGlobalsForThinLTO(); }
387
389 bool ClearDSOLocalOnDeclarations,
390 SetVector<GlobalValue *> *GlobalsToImport) {
391 llvm::TimeTraceScope timeScope("Rename module for ThinLTO");
392 FunctionImportGlobalProcessing ThinLTOProcessing(M, Index, GlobalsToImport,
393 ClearDSOLocalOnDeclarations);
394 ThinLTOProcessing.run();
395}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
DXIL Finalize Linkage
static bool isNonRenamableLocal(const GlobalValue &GV)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Class to handle necessary GlobalValue changes required by ThinLTO function importing,...
LLVM_ABI FunctionImportGlobalProcessing(Module &M, const ModuleSummaryIndex &Index, SetVector< GlobalValue * > *GlobalsToImport, bool ClearDSOLocalOnDeclarations)
Function and variable summary information to aid decisions and implementation of importing.
bool isImplicitDSOLocal() const
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:392
LinkageTypes getLinkage() const
bool hasLocalLinkage() const
GUID getGUIDOrFallback() const
Return the GUID for this value if it has been assigned, otherwise fall back to computing it based on ...
Definition Globals.cpp:103
void setDLLStorageClass(DLLStorageClassTypes C)
LLVM_ABI const Comdat * getComdat() const
Definition Globals.cpp:265
bool hasDLLImportStorageClass() const
void setLinkage(LinkageTypes LT)
bool isDeclarationForLinker() const
Module * getParent()
Get the module that this global value is contained inside of...
void setDSOLocal(bool Local)
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
bool hasSection() const
void setVisibility(VisibilityTypes V)
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash)
Convenience method for creating a promoted global name for the given value name of a local,...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
const std::string & getSourceFileName() const
Get the module's original source file name.
Definition Module.h:266
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition Module.h:255
A vector that has set insertion semantics.
Definition SetVector.h:57
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:393
bool hasName() const
Definition Value.h:261
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
cl::list< GlobalValue::GUID > MoveSymbolGUID
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
constexpr from_range_t from_range
LLVM_ABI void renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, bool ClearDSOLocalOnDeclarations, SetVector< GlobalValue * > *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
cl::opt< bool > AlwaysRenamePromotedLocals("always-rename-promoted-locals", cl::init(true), cl::Hidden, cl::desc("Always rename promoted locals."))
Definition LTO.cpp:114
static cl::opt< bool > UseSourceFilenameForPromotedLocals("use-source-filename-for-promoted-locals", cl::Hidden, cl::desc("Uses the source file name instead of the Module hash. " "This requires that the source filename has a unique name / " "path to avoid name collisions."))
Uses the "source_filename" instead of a Module hash ID for the suffix of promoted locals during LTO.
bool isAlnum(char C)
Checks whether character C is either a decimal digit or an uppercase or lowercase letter as classifie...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Definition Module.cpp:898
#define NDEBUG
Definition regutils.h:48