FunctionImportUtils.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. #include "llvm/Transforms/Utils/FunctionImportUtils.h"
  14. #include "llvm/IR/InstIterator.h"
  15. using namespace llvm;
  16. /// Checks if we should import SGV as a definition, otherwise import as a
  17. /// declaration.
  18. bool FunctionImportGlobalProcessing::doImportAsDefinition(
  19. const GlobalValue *SGV, SetVector<GlobalValue *> *GlobalsToImport) {
  20. // Only import the globals requested for importing.
  21. if (!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)))
  22. return false;
  23. assert(!isa<GlobalAlias>(SGV) &&
  24. "Unexpected global alias in the import list.");
  25. // Otherwise yes.
  26. return true;
  27. }
  28. bool FunctionImportGlobalProcessing::doImportAsDefinition(
  29. const GlobalValue *SGV) {
  30. if (!isPerformingImport())
  31. return false;
  32. return FunctionImportGlobalProcessing::doImportAsDefinition(SGV,
  33. GlobalsToImport);
  34. }
  35. bool FunctionImportGlobalProcessing::shouldPromoteLocalToGlobal(
  36. const GlobalValue *SGV) {
  37. assert(SGV->hasLocalLinkage());
  38. // Both the imported references and the original local variable must
  39. // be promoted.
  40. if (!isPerformingImport() && !isModuleExporting())
  41. return false;
  42. if (isPerformingImport()) {
  43. assert((!GlobalsToImport->count(const_cast<GlobalValue *>(SGV)) ||
  44. !isNonRenamableLocal(*SGV)) &&
  45. "Attempting to promote non-renamable local");
  46. // We don't know for sure yet if we are importing this value (as either
  47. // a reference or a def), since we are simply walking all values in the
  48. // module. But by necessity if we end up importing it and it is local,
  49. // it must be promoted, so unconditionally promote all values in the
  50. // importing module.
  51. return true;
  52. }
  53. // When exporting, consult the index. We can have more than one local
  54. // with the same GUID, in the case of same-named locals in different but
  55. // same-named source files that were compiled in their respective directories
  56. // (so the source file name and resulting GUID is the same). Find the one
  57. // in this module.
  58. auto Summary = ImportIndex.findSummaryInModule(
  59. SGV->getGUID(), SGV->getParent()->getModuleIdentifier());
  60. assert(Summary && "Missing summary for global value when exporting");
  61. auto Linkage = Summary->linkage();
  62. if (!GlobalValue::isLocalLinkage(Linkage)) {
  63. assert(!isNonRenamableLocal(*SGV) &&
  64. "Attempting to promote non-renamable local");
  65. return true;
  66. }
  67. return false;
  68. }
  69. #ifndef NDEBUG
  70. bool FunctionImportGlobalProcessing::isNonRenamableLocal(
  71. const GlobalValue &GV) const {
  72. if (!GV.hasLocalLinkage())
  73. return false;
  74. // This needs to stay in sync with the logic in buildModuleSummaryIndex.
  75. if (GV.hasSection())
  76. return true;
  77. if (Used.count(const_cast<GlobalValue *>(&GV)))
  78. return true;
  79. return false;
  80. }
  81. #endif
  82. std::string FunctionImportGlobalProcessing::getName(const GlobalValue *SGV,
  83. bool DoPromote) {
  84. // For locals that must be promoted to global scope, ensure that
  85. // the promoted name uniquely identifies the copy in the original module,
  86. // using the ID assigned during combined index creation. When importing,
  87. // we rename all locals (not just those that are promoted) in order to
  88. // avoid naming conflicts between locals imported from different modules.
  89. if (SGV->hasLocalLinkage() && (DoPromote || isPerformingImport()))
  90. return ModuleSummaryIndex::getGlobalNameForLocal(
  91. SGV->getName(),
  92. ImportIndex.getModuleHash(SGV->getParent()->getModuleIdentifier()));
  93. return SGV->getName();
  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. // Otherwise, if we aren't importing, no linkage change is needed.
  108. if (!isPerformingImport())
  109. return SGV->getLinkage();
  110. switch (SGV->getLinkage()) {
  111. case GlobalValue::LinkOnceODRLinkage:
  112. case GlobalValue::ExternalLinkage:
  113. // External and linkonce definitions are converted to available_externally
  114. // definitions upon import, so that they are available for inlining
  115. // and/or optimization, but are turned into declarations later
  116. // during the EliminateAvailableExternally pass.
  117. if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
  118. return GlobalValue::AvailableExternallyLinkage;
  119. // An imported external declaration stays external.
  120. return SGV->getLinkage();
  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. case GlobalValue::LinkOnceAnyLinkage:
  129. case GlobalValue::WeakAnyLinkage:
  130. // Can't import linkonce_any/weak_any definitions correctly, or we might
  131. // change the program semantics, since the linker will pick the first
  132. // linkonce_any/weak_any definition and importing would change the order
  133. // they are seen by the linker. The module linking caller needs to enforce
  134. // this.
  135. assert(!doImportAsDefinition(SGV));
  136. // If imported as a declaration, it becomes external_weak.
  137. return SGV->getLinkage();
  138. case GlobalValue::WeakODRLinkage:
  139. // For weak_odr linkage, there is a guarantee that all copies will be
  140. // equivalent, so the issue described above for weak_any does not exist,
  141. // and the definition can be imported. It can be treated similarly
  142. // to an imported externally visible global value.
  143. if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
  144. return GlobalValue::AvailableExternallyLinkage;
  145. else
  146. return GlobalValue::ExternalLinkage;
  147. case GlobalValue::AppendingLinkage:
  148. // It would be incorrect to import an appending linkage variable,
  149. // since it would cause global constructors/destructors to be
  150. // executed multiple times. This should have already been handled
  151. // by linkIfNeeded, and we will assert in shouldLinkFromSource
  152. // if we try to import, so we simply return AppendingLinkage.
  153. return GlobalValue::AppendingLinkage;
  154. case GlobalValue::InternalLinkage:
  155. case GlobalValue::PrivateLinkage:
  156. // If we are promoting the local to global scope, it is handled
  157. // similarly to a normal externally visible global.
  158. if (DoPromote) {
  159. if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
  160. return GlobalValue::AvailableExternallyLinkage;
  161. else
  162. return GlobalValue::ExternalLinkage;
  163. }
  164. // A non-promoted imported local definition stays local.
  165. // The ThinLTO pass will eventually force-import their definitions.
  166. return SGV->getLinkage();
  167. case GlobalValue::ExternalWeakLinkage:
  168. // External weak doesn't apply to definitions, must be a declaration.
  169. assert(!doImportAsDefinition(SGV));
  170. // Linkage stays external_weak.
  171. return SGV->getLinkage();
  172. case GlobalValue::CommonLinkage:
  173. // Linkage stays common on definitions.
  174. // The ThinLTO pass will eventually force-import their definitions.
  175. return SGV->getLinkage();
  176. }
  177. llvm_unreachable("unknown linkage type");
  178. }
  179. void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) {
  180. ValueInfo VI;
  181. if (GV.hasName()) {
  182. VI = ImportIndex.getValueInfo(GV.getGUID());
  183. // Set synthetic function entry counts.
  184. if (VI && ImportIndex.hasSyntheticEntryCounts()) {
  185. if (Function *F = dyn_cast<Function>(&GV)) {
  186. if (!F->isDeclaration()) {
  187. for (auto &S : VI.getSummaryList()) {
  188. FunctionSummary *FS = dyn_cast<FunctionSummary>(S->getBaseObject());
  189. if (FS->modulePath() == M.getModuleIdentifier()) {
  190. F->setEntryCount(Function::ProfileCount(FS->entryCount(),
  191. Function::PCT_Synthetic));
  192. break;
  193. }
  194. }
  195. }
  196. }
  197. }
  198. // Check the summaries to see if the symbol gets resolved to a known local
  199. // definition.
  200. if (VI && VI.isDSOLocal()) {
  201. GV.setDSOLocal(true);
  202. if (GV.hasDLLImportStorageClass())
  203. GV.setDLLStorageClass(GlobalValue::DefaultStorageClass);
  204. }
  205. }
  206. // Mark read-only variables which can be imported with specific attribute.
  207. // We can't internalize them now because IRMover will fail to link variable
  208. // definitions to their external declarations during ThinLTO import. We'll
  209. // internalize read-only variables later, after import is finished.
  210. // See internalizeImmutableGVs.
  211. //
  212. // If global value dead stripping is not enabled in summary then
  213. // propagateConstants hasn't been run. We can't internalize GV
  214. // in such case.
  215. if (!GV.isDeclaration() && VI && ImportIndex.withGlobalValueDeadStripping()) {
  216. const auto &SL = VI.getSummaryList();
  217. auto *GVS = SL.empty() ? nullptr : dyn_cast<GlobalVarSummary>(SL[0].get());
  218. if (GVS && GVS->isReadOnly())
  219. cast<GlobalVariable>(&GV)->addAttribute("thinlto-internalize");
  220. }
  221. bool DoPromote = false;
  222. if (GV.hasLocalLinkage() &&
  223. ((DoPromote = shouldPromoteLocalToGlobal(&GV)) || isPerformingImport())) {
  224. // Save the original name string before we rename GV below.
  225. auto Name = GV.getName().str();
  226. // Once we change the name or linkage it is difficult to determine
  227. // again whether we should promote since shouldPromoteLocalToGlobal needs
  228. // to locate the summary (based on GUID from name and linkage). Therefore,
  229. // use DoPromote result saved above.
  230. GV.setName(getName(&GV, DoPromote));
  231. GV.setLinkage(getLinkage(&GV, DoPromote));
  232. if (!GV.hasLocalLinkage())
  233. GV.setVisibility(GlobalValue::HiddenVisibility);
  234. // If we are renaming a COMDAT leader, ensure that we record the COMDAT
  235. // for later renaming as well. This is required for COFF.
  236. if (const auto *C = GV.getComdat())
  237. if (C->getName() == Name)
  238. RenamedComdats.try_emplace(C, M.getOrInsertComdat(GV.getName()));
  239. } else
  240. GV.setLinkage(getLinkage(&GV, /* DoPromote */ false));
  241. // Remove functions imported as available externally defs from comdats,
  242. // as this is a declaration for the linker, and will be dropped eventually.
  243. // It is illegal for comdats to contain declarations.
  244. auto *GO = dyn_cast<GlobalObject>(&GV);
  245. if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
  246. // The IRMover should not have placed any imported declarations in
  247. // a comdat, so the only declaration that should be in a comdat
  248. // at this point would be a definition imported as available_externally.
  249. assert(GO->hasAvailableExternallyLinkage() &&
  250. "Expected comdat on definition (possibly available external)");
  251. GO->setComdat(nullptr);
  252. }
  253. }
  254. void FunctionImportGlobalProcessing::processGlobalsForThinLTO() {
  255. for (GlobalVariable &GV : M.globals())
  256. processGlobalForThinLTO(GV);
  257. for (Function &SF : M)
  258. processGlobalForThinLTO(SF);
  259. for (GlobalAlias &GA : M.aliases())
  260. processGlobalForThinLTO(GA);
  261. // Replace any COMDATS that required renaming (because the COMDAT leader was
  262. // promoted and renamed).
  263. if (!RenamedComdats.empty())
  264. for (auto &GO : M.global_objects())
  265. if (auto *C = GO.getComdat()) {
  266. auto Replacement = RenamedComdats.find(C);
  267. if (Replacement != RenamedComdats.end())
  268. GO.setComdat(Replacement->second);
  269. }
  270. }
  271. bool FunctionImportGlobalProcessing::run() {
  272. processGlobalsForThinLTO();
  273. return false;
  274. }
  275. bool llvm::renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index,
  276. SetVector<GlobalValue *> *GlobalsToImport) {
  277. FunctionImportGlobalProcessing ThinLTOProcessing(M, Index, GlobalsToImport);
  278. return ThinLTOProcessing.run();
  279. }