1 //===- lib/Transforms/Utils/FunctionImportUtils.cpp - Importing utilities -===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the FunctionImportGlobalProcessing class, used
10 // to perform the necessary global value handling for function importing.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
15 #include "llvm/IR/Constants.h"
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
96 FunctionImportGlobalProcessing::getPromotedName(const GlobalValue *SGV) {
97   assert(SGV->hasLocalLinkage());
98   // For locals that must be promoted to global scope, ensure that
99   // the promoted name uniquely identifies the copy in the original module,
100   // using the ID assigned during combined index creation.
101   return ModuleSummaryIndex::getGlobalNameForLocal(
102       SGV->getName(),
103       ImportIndex.getModuleHash(SGV->getParent()->getModuleIdentifier()));
104 }
105 
106 GlobalValue::LinkageTypes
107 FunctionImportGlobalProcessing::getLinkage(const GlobalValue *SGV,
108                                            bool DoPromote) {
109   // Any local variable that is referenced by an exported function needs
110   // to be promoted to global scope. Since we don't currently know which
111   // functions reference which local variables/functions, we must treat
112   // all as potentially exported if this module is exporting anything.
113   if (isModuleExporting()) {
114     if (SGV->hasLocalLinkage() && DoPromote)
115       return GlobalValue::ExternalLinkage;
116     return SGV->getLinkage();
117   }
118 
119   // Otherwise, if we aren't importing, no linkage change is needed.
120   if (!isPerformingImport())
121     return SGV->getLinkage();
122 
123   switch (SGV->getLinkage()) {
124   case GlobalValue::LinkOnceODRLinkage:
125   case GlobalValue::ExternalLinkage:
126     // External and linkonce definitions are converted to available_externally
127     // definitions upon import, so that they are available for inlining
128     // and/or optimization, but are turned into declarations later
129     // during the EliminateAvailableExternally pass.
130     if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
131       return GlobalValue::AvailableExternallyLinkage;
132     // An imported external declaration stays external.
133     return SGV->getLinkage();
134 
135   case GlobalValue::AvailableExternallyLinkage:
136     // An imported available_externally definition converts
137     // to external if imported as a declaration.
138     if (!doImportAsDefinition(SGV))
139       return GlobalValue::ExternalLinkage;
140     // An imported available_externally declaration stays that way.
141     return SGV->getLinkage();
142 
143   case GlobalValue::LinkOnceAnyLinkage:
144   case GlobalValue::WeakAnyLinkage:
145     // Can't import linkonce_any/weak_any definitions correctly, or we might
146     // change the program semantics, since the linker will pick the first
147     // linkonce_any/weak_any definition and importing would change the order
148     // they are seen by the linker. The module linking caller needs to enforce
149     // this.
150     assert(!doImportAsDefinition(SGV));
151     // If imported as a declaration, it becomes external_weak.
152     return SGV->getLinkage();
153 
154   case GlobalValue::WeakODRLinkage:
155     // For weak_odr linkage, there is a guarantee that all copies will be
156     // equivalent, so the issue described above for weak_any does not exist,
157     // and the definition can be imported. It can be treated similarly
158     // to an imported externally visible global value.
159     if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
160       return GlobalValue::AvailableExternallyLinkage;
161     else
162       return GlobalValue::ExternalLinkage;
163 
164   case GlobalValue::AppendingLinkage:
165     // It would be incorrect to import an appending linkage variable,
166     // since it would cause global constructors/destructors to be
167     // executed multiple times. This should have already been handled
168     // by linkIfNeeded, and we will assert in shouldLinkFromSource
169     // if we try to import, so we simply return AppendingLinkage.
170     return GlobalValue::AppendingLinkage;
171 
172   case GlobalValue::InternalLinkage:
173   case GlobalValue::PrivateLinkage:
174     // If we are promoting the local to global scope, it is handled
175     // similarly to a normal externally visible global.
176     if (DoPromote) {
177       if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
178         return GlobalValue::AvailableExternallyLinkage;
179       else
180         return GlobalValue::ExternalLinkage;
181     }
182     // A non-promoted imported local definition stays local.
183     // The ThinLTO pass will eventually force-import their definitions.
184     return SGV->getLinkage();
185 
186   case GlobalValue::ExternalWeakLinkage:
187     // External weak doesn't apply to definitions, must be a declaration.
188     assert(!doImportAsDefinition(SGV));
189     // Linkage stays external_weak.
190     return SGV->getLinkage();
191 
192   case GlobalValue::CommonLinkage:
193     // Linkage stays common on definitions.
194     // The ThinLTO pass will eventually force-import their definitions.
195     return SGV->getLinkage();
196   }
197 
198   llvm_unreachable("unknown linkage type");
199 }
200 
201 void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) {
202 
203   ValueInfo VI;
204   if (GV.hasName()) {
205     VI = ImportIndex.getValueInfo(GV.getGUID());
206     // Set synthetic function entry counts.
207     if (VI && ImportIndex.hasSyntheticEntryCounts()) {
208       if (Function *F = dyn_cast<Function>(&GV)) {
209         if (!F->isDeclaration()) {
210           for (auto &S : VI.getSummaryList()) {
211             auto *FS = cast<FunctionSummary>(S->getBaseObject());
212             if (FS->modulePath() == M.getModuleIdentifier()) {
213               F->setEntryCount(Function::ProfileCount(FS->entryCount(),
214                                                       Function::PCT_Synthetic));
215               break;
216             }
217           }
218         }
219       }
220     }
221     // Check the summaries to see if the symbol gets resolved to a known local
222     // definition.
223     if (VI && VI.isDSOLocal()) {
224       GV.setDSOLocal(true);
225       if (GV.hasDLLImportStorageClass())
226         GV.setDLLStorageClass(GlobalValue::DefaultStorageClass);
227     }
228   }
229 
230   // Mark read/write-only variables which can be imported with specific
231   // attribute. We can't internalize them now because IRMover will fail
232   // to link variable definitions to their external declarations during
233   // ThinLTO import. We'll internalize read-only variables later, after
234   // import is finished. See internalizeGVsAfterImport.
235   //
236   // If global value dead stripping is not enabled in summary then
237   // propagateConstants hasn't been run. We can't internalize GV
238   // in such case.
239   if (!GV.isDeclaration() && VI && ImportIndex.withAttributePropagation()) {
240     if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
241       // We can have more than one local with the same GUID, in the case of
242       // same-named locals in different but same-named source files that were
243       // compiled in their respective directories (so the source file name
244       // and resulting GUID is the same). Find the one in this module.
245       // Handle the case where there is no summary found in this module. That
246       // can happen in the distributed ThinLTO backend, because the index only
247       // contains summaries from the source modules if they are being imported.
248       // We might have a non-null VI and get here even in that case if the name
249       // matches one in this module (e.g. weak or appending linkage).
250       auto *GVS = dyn_cast_or_null<GlobalVarSummary>(
251           ImportIndex.findSummaryInModule(VI, M.getModuleIdentifier()));
252       if (GVS &&
253           (ImportIndex.isReadOnly(GVS) || ImportIndex.isWriteOnly(GVS))) {
254         V->addAttribute("thinlto-internalize");
255         // Objects referenced by writeonly GV initializer should not be
256         // promoted, because there is no any kind of read access to them
257         // on behalf of this writeonly GV. To avoid promotion we convert
258         // GV initializer to 'zeroinitializer'. This effectively drops
259         // references in IR module (not in combined index), so we can
260         // ignore them when computing import. We do not export references
261         // of writeonly object. See computeImportForReferencedGlobals
262         if (ImportIndex.isWriteOnly(GVS) && GVS->refs().size())
263           V->setInitializer(Constant::getNullValue(V->getValueType()));
264       }
265     }
266   }
267 
268   if (GV.hasLocalLinkage() && shouldPromoteLocalToGlobal(&GV)) {
269     // Save the original name string before we rename GV below.
270     auto Name = GV.getName().str();
271     GV.setName(getPromotedName(&GV));
272     GV.setLinkage(getLinkage(&GV, /* DoPromote */ true));
273     assert(!GV.hasLocalLinkage());
274     GV.setVisibility(GlobalValue::HiddenVisibility);
275 
276     // If we are renaming a COMDAT leader, ensure that we record the COMDAT
277     // for later renaming as well. This is required for COFF.
278     if (const auto *C = GV.getComdat())
279       if (C->getName() == Name)
280         RenamedComdats.try_emplace(C, M.getOrInsertComdat(GV.getName()));
281   } else
282     GV.setLinkage(getLinkage(&GV, /* DoPromote */ false));
283 
284   // Remove functions imported as available externally defs from comdats,
285   // as this is a declaration for the linker, and will be dropped eventually.
286   // It is illegal for comdats to contain declarations.
287   auto *GO = dyn_cast<GlobalObject>(&GV);
288   if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
289     // The IRMover should not have placed any imported declarations in
290     // a comdat, so the only declaration that should be in a comdat
291     // at this point would be a definition imported as available_externally.
292     assert(GO->hasAvailableExternallyLinkage() &&
293            "Expected comdat on definition (possibly available external)");
294     GO->setComdat(nullptr);
295   }
296 }
297 
298 void FunctionImportGlobalProcessing::processGlobalsForThinLTO() {
299   for (GlobalVariable &GV : M.globals())
300     processGlobalForThinLTO(GV);
301   for (Function &SF : M)
302     processGlobalForThinLTO(SF);
303   for (GlobalAlias &GA : M.aliases())
304     processGlobalForThinLTO(GA);
305 
306   // Replace any COMDATS that required renaming (because the COMDAT leader was
307   // promoted and renamed).
308   if (!RenamedComdats.empty())
309     for (auto &GO : M.global_objects())
310       if (auto *C = GO.getComdat()) {
311         auto Replacement = RenamedComdats.find(C);
312         if (Replacement != RenamedComdats.end())
313           GO.setComdat(Replacement->second);
314       }
315 }
316 
317 bool FunctionImportGlobalProcessing::run() {
318   processGlobalsForThinLTO();
319   return false;
320 }
321 
322 bool llvm::renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index,
323                                   SetVector<GlobalValue *> *GlobalsToImport) {
324   FunctionImportGlobalProcessing ThinLTOProcessing(M, Index, GlobalsToImport);
325   return ThinLTOProcessing.run();
326 }
327