1488a800aSTeresa Johnson //===- lib/Transforms/Utils/FunctionImportUtils.cpp - Importing utilities -===//
2488a800aSTeresa Johnson //
3488a800aSTeresa Johnson //                     The LLVM Compiler Infrastructure
4488a800aSTeresa Johnson //
5488a800aSTeresa Johnson // This file is distributed under the University of Illinois Open Source
6488a800aSTeresa Johnson // License. See LICENSE.TXT for details.
7488a800aSTeresa Johnson //
8488a800aSTeresa Johnson //===----------------------------------------------------------------------===//
9488a800aSTeresa Johnson //
10488a800aSTeresa Johnson // This file implements the FunctionImportGlobalProcessing class, used
11488a800aSTeresa Johnson // to perform the necessary global value handling for function importing.
12488a800aSTeresa Johnson //
13488a800aSTeresa Johnson //===----------------------------------------------------------------------===//
14488a800aSTeresa Johnson 
15488a800aSTeresa Johnson #include "llvm/Transforms/Utils/FunctionImportUtils.h"
166bda14b3SChandler Carruth #include "llvm/Analysis/ModuleSummaryAnalysis.h"
17df5ef871STeresa Johnson #include "llvm/IR/InstIterator.h"
18df5ef871STeresa Johnson #include "llvm/IR/Instructions.h"
19488a800aSTeresa Johnson using namespace llvm;
20488a800aSTeresa Johnson 
21488a800aSTeresa Johnson /// Checks if we should import SGV as a definition, otherwise import as a
22488a800aSTeresa Johnson /// declaration.
23488a800aSTeresa Johnson bool FunctionImportGlobalProcessing::doImportAsDefinition(
246d8f817fSPeter Collingbourne     const GlobalValue *SGV, SetVector<GlobalValue *> *GlobalsToImport) {
258d05185aSMehdi Amini 
268d05185aSMehdi Amini   // Only import the globals requested for importing.
276d8f817fSPeter Collingbourne   if (GlobalsToImport->count(const_cast<GlobalValue *>(SGV)))
28488a800aSTeresa Johnson     return true;
29*2f0cc477SDavid Blaikie 
30*2f0cc477SDavid Blaikie   assert(!isa<GlobalAlias>(SGV) &&
31*2f0cc477SDavid Blaikie          "Unexpected global alias in the import list.");
32*2f0cc477SDavid Blaikie 
33488a800aSTeresa Johnson   // Otherwise no.
34488a800aSTeresa Johnson   return false;
35488a800aSTeresa Johnson }
36488a800aSTeresa Johnson 
37488a800aSTeresa Johnson bool FunctionImportGlobalProcessing::doImportAsDefinition(
38488a800aSTeresa Johnson     const GlobalValue *SGV) {
39488a800aSTeresa Johnson   if (!isPerformingImport())
40488a800aSTeresa Johnson     return false;
418d05185aSMehdi Amini   return FunctionImportGlobalProcessing::doImportAsDefinition(SGV,
428d05185aSMehdi Amini                                                               GlobalsToImport);
43488a800aSTeresa Johnson }
44488a800aSTeresa Johnson 
4538d4df71STeresa Johnson bool FunctionImportGlobalProcessing::shouldPromoteLocalToGlobal(
46488a800aSTeresa Johnson     const GlobalValue *SGV) {
47488a800aSTeresa Johnson   assert(SGV->hasLocalLinkage());
48488a800aSTeresa Johnson   // Both the imported references and the original local variable must
49488a800aSTeresa Johnson   // be promoted.
50488a800aSTeresa Johnson   if (!isPerformingImport() && !isModuleExporting())
51488a800aSTeresa Johnson     return false;
52488a800aSTeresa Johnson 
534fef68cbSTeresa Johnson   if (isPerformingImport()) {
546d8f817fSPeter Collingbourne     assert((!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)) ||
556d8f817fSPeter Collingbourne             !isNonRenamableLocal(*SGV)) &&
56519465b9STeresa Johnson            "Attempting to promote non-renamable local");
574fef68cbSTeresa Johnson     // We don't know for sure yet if we are importing this value (as either
584fef68cbSTeresa Johnson     // a reference or a def), since we are simply walking all values in the
594fef68cbSTeresa Johnson     // module. But by necessity if we end up importing it and it is local,
604fef68cbSTeresa Johnson     // it must be promoted, so unconditionally promote all values in the
614fef68cbSTeresa Johnson     // importing module.
624fef68cbSTeresa Johnson     return true;
630515fb8dSTeresa Johnson   }
64b4e1e829SMehdi Amini 
659006d526STeresa Johnson   // When exporting, consult the index. We can have more than one local
669006d526STeresa Johnson   // with the same GUID, in the case of same-named locals in different but
679006d526STeresa Johnson   // same-named source files that were compiled in their respective directories
689006d526STeresa Johnson   // (so the source file name and resulting GUID is the same). Find the one
699006d526STeresa Johnson   // in this module.
709006d526STeresa Johnson   auto Summary = ImportIndex.findSummaryInModule(
719006d526STeresa Johnson       SGV->getGUID(), SGV->getParent()->getModuleIdentifier());
729006d526STeresa Johnson   assert(Summary && "Missing summary for global value when exporting");
739006d526STeresa Johnson   auto Linkage = Summary->linkage();
744fef68cbSTeresa Johnson   if (!GlobalValue::isLocalLinkage(Linkage)) {
75519465b9STeresa Johnson     assert(!isNonRenamableLocal(*SGV) &&
76519465b9STeresa Johnson            "Attempting to promote non-renamable local");
77488a800aSTeresa Johnson     return true;
78488a800aSTeresa Johnson   }
79488a800aSTeresa Johnson 
804fef68cbSTeresa Johnson   return false;
814fef68cbSTeresa Johnson }
824fef68cbSTeresa Johnson 
83519465b9STeresa Johnson #ifndef NDEBUG
84519465b9STeresa Johnson bool FunctionImportGlobalProcessing::isNonRenamableLocal(
85519465b9STeresa Johnson     const GlobalValue &GV) const {
86519465b9STeresa Johnson   if (!GV.hasLocalLinkage())
87519465b9STeresa Johnson     return false;
88519465b9STeresa Johnson   // This needs to stay in sync with the logic in buildModuleSummaryIndex.
89519465b9STeresa Johnson   if (GV.hasSection())
90519465b9STeresa Johnson     return true;
91519465b9STeresa Johnson   if (Used.count(const_cast<GlobalValue *>(&GV)))
92519465b9STeresa Johnson     return true;
93519465b9STeresa Johnson   return false;
94519465b9STeresa Johnson }
95519465b9STeresa Johnson #endif
96519465b9STeresa Johnson 
971b9c2be8STeresa Johnson std::string FunctionImportGlobalProcessing::getName(const GlobalValue *SGV,
981b9c2be8STeresa Johnson                                                     bool DoPromote) {
99488a800aSTeresa Johnson   // For locals that must be promoted to global scope, ensure that
100488a800aSTeresa Johnson   // the promoted name uniquely identifies the copy in the original module,
101488a800aSTeresa Johnson   // using the ID assigned during combined index creation. When importing,
102488a800aSTeresa Johnson   // we rename all locals (not just those that are promoted) in order to
103488a800aSTeresa Johnson   // avoid naming conflicts between locals imported from different modules.
1041b9c2be8STeresa Johnson   if (SGV->hasLocalLinkage() && (DoPromote || isPerformingImport()))
10526ab5772STeresa Johnson     return ModuleSummaryIndex::getGlobalNameForLocal(
106488a800aSTeresa Johnson         SGV->getName(),
107ae280e54SMehdi Amini         ImportIndex.getModuleHash(SGV->getParent()->getModuleIdentifier()));
108488a800aSTeresa Johnson   return SGV->getName();
109488a800aSTeresa Johnson }
110488a800aSTeresa Johnson 
111488a800aSTeresa Johnson GlobalValue::LinkageTypes
1121b9c2be8STeresa Johnson FunctionImportGlobalProcessing::getLinkage(const GlobalValue *SGV,
1131b9c2be8STeresa Johnson                                            bool DoPromote) {
114488a800aSTeresa Johnson   // Any local variable that is referenced by an exported function needs
115488a800aSTeresa Johnson   // to be promoted to global scope. Since we don't currently know which
116488a800aSTeresa Johnson   // functions reference which local variables/functions, we must treat
117488a800aSTeresa Johnson   // all as potentially exported if this module is exporting anything.
118488a800aSTeresa Johnson   if (isModuleExporting()) {
1191b9c2be8STeresa Johnson     if (SGV->hasLocalLinkage() && DoPromote)
120488a800aSTeresa Johnson       return GlobalValue::ExternalLinkage;
121488a800aSTeresa Johnson     return SGV->getLinkage();
122488a800aSTeresa Johnson   }
123488a800aSTeresa Johnson 
124488a800aSTeresa Johnson   // Otherwise, if we aren't importing, no linkage change is needed.
125488a800aSTeresa Johnson   if (!isPerformingImport())
126488a800aSTeresa Johnson     return SGV->getLinkage();
127488a800aSTeresa Johnson 
128488a800aSTeresa Johnson   switch (SGV->getLinkage()) {
129*2f0cc477SDavid Blaikie   case GlobalValue::LinkOnceAnyLinkage:
130*2f0cc477SDavid Blaikie   case GlobalValue::LinkOnceODRLinkage:
131488a800aSTeresa Johnson   case GlobalValue::ExternalLinkage:
132*2f0cc477SDavid Blaikie     // External and linkonce definitions are converted to available_externally
133488a800aSTeresa Johnson     // definitions upon import, so that they are available for inlining
134488a800aSTeresa Johnson     // and/or optimization, but are turned into declarations later
135488a800aSTeresa Johnson     // during the EliminateAvailableExternally pass.
136488a800aSTeresa Johnson     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
137488a800aSTeresa Johnson       return GlobalValue::AvailableExternallyLinkage;
138488a800aSTeresa Johnson     // An imported external declaration stays external.
139488a800aSTeresa Johnson     return SGV->getLinkage();
140488a800aSTeresa Johnson 
141488a800aSTeresa Johnson   case GlobalValue::AvailableExternallyLinkage:
142488a800aSTeresa Johnson     // An imported available_externally definition converts
143488a800aSTeresa Johnson     // to external if imported as a declaration.
144488a800aSTeresa Johnson     if (!doImportAsDefinition(SGV))
145488a800aSTeresa Johnson       return GlobalValue::ExternalLinkage;
146488a800aSTeresa Johnson     // An imported available_externally declaration stays that way.
147488a800aSTeresa Johnson     return SGV->getLinkage();
148488a800aSTeresa Johnson 
149488a800aSTeresa Johnson   case GlobalValue::WeakAnyLinkage:
150488a800aSTeresa Johnson     // Can't import weak_any definitions correctly, or we might change the
151488a800aSTeresa Johnson     // program semantics, since the linker will pick the first weak_any
152488a800aSTeresa Johnson     // definition and importing would change the order they are seen by the
153488a800aSTeresa Johnson     // linker. The module linking caller needs to enforce this.
154488a800aSTeresa Johnson     assert(!doImportAsDefinition(SGV));
155488a800aSTeresa Johnson     // If imported as a declaration, it becomes external_weak.
156bb3a1d92SMehdi Amini     return SGV->getLinkage();
157488a800aSTeresa Johnson 
158488a800aSTeresa Johnson   case GlobalValue::WeakODRLinkage:
159488a800aSTeresa Johnson     // For weak_odr linkage, there is a guarantee that all copies will be
160488a800aSTeresa Johnson     // equivalent, so the issue described above for weak_any does not exist,
161488a800aSTeresa Johnson     // and the definition can be imported. It can be treated similarly
162488a800aSTeresa Johnson     // to an imported externally visible global value.
163488a800aSTeresa Johnson     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
164488a800aSTeresa Johnson       return GlobalValue::AvailableExternallyLinkage;
165488a800aSTeresa Johnson     else
166488a800aSTeresa Johnson       return GlobalValue::ExternalLinkage;
167488a800aSTeresa Johnson 
168488a800aSTeresa Johnson   case GlobalValue::AppendingLinkage:
169488a800aSTeresa Johnson     // It would be incorrect to import an appending linkage variable,
170488a800aSTeresa Johnson     // since it would cause global constructors/destructors to be
171488a800aSTeresa Johnson     // executed multiple times. This should have already been handled
172488a800aSTeresa Johnson     // by linkIfNeeded, and we will assert in shouldLinkFromSource
173488a800aSTeresa Johnson     // if we try to import, so we simply return AppendingLinkage.
174488a800aSTeresa Johnson     return GlobalValue::AppendingLinkage;
175488a800aSTeresa Johnson 
176488a800aSTeresa Johnson   case GlobalValue::InternalLinkage:
177488a800aSTeresa Johnson   case GlobalValue::PrivateLinkage:
178488a800aSTeresa Johnson     // If we are promoting the local to global scope, it is handled
179488a800aSTeresa Johnson     // similarly to a normal externally visible global.
1801b9c2be8STeresa Johnson     if (DoPromote) {
181488a800aSTeresa Johnson       if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
182488a800aSTeresa Johnson         return GlobalValue::AvailableExternallyLinkage;
183488a800aSTeresa Johnson       else
184488a800aSTeresa Johnson         return GlobalValue::ExternalLinkage;
185488a800aSTeresa Johnson     }
186488a800aSTeresa Johnson     // A non-promoted imported local definition stays local.
187488a800aSTeresa Johnson     // The ThinLTO pass will eventually force-import their definitions.
188488a800aSTeresa Johnson     return SGV->getLinkage();
189488a800aSTeresa Johnson 
190488a800aSTeresa Johnson   case GlobalValue::ExternalWeakLinkage:
191488a800aSTeresa Johnson     // External weak doesn't apply to definitions, must be a declaration.
192488a800aSTeresa Johnson     assert(!doImportAsDefinition(SGV));
193488a800aSTeresa Johnson     // Linkage stays external_weak.
194488a800aSTeresa Johnson     return SGV->getLinkage();
195488a800aSTeresa Johnson 
196488a800aSTeresa Johnson   case GlobalValue::CommonLinkage:
197488a800aSTeresa Johnson     // Linkage stays common on definitions.
198488a800aSTeresa Johnson     // The ThinLTO pass will eventually force-import their definitions.
199488a800aSTeresa Johnson     return SGV->getLinkage();
200488a800aSTeresa Johnson   }
201488a800aSTeresa Johnson 
202488a800aSTeresa Johnson   llvm_unreachable("unknown linkage type");
203488a800aSTeresa Johnson }
204488a800aSTeresa Johnson 
205488a800aSTeresa Johnson void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) {
2061b9c2be8STeresa Johnson   bool DoPromote = false;
207488a800aSTeresa Johnson   if (GV.hasLocalLinkage() &&
20838d4df71STeresa Johnson       ((DoPromote = shouldPromoteLocalToGlobal(&GV)) || isPerformingImport())) {
2091b9c2be8STeresa Johnson     // Once we change the name or linkage it is difficult to determine
21038d4df71STeresa Johnson     // again whether we should promote since shouldPromoteLocalToGlobal needs
2111b9c2be8STeresa Johnson     // to locate the summary (based on GUID from name and linkage). Therefore,
2121b9c2be8STeresa Johnson     // use DoPromote result saved above.
2131b9c2be8STeresa Johnson     GV.setName(getName(&GV, DoPromote));
2141b9c2be8STeresa Johnson     GV.setLinkage(getLinkage(&GV, DoPromote));
215488a800aSTeresa Johnson     if (!GV.hasLocalLinkage())
216488a800aSTeresa Johnson       GV.setVisibility(GlobalValue::HiddenVisibility);
217488a800aSTeresa Johnson   } else
2181b9c2be8STeresa Johnson     GV.setLinkage(getLinkage(&GV, /* DoPromote */ false));
219488a800aSTeresa Johnson 
220488a800aSTeresa Johnson   // Remove functions imported as available externally defs from comdats,
221488a800aSTeresa Johnson   // as this is a declaration for the linker, and will be dropped eventually.
222488a800aSTeresa Johnson   // It is illegal for comdats to contain declarations.
223488a800aSTeresa Johnson   auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
224488a800aSTeresa Johnson   if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
225488a800aSTeresa Johnson     // The IRMover should not have placed any imported declarations in
226488a800aSTeresa Johnson     // a comdat, so the only declaration that should be in a comdat
227488a800aSTeresa Johnson     // at this point would be a definition imported as available_externally.
228488a800aSTeresa Johnson     assert(GO->hasAvailableExternallyLinkage() &&
229488a800aSTeresa Johnson            "Expected comdat on definition (possibly available external)");
230488a800aSTeresa Johnson     GO->setComdat(nullptr);
231488a800aSTeresa Johnson   }
232488a800aSTeresa Johnson }
233488a800aSTeresa Johnson 
234488a800aSTeresa Johnson void FunctionImportGlobalProcessing::processGlobalsForThinLTO() {
235488a800aSTeresa Johnson   for (GlobalVariable &GV : M.globals())
236488a800aSTeresa Johnson     processGlobalForThinLTO(GV);
237488a800aSTeresa Johnson   for (Function &SF : M)
238488a800aSTeresa Johnson     processGlobalForThinLTO(SF);
239488a800aSTeresa Johnson   for (GlobalAlias &GA : M.aliases())
240488a800aSTeresa Johnson     processGlobalForThinLTO(GA);
241488a800aSTeresa Johnson }
242488a800aSTeresa Johnson 
243488a800aSTeresa Johnson bool FunctionImportGlobalProcessing::run() {
244488a800aSTeresa Johnson   processGlobalsForThinLTO();
245488a800aSTeresa Johnson   return false;
246488a800aSTeresa Johnson }
247488a800aSTeresa Johnson 
2486d8f817fSPeter Collingbourne bool llvm::renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index,
2496d8f817fSPeter Collingbourne                                   SetVector<GlobalValue *> *GlobalsToImport) {
2508d05185aSMehdi Amini   FunctionImportGlobalProcessing ThinLTOProcessing(M, Index, GlobalsToImport);
251488a800aSTeresa Johnson   return ThinLTOProcessing.run();
252488a800aSTeresa Johnson }
253