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