1 //===- NameAnonGlobals.cpp - ThinLTO Support: Name Unnamed Globals --------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements naming anonymous globals to make sure they can be
10 // referred to by ThinLTO.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/IR/Module.h"
17 #include "llvm/Support/MD5.h"
18 #include "llvm/Transforms/Utils/ModuleUtils.h"
23 // Compute a "unique" hash for the module based on the name of the public
30 ModuleHasher(Module
&M
) : TheModule(M
) {}
32 /// Return the lazily computed hash.
39 for (auto &F
: TheModule
) {
40 if (F
.isDeclaration() || F
.hasLocalLinkage() || !F
.hasName())
42 auto Name
= F
.getName();
45 for (auto &GV
: TheModule
.globals()) {
46 if (GV
.isDeclaration() || GV
.hasLocalLinkage() || !GV
.hasName())
48 auto Name
= GV
.getName();
52 // Now return the result.
55 SmallString
<32> Result
;
56 MD5::stringifyResult(Hash
, Result
);
57 TheHash
= std::string(Result
);
61 } // end anonymous namespace
63 // Rename all the anon globals in the module
64 bool llvm::nameUnamedGlobals(Module
&M
) {
66 ModuleHasher
ModuleHash(M
);
68 auto RenameIfNeed
= [&](GlobalValue
&GV
) {
71 GV
.setName(Twine("anon.") + ModuleHash
.get() + "." + Twine(count
++));
74 for (auto &GO
: M
.global_objects())
76 for (auto &GA
: M
.aliases())
82 PreservedAnalyses
NameAnonGlobalPass::run(Module
&M
,
83 ModuleAnalysisManager
&AM
) {
84 if (!nameUnamedGlobals(M
))
85 return PreservedAnalyses::all();
87 return PreservedAnalyses::none();