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 
15 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
16 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
17 #include "llvm/IR/InstIterator.h"
18 #include "llvm/IR/Instructions.h"
19 using namespace llvm;
20 
21 /// Checks if we should import SGV as a definition, otherwise import as a
22 /// declaration.
23 bool FunctionImportGlobalProcessing::doImportAsDefinition(
24     const GlobalValue *SGV, DenseSet<const GlobalValue *> *GlobalsToImport) {
25 
26   // For alias, we tie the definition to the base object. Extract it and recurse
27   if (auto *GA = dyn_cast<GlobalAlias>(SGV)) {
28     if (GA->hasWeakAnyLinkage())
29       return false;
30     const GlobalObject *GO = GA->getBaseObject();
31     if (!GO->hasLinkOnceODRLinkage())
32       return false;
33     return FunctionImportGlobalProcessing::doImportAsDefinition(
34         GO, GlobalsToImport);
35   }
36   // Only import the globals requested for importing.
37   if (GlobalsToImport->count(SGV))
38     return true;
39   // Otherwise no.
40   return false;
41 }
42 
43 bool FunctionImportGlobalProcessing::doImportAsDefinition(
44     const GlobalValue *SGV) {
45   if (!isPerformingImport())
46     return false;
47   return FunctionImportGlobalProcessing::doImportAsDefinition(SGV,
48                                                               GlobalsToImport);
49 }
50 
51 bool FunctionImportGlobalProcessing::shouldPromoteLocalToGlobal(
52     const GlobalValue *SGV) {
53   assert(SGV->hasLocalLinkage());
54   // Both the imported references and the original local variable must
55   // be promoted.
56   if (!isPerformingImport() && !isModuleExporting())
57     return false;
58 
59   // Local const variables never need to be promoted unless they are address
60   // taken. The imported uses can simply use the clone created in this module.
61   // For now we are conservative in determining which variables are not
62   // address taken by checking the unnamed addr flag. To be more aggressive,
63   // the address taken information must be checked earlier during parsing
64   // of the module and recorded in the summary index for use when importing
65   // from that module.
66   auto *GVar = dyn_cast<GlobalVariable>(SGV);
67   if (GVar && GVar->isConstant() && GVar->hasGlobalUnnamedAddr())
68     return false;
69 
70   auto *Summary = ImportIndex.getGlobalValueSummary(SGV->getGUID());
71   assert(Summary && "Missing summary for global value");
72   if (Summary->noRename())
73     return false;
74 
75   // Eventually we only need to promote functions in the exporting module that
76   // are referenced by a potentially exported function (i.e. one that is in the
77   // summary index).
78   return true;
79 }
80 
81 std::string FunctionImportGlobalProcessing::getName(const GlobalValue *SGV,
82                                                     bool DoPromote) {
83   // For locals that must be promoted to global scope, ensure that
84   // the promoted name uniquely identifies the copy in the original module,
85   // using the ID assigned during combined index creation. When importing,
86   // we rename all locals (not just those that are promoted) in order to
87   // avoid naming conflicts between locals imported from different modules.
88   if (SGV->hasLocalLinkage() && (DoPromote || isPerformingImport()))
89     return ModuleSummaryIndex::getGlobalNameForLocal(
90         SGV->getName(),
91         ImportIndex.getModuleHash(SGV->getParent()->getModuleIdentifier()));
92   return SGV->getName();
93 }
94 
95 GlobalValue::LinkageTypes
96 FunctionImportGlobalProcessing::getLinkage(const GlobalValue *SGV,
97                                            bool DoPromote) {
98   // Any local variable that is referenced by an exported function needs
99   // to be promoted to global scope. Since we don't currently know which
100   // functions reference which local variables/functions, we must treat
101   // all as potentially exported if this module is exporting anything.
102   if (isModuleExporting()) {
103     if (SGV->hasLocalLinkage() && DoPromote)
104       return GlobalValue::ExternalLinkage;
105     return SGV->getLinkage();
106   }
107 
108   // Otherwise, if we aren't importing, no linkage change is needed.
109   if (!isPerformingImport())
110     return SGV->getLinkage();
111 
112   switch (SGV->getLinkage()) {
113   case GlobalValue::ExternalLinkage:
114     // External defnitions are converted to available_externally
115     // definitions upon import, so that they are available for inlining
116     // and/or optimization, but are turned into declarations later
117     // during the EliminateAvailableExternally pass.
118     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
119       return GlobalValue::AvailableExternallyLinkage;
120     // An imported external declaration stays external.
121     return SGV->getLinkage();
122 
123   case GlobalValue::AvailableExternallyLinkage:
124     // An imported available_externally definition converts
125     // to external if imported as a declaration.
126     if (!doImportAsDefinition(SGV))
127       return GlobalValue::ExternalLinkage;
128     // An imported available_externally declaration stays that way.
129     return SGV->getLinkage();
130 
131   case GlobalValue::LinkOnceAnyLinkage:
132   case GlobalValue::LinkOnceODRLinkage:
133     // These both stay the same when importing the definition.
134     // The ThinLTO pass will eventually force-import their definitions.
135     return SGV->getLinkage();
136 
137   case GlobalValue::WeakAnyLinkage:
138     // Can't import weak_any definitions correctly, or we might change the
139     // program semantics, since the linker will pick the first weak_any
140     // definition and importing would change the order they are seen by the
141     // linker. The module linking caller needs to enforce this.
142     assert(!doImportAsDefinition(SGV));
143     // If imported as a declaration, it becomes external_weak.
144     return SGV->getLinkage();
145 
146   case GlobalValue::WeakODRLinkage:
147     // For weak_odr linkage, there is a guarantee that all copies will be
148     // equivalent, so the issue described above for weak_any does not exist,
149     // and the definition can be imported. It can be treated similarly
150     // to an imported externally visible global value.
151     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
152       return GlobalValue::AvailableExternallyLinkage;
153     else
154       return GlobalValue::ExternalLinkage;
155 
156   case GlobalValue::AppendingLinkage:
157     // It would be incorrect to import an appending linkage variable,
158     // since it would cause global constructors/destructors to be
159     // executed multiple times. This should have already been handled
160     // by linkIfNeeded, and we will assert in shouldLinkFromSource
161     // if we try to import, so we simply return AppendingLinkage.
162     return GlobalValue::AppendingLinkage;
163 
164   case GlobalValue::InternalLinkage:
165   case GlobalValue::PrivateLinkage:
166     // If we are promoting the local to global scope, it is handled
167     // similarly to a normal externally visible global.
168     if (DoPromote) {
169       if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
170         return GlobalValue::AvailableExternallyLinkage;
171       else
172         return GlobalValue::ExternalLinkage;
173     }
174     // A non-promoted imported local definition stays local.
175     // The ThinLTO pass will eventually force-import their definitions.
176     return SGV->getLinkage();
177 
178   case GlobalValue::ExternalWeakLinkage:
179     // External weak doesn't apply to definitions, must be a declaration.
180     assert(!doImportAsDefinition(SGV));
181     // Linkage stays external_weak.
182     return SGV->getLinkage();
183 
184   case GlobalValue::CommonLinkage:
185     // Linkage stays common on definitions.
186     // The ThinLTO pass will eventually force-import their definitions.
187     return SGV->getLinkage();
188   }
189 
190   llvm_unreachable("unknown linkage type");
191 }
192 
193 void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) {
194   bool DoPromote = false;
195   if (GV.hasLocalLinkage() &&
196       ((DoPromote = shouldPromoteLocalToGlobal(&GV)) || isPerformingImport())) {
197     // Once we change the name or linkage it is difficult to determine
198     // again whether we should promote since shouldPromoteLocalToGlobal needs
199     // to locate the summary (based on GUID from name and linkage). Therefore,
200     // use DoPromote result saved above.
201     GV.setName(getName(&GV, DoPromote));
202     GV.setLinkage(getLinkage(&GV, DoPromote));
203     if (!GV.hasLocalLinkage())
204       GV.setVisibility(GlobalValue::HiddenVisibility);
205   } else
206     GV.setLinkage(getLinkage(&GV, /* DoPromote */ false));
207 
208   // Remove functions imported as available externally defs from comdats,
209   // as this is a declaration for the linker, and will be dropped eventually.
210   // It is illegal for comdats to contain declarations.
211   auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
212   if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
213     // The IRMover should not have placed any imported declarations in
214     // a comdat, so the only declaration that should be in a comdat
215     // at this point would be a definition imported as available_externally.
216     assert(GO->hasAvailableExternallyLinkage() &&
217            "Expected comdat on definition (possibly available external)");
218     GO->setComdat(nullptr);
219   }
220 }
221 
222 void FunctionImportGlobalProcessing::processGlobalsForThinLTO() {
223   for (GlobalVariable &GV : M.globals())
224     processGlobalForThinLTO(GV);
225   for (Function &SF : M)
226     processGlobalForThinLTO(SF);
227   for (GlobalAlias &GA : M.aliases())
228     processGlobalForThinLTO(GA);
229 }
230 
231 bool FunctionImportGlobalProcessing::run() {
232   processGlobalsForThinLTO();
233   return false;
234 }
235 
236 bool llvm::renameModuleForThinLTO(
237     Module &M, const ModuleSummaryIndex &Index,
238     DenseSet<const GlobalValue *> *GlobalsToImport) {
239   FunctionImportGlobalProcessing ThinLTOProcessing(M, Index, GlobalsToImport);
240   return ThinLTOProcessing.run();
241 }
242