LLVM  8.0.0svn
FunctionImportUtils.cpp
Go to the documentation of this file.
1 //===- lib/Transforms/Utils/FunctionImportUtils.cpp - Importing utilities -===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the FunctionImportGlobalProcessing class, used
11 // to perform the necessary global value handling for function importing.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "llvm/IR/InstIterator.h"
17 using namespace llvm;
18 
19 /// Checks if we should import SGV as a definition, otherwise import as a
20 /// declaration.
21 bool FunctionImportGlobalProcessing::doImportAsDefinition(
22  const GlobalValue *SGV, SetVector<GlobalValue *> *GlobalsToImport) {
23 
24  // Only import the globals requested for importing.
25  if (!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)))
26  return false;
27 
28  assert(!isa<GlobalAlias>(SGV) &&
29  "Unexpected global alias in the import list.");
30 
31  // Otherwise yes.
32  return true;
33 }
34 
35 bool FunctionImportGlobalProcessing::doImportAsDefinition(
36  const GlobalValue *SGV) {
37  if (!isPerformingImport())
38  return false;
39  return FunctionImportGlobalProcessing::doImportAsDefinition(SGV,
40  GlobalsToImport);
41 }
42 
43 bool FunctionImportGlobalProcessing::shouldPromoteLocalToGlobal(
44  const GlobalValue *SGV) {
45  assert(SGV->hasLocalLinkage());
46  // Both the imported references and the original local variable must
47  // be promoted.
48  if (!isPerformingImport() && !isModuleExporting())
49  return false;
50 
51  if (isPerformingImport()) {
52  assert((!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)) ||
53  !isNonRenamableLocal(*SGV)) &&
54  "Attempting to promote non-renamable local");
55  // We don't know for sure yet if we are importing this value (as either
56  // a reference or a def), since we are simply walking all values in the
57  // module. But by necessity if we end up importing it and it is local,
58  // it must be promoted, so unconditionally promote all values in the
59  // importing module.
60  return true;
61  }
62 
63  // When exporting, consult the index. We can have more than one local
64  // with the same GUID, in the case of same-named locals in different but
65  // same-named source files that were compiled in their respective directories
66  // (so the source file name and resulting GUID is the same). Find the one
67  // in this module.
68  auto Summary = ImportIndex.findSummaryInModule(
69  SGV->getGUID(), SGV->getParent()->getModuleIdentifier());
70  assert(Summary && "Missing summary for global value when exporting");
71  auto Linkage = Summary->linkage();
72  if (!GlobalValue::isLocalLinkage(Linkage)) {
73  assert(!isNonRenamableLocal(*SGV) &&
74  "Attempting to promote non-renamable local");
75  return true;
76  }
77 
78  return false;
79 }
80 
81 #ifndef NDEBUG
82 bool FunctionImportGlobalProcessing::isNonRenamableLocal(
83  const GlobalValue &GV) const {
84  if (!GV.hasLocalLinkage())
85  return false;
86  // This needs to stay in sync with the logic in buildModuleSummaryIndex.
87  if (GV.hasSection())
88  return true;
89  if (Used.count(const_cast<GlobalValue *>(&GV)))
90  return true;
91  return false;
92 }
93 #endif
94 
95 std::string FunctionImportGlobalProcessing::getName(const GlobalValue *SGV,
96  bool DoPromote) {
97  // For locals that must be promoted to global scope, ensure that
98  // the promoted name uniquely identifies the copy in the original module,
99  // using the ID assigned during combined index creation. When importing,
100  // we rename all locals (not just those that are promoted) in order to
101  // avoid naming conflicts between locals imported from different modules.
102  if (SGV->hasLocalLinkage() && (DoPromote || isPerformingImport()))
104  SGV->getName(),
105  ImportIndex.getModuleHash(SGV->getParent()->getModuleIdentifier()));
106  return SGV->getName();
107 }
108 
110 FunctionImportGlobalProcessing::getLinkage(const GlobalValue *SGV,
111  bool DoPromote) {
112  // Any local variable that is referenced by an exported function needs
113  // to be promoted to global scope. Since we don't currently know which
114  // functions reference which local variables/functions, we must treat
115  // all as potentially exported if this module is exporting anything.
116  if (isModuleExporting()) {
117  if (SGV->hasLocalLinkage() && DoPromote)
119  return SGV->getLinkage();
120  }
121 
122  // Otherwise, if we aren't importing, no linkage change is needed.
123  if (!isPerformingImport())
124  return SGV->getLinkage();
125 
126  switch (SGV->getLinkage()) {
129  // External and linkonce definitions are converted to available_externally
130  // definitions upon import, so that they are available for inlining
131  // and/or optimization, but are turned into declarations later
132  // during the EliminateAvailableExternally pass.
133  if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
135  // An imported external declaration stays external.
136  return SGV->getLinkage();
137 
139  // An imported available_externally definition converts
140  // to external if imported as a declaration.
141  if (!doImportAsDefinition(SGV))
143  // An imported available_externally declaration stays that way.
144  return SGV->getLinkage();
145 
148  // Can't import linkonce_any/weak_any definitions correctly, or we might
149  // change the program semantics, since the linker will pick the first
150  // linkonce_any/weak_any definition and importing would change the order
151  // they are seen by the linker. The module linking caller needs to enforce
152  // this.
153  assert(!doImportAsDefinition(SGV));
154  // If imported as a declaration, it becomes external_weak.
155  return SGV->getLinkage();
156 
158  // For weak_odr linkage, there is a guarantee that all copies will be
159  // equivalent, so the issue described above for weak_any does not exist,
160  // and the definition can be imported. It can be treated similarly
161  // to an imported externally visible global value.
162  if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
164  else
166 
168  // It would be incorrect to import an appending linkage variable,
169  // since it would cause global constructors/destructors to be
170  // executed multiple times. This should have already been handled
171  // by linkIfNeeded, and we will assert in shouldLinkFromSource
172  // if we try to import, so we simply return AppendingLinkage.
174 
177  // If we are promoting the local to global scope, it is handled
178  // similarly to a normal externally visible global.
179  if (DoPromote) {
180  if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
182  else
184  }
185  // A non-promoted imported local definition stays local.
186  // The ThinLTO pass will eventually force-import their definitions.
187  return SGV->getLinkage();
188 
190  // External weak doesn't apply to definitions, must be a declaration.
191  assert(!doImportAsDefinition(SGV));
192  // Linkage stays external_weak.
193  return SGV->getLinkage();
194 
196  // Linkage stays common on definitions.
197  // The ThinLTO pass will eventually force-import their definitions.
198  return SGV->getLinkage();
199  }
200 
201  llvm_unreachable("unknown linkage type");
202 }
203 
204 void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) {
205 
206  // Check the summaries to see if the symbol gets resolved to a known local
207  // definition.
208  ValueInfo VI;
209  if (GV.hasName()) {
210  VI = ImportIndex.getValueInfo(GV.getGUID());
211  if (VI && VI.isDSOLocal()) {
212  GV.setDSOLocal(true);
213  if (GV.hasDLLImportStorageClass())
215  }
216  }
217 
218  // Mark read-only variables which can be imported with specific attribute.
219  // We can't internalize them now because IRMover will fail to link variable
220  // definitions to their external declarations during ThinLTO import. We'll
221  // internalize read-only variables later, after import is finished.
222  // See internalizeImmutableGVs.
223  //
224  // If global value dead stripping is not enabled in summary then
225  // propagateConstants hasn't been run. We can't internalize GV
226  // in such case.
227  if (!GV.isDeclaration() && VI && ImportIndex.withGlobalValueDeadStripping()) {
228  const auto &SL = VI.getSummaryList();
229  auto *GVS = SL.empty() ? nullptr : dyn_cast<GlobalVarSummary>(SL[0].get());
230  if (GVS && GVS->isReadOnly())
231  cast<GlobalVariable>(&GV)->addAttribute("thinlto-internalize");
232  }
233 
234  bool DoPromote = false;
235  if (GV.hasLocalLinkage() &&
236  ((DoPromote = shouldPromoteLocalToGlobal(&GV)) || isPerformingImport())) {
237  // Once we change the name or linkage it is difficult to determine
238  // again whether we should promote since shouldPromoteLocalToGlobal needs
239  // to locate the summary (based on GUID from name and linkage). Therefore,
240  // use DoPromote result saved above.
241  GV.setName(getName(&GV, DoPromote));
242  GV.setLinkage(getLinkage(&GV, DoPromote));
243  if (!GV.hasLocalLinkage())
245  } else
246  GV.setLinkage(getLinkage(&GV, /* DoPromote */ false));
247 
248  // Remove functions imported as available externally defs from comdats,
249  // as this is a declaration for the linker, and will be dropped eventually.
250  // It is illegal for comdats to contain declarations.
251  auto *GO = dyn_cast<GlobalObject>(&GV);
252  if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
253  // The IRMover should not have placed any imported declarations in
254  // a comdat, so the only declaration that should be in a comdat
255  // at this point would be a definition imported as available_externally.
256  assert(GO->hasAvailableExternallyLinkage() &&
257  "Expected comdat on definition (possibly available external)");
258  GO->setComdat(nullptr);
259  }
260 }
261 
262 void FunctionImportGlobalProcessing::processGlobalsForThinLTO() {
263  for (GlobalVariable &GV : M.globals())
264  processGlobalForThinLTO(GV);
265  for (Function &SF : M)
266  processGlobalForThinLTO(SF);
267  for (GlobalAlias &GA : M.aliases())
268  processGlobalForThinLTO(GA);
269 }
270 
272  processGlobalsForThinLTO();
273  return false;
274 }
275 
277  SetVector<GlobalValue *> *GlobalsToImport) {
278  FunctionImportGlobalProcessing ThinLTOProcessing(M, Index, GlobalsToImport);
279  return ThinLTOProcessing.run();
280 }
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:239
bool hasLocalLinkage() const
Definition: GlobalValue.h:436
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:55
This class represents lattice values for constants.
Definition: AllocatorList.h:24
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:64
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:54
GlobalValueSummary * findSummaryInModule(GlobalValue::GUID ValueGUID, StringRef ModuleId) const
Find the summary for global GUID in module ModuleId, or nullptr if not found.
Global variable summary information to aid decisions and implementation of importing.
Available for inspection, not emission.
Definition: GlobalValue.h:50
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:57
Externally visible function.
Definition: GlobalValue.h:49
Class to handle necessary GlobalValue changes required by ThinLTO function importing, including linkage changes and any necessary renaming.
bool hasDLLImportStorageClass() const
Definition: GlobalValue.h:262
Tentative definitions.
Definition: GlobalValue.h:59
static bool isLocalLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:321
bool hasSection() const
Definition: GlobalValue.h:270
static std::string getGlobalNameForLocal(StringRef Name, ModuleHash ModHash)
Convenience method for creating a promoted global name for the given value name of a local...
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:286
void setDLLStorageClass(DLLStorageClassTypes C)
Definition: GlobalValue.h:268
LinkageTypes getLinkage() const
Definition: GlobalValue.h:451
Class to hold module path string table and global value map, and encapsulate methods for operating on...
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Definition: SetVector.h:211
ExternalWeak linkage description.
Definition: GlobalValue.h:58
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:52
bool renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, SetVector< GlobalValue *> *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
bool hasName() const
Definition: Value.h:251
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
static GUID getGUID(StringRef GlobalName)
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:497
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:209
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Struct that holds a reference to a particular GUID in a global value summary.
bool isDSOLocal() const
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:51
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:445
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:48
ValueInfo getValueInfo(const GlobalValueSummaryMapTy::value_type &R) const
Return a ValueInfo for the index value_type (convenient when iterating index).
bool withGlobalValueDeadStripping() const
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:215
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:53
Rename collisions when linking (static functions).
Definition: GlobalValue.h:56
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:206
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:566
A vector that has set insertion semantics.
Definition: SetVector.h:41
iterator_range< global_iterator > globals()
Definition: Module.h:574
void setDSOLocal(bool Local)
Definition: GlobalValue.h:278