FunctionImport.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464
  1. //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
  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 Function import based on summaries.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Transforms/IPO/FunctionImport.h"
  13. #include "llvm/ADT/ArrayRef.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SetVector.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/ADT/StringMap.h"
  19. #include "llvm/ADT/StringRef.h"
  20. #include "llvm/Bitcode/BitcodeReader.h"
  21. #include "llvm/IR/AutoUpgrade.h"
  22. #include "llvm/IR/Constants.h"
  23. #include "llvm/IR/Function.h"
  24. #include "llvm/IR/GlobalAlias.h"
  25. #include "llvm/IR/GlobalObject.h"
  26. #include "llvm/IR/GlobalValue.h"
  27. #include "llvm/IR/GlobalVariable.h"
  28. #include "llvm/IR/Metadata.h"
  29. #include "llvm/IR/Module.h"
  30. #include "llvm/IR/ModuleSummaryIndex.h"
  31. #include "llvm/IRReader/IRReader.h"
  32. #include "llvm/InitializePasses.h"
  33. #include "llvm/Linker/IRMover.h"
  34. #include "llvm/Pass.h"
  35. #include "llvm/Support/Casting.h"
  36. #include "llvm/Support/CommandLine.h"
  37. #include "llvm/Support/Debug.h"
  38. #include "llvm/Support/Errc.h"
  39. #include "llvm/Support/Error.h"
  40. #include "llvm/Support/ErrorHandling.h"
  41. #include "llvm/Support/FileSystem.h"
  42. #include "llvm/Support/SourceMgr.h"
  43. #include "llvm/Support/raw_ostream.h"
  44. #include "llvm/Transforms/IPO/Internalize.h"
  45. #include "llvm/Transforms/Utils/Cloning.h"
  46. #include "llvm/Transforms/Utils/FunctionImportUtils.h"
  47. #include "llvm/Transforms/Utils/ValueMapper.h"
  48. #include <cassert>
  49. #include <memory>
  50. #include <set>
  51. #include <string>
  52. #include <system_error>
  53. #include <tuple>
  54. #include <utility>
  55. using namespace llvm;
  56. #define DEBUG_TYPE "function-import"
  57. STATISTIC(NumImportedFunctionsThinLink,
  58. "Number of functions thin link decided to import");
  59. STATISTIC(NumImportedHotFunctionsThinLink,
  60. "Number of hot functions thin link decided to import");
  61. STATISTIC(NumImportedCriticalFunctionsThinLink,
  62. "Number of critical functions thin link decided to import");
  63. STATISTIC(NumImportedGlobalVarsThinLink,
  64. "Number of global variables thin link decided to import");
  65. STATISTIC(NumImportedFunctions, "Number of functions imported in backend");
  66. STATISTIC(NumImportedGlobalVars,
  67. "Number of global variables imported in backend");
  68. STATISTIC(NumImportedModules, "Number of modules imported from");
  69. STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
  70. STATISTIC(NumLiveSymbols, "Number of live symbols in index");
  71. /// Limit on instruction count of imported functions.
  72. static cl::opt<unsigned> ImportInstrLimit(
  73. "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
  74. cl::desc("Only import functions with less than N instructions"));
  75. static cl::opt<int> ImportCutoff(
  76. "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"),
  77. cl::desc("Only import first N functions if N>=0 (default -1)"));
  78. static cl::opt<bool>
  79. ForceImportAll("force-import-all", cl::init(false), cl::Hidden,
  80. cl::desc("Import functions with noinline attribute"));
  81. static cl::opt<float>
  82. ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
  83. cl::Hidden, cl::value_desc("x"),
  84. cl::desc("As we import functions, multiply the "
  85. "`import-instr-limit` threshold by this factor "
  86. "before processing newly imported functions"));
  87. static cl::opt<float> ImportHotInstrFactor(
  88. "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
  89. cl::value_desc("x"),
  90. cl::desc("As we import functions called from hot callsite, multiply the "
  91. "`import-instr-limit` threshold by this factor "
  92. "before processing newly imported functions"));
  93. static cl::opt<float> ImportHotMultiplier(
  94. "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
  95. cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
  96. static cl::opt<float> ImportCriticalMultiplier(
  97. "import-critical-multiplier", cl::init(100.0), cl::Hidden,
  98. cl::value_desc("x"),
  99. cl::desc(
  100. "Multiply the `import-instr-limit` threshold for critical callsites"));
  101. // FIXME: This multiplier was not really tuned up.
  102. static cl::opt<float> ImportColdMultiplier(
  103. "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
  104. cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
  105. static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
  106. cl::desc("Print imported functions"));
  107. static cl::opt<bool> PrintImportFailures(
  108. "print-import-failures", cl::init(false), cl::Hidden,
  109. cl::desc("Print information for functions rejected for importing"));
  110. static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
  111. cl::desc("Compute dead symbols"));
  112. static cl::opt<bool> EnableImportMetadata(
  113. "enable-import-metadata", cl::init(false), cl::Hidden,
  114. cl::desc("Enable import metadata like 'thinlto_src_module'"));
  115. /// Summary file to use for function importing when using -function-import from
  116. /// the command line.
  117. static cl::opt<std::string>
  118. SummaryFile("summary-file",
  119. cl::desc("The summary file to use for function importing."));
  120. /// Used when testing importing from distributed indexes via opt
  121. // -function-import.
  122. static cl::opt<bool>
  123. ImportAllIndex("import-all-index",
  124. cl::desc("Import all external functions in index."));
  125. // Load lazily a module from \p FileName in \p Context.
  126. static std::unique_ptr<Module> loadFile(const std::string &FileName,
  127. LLVMContext &Context) {
  128. SMDiagnostic Err;
  129. LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n");
  130. // Metadata isn't loaded until functions are imported, to minimize
  131. // the memory overhead.
  132. std::unique_ptr<Module> Result =
  133. getLazyIRFileModule(FileName, Err, Context,
  134. /* ShouldLazyLoadMetadata = */ true);
  135. if (!Result) {
  136. Err.print("function-import", errs());
  137. report_fatal_error("Abort");
  138. }
  139. return Result;
  140. }
  141. /// Given a list of possible callee implementation for a call site, select one
  142. /// that fits the \p Threshold.
  143. ///
  144. /// FIXME: select "best" instead of first that fits. But what is "best"?
  145. /// - The smallest: more likely to be inlined.
  146. /// - The one with the least outgoing edges (already well optimized).
  147. /// - One from a module already being imported from in order to reduce the
  148. /// number of source modules parsed/linked.
  149. /// - One that has PGO data attached.
  150. /// - [insert you fancy metric here]
  151. static const GlobalValueSummary *
  152. selectCallee(const ModuleSummaryIndex &Index,
  153. ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
  154. unsigned Threshold, StringRef CallerModulePath,
  155. FunctionImporter::ImportFailureReason &Reason,
  156. GlobalValue::GUID GUID) {
  157. Reason = FunctionImporter::ImportFailureReason::None;
  158. auto It = llvm::find_if(
  159. CalleeSummaryList,
  160. [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
  161. auto *GVSummary = SummaryPtr.get();
  162. if (!Index.isGlobalValueLive(GVSummary)) {
  163. Reason = FunctionImporter::ImportFailureReason::NotLive;
  164. return false;
  165. }
  166. if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) {
  167. Reason = FunctionImporter::ImportFailureReason::InterposableLinkage;
  168. // There is no point in importing these, we can't inline them
  169. return false;
  170. }
  171. auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject());
  172. // If this is a local function, make sure we import the copy
  173. // in the caller's module. The only time a local function can
  174. // share an entry in the index is if there is a local with the same name
  175. // in another module that had the same source file name (in a different
  176. // directory), where each was compiled in their own directory so there
  177. // was not distinguishing path.
  178. // However, do the import from another module if there is only one
  179. // entry in the list - in that case this must be a reference due
  180. // to indirect call profile data, since a function pointer can point to
  181. // a local in another module.
  182. if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
  183. CalleeSummaryList.size() > 1 &&
  184. Summary->modulePath() != CallerModulePath) {
  185. Reason =
  186. FunctionImporter::ImportFailureReason::LocalLinkageNotInModule;
  187. return false;
  188. }
  189. if ((Summary->instCount() > Threshold) &&
  190. !Summary->fflags().AlwaysInline && !ForceImportAll) {
  191. Reason = FunctionImporter::ImportFailureReason::TooLarge;
  192. return false;
  193. }
  194. // Skip if it isn't legal to import (e.g. may reference unpromotable
  195. // locals).
  196. if (Summary->notEligibleToImport()) {
  197. Reason = FunctionImporter::ImportFailureReason::NotEligible;
  198. return false;
  199. }
  200. // Don't bother importing if we can't inline it anyway.
  201. if (Summary->fflags().NoInline && !ForceImportAll) {
  202. Reason = FunctionImporter::ImportFailureReason::NoInline;
  203. return false;
  204. }
  205. return true;
  206. });
  207. if (It == CalleeSummaryList.end())
  208. return nullptr;
  209. return cast<GlobalValueSummary>(It->get());
  210. }
  211. namespace {
  212. using EdgeInfo =
  213. std::tuple<const GlobalValueSummary *, unsigned /* Threshold */>;
  214. } // anonymous namespace
  215. static bool shouldImportGlobal(const ValueInfo &VI,
  216. const GVSummaryMapTy &DefinedGVSummaries) {
  217. const auto &GVS = DefinedGVSummaries.find(VI.getGUID());
  218. if (GVS == DefinedGVSummaries.end())
  219. return true;
  220. // We should not skip import if the module contains a definition with
  221. // interposable linkage type. This is required for correctness in
  222. // the situation with two following conditions:
  223. // * the def with interposable linkage is non-prevailing,
  224. // * there is a prevailing def available for import and marked read-only.
  225. // In this case, the non-prevailing def will be converted to a declaration,
  226. // while the prevailing one becomes internal, thus no definitions will be
  227. // available for linking. In order to prevent undefined symbol link error,
  228. // the prevailing definition must be imported.
  229. // FIXME: Consider adding a check that the suitable prevailing definition
  230. // exists and marked read-only.
  231. if (VI.getSummaryList().size() > 1 &&
  232. GlobalValue::isInterposableLinkage(GVS->second->linkage()))
  233. return true;
  234. return false;
  235. }
  236. static void computeImportForReferencedGlobals(
  237. const GlobalValueSummary &Summary, const ModuleSummaryIndex &Index,
  238. const GVSummaryMapTy &DefinedGVSummaries,
  239. SmallVectorImpl<EdgeInfo> &Worklist,
  240. FunctionImporter::ImportMapTy &ImportList,
  241. StringMap<FunctionImporter::ExportSetTy> *ExportLists) {
  242. for (const auto &VI : Summary.refs()) {
  243. if (!shouldImportGlobal(VI, DefinedGVSummaries)) {
  244. LLVM_DEBUG(
  245. dbgs() << "Ref ignored! Target already in destination module.\n");
  246. continue;
  247. }
  248. LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n");
  249. // If this is a local variable, make sure we import the copy
  250. // in the caller's module. The only time a local variable can
  251. // share an entry in the index is if there is a local with the same name
  252. // in another module that had the same source file name (in a different
  253. // directory), where each was compiled in their own directory so there
  254. // was not distinguishing path.
  255. auto LocalNotInModule = [&](const GlobalValueSummary *RefSummary) -> bool {
  256. return GlobalValue::isLocalLinkage(RefSummary->linkage()) &&
  257. RefSummary->modulePath() != Summary.modulePath();
  258. };
  259. for (const auto &RefSummary : VI.getSummaryList())
  260. if (isa<GlobalVarSummary>(RefSummary.get()) &&
  261. Index.canImportGlobalVar(RefSummary.get(), /* AnalyzeRefs */ true) &&
  262. !LocalNotInModule(RefSummary.get())) {
  263. auto ILI = ImportList[RefSummary->modulePath()].insert(VI.getGUID());
  264. // Only update stat and exports if we haven't already imported this
  265. // variable.
  266. if (!ILI.second)
  267. break;
  268. NumImportedGlobalVarsThinLink++;
  269. // Any references made by this variable will be marked exported later,
  270. // in ComputeCrossModuleImport, after import decisions are complete,
  271. // which is more efficient than adding them here.
  272. if (ExportLists)
  273. (*ExportLists)[RefSummary->modulePath()].insert(VI);
  274. // If variable is not writeonly we attempt to recursively analyze
  275. // its references in order to import referenced constants.
  276. if (!Index.isWriteOnly(cast<GlobalVarSummary>(RefSummary.get())))
  277. Worklist.emplace_back(RefSummary.get(), 0);
  278. break;
  279. }
  280. }
  281. }
  282. static const char *
  283. getFailureName(FunctionImporter::ImportFailureReason Reason) {
  284. switch (Reason) {
  285. case FunctionImporter::ImportFailureReason::None:
  286. return "None";
  287. case FunctionImporter::ImportFailureReason::GlobalVar:
  288. return "GlobalVar";
  289. case FunctionImporter::ImportFailureReason::NotLive:
  290. return "NotLive";
  291. case FunctionImporter::ImportFailureReason::TooLarge:
  292. return "TooLarge";
  293. case FunctionImporter::ImportFailureReason::InterposableLinkage:
  294. return "InterposableLinkage";
  295. case FunctionImporter::ImportFailureReason::LocalLinkageNotInModule:
  296. return "LocalLinkageNotInModule";
  297. case FunctionImporter::ImportFailureReason::NotEligible:
  298. return "NotEligible";
  299. case FunctionImporter::ImportFailureReason::NoInline:
  300. return "NoInline";
  301. }
  302. llvm_unreachable("invalid reason");
  303. }
  304. /// Compute the list of functions to import for a given caller. Mark these
  305. /// imported functions and the symbols they reference in their source module as
  306. /// exported from their source module.
  307. static void computeImportForFunction(
  308. const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
  309. const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
  310. SmallVectorImpl<EdgeInfo> &Worklist,
  311. FunctionImporter::ImportMapTy &ImportList,
  312. StringMap<FunctionImporter::ExportSetTy> *ExportLists,
  313. FunctionImporter::ImportThresholdsTy &ImportThresholds) {
  314. computeImportForReferencedGlobals(Summary, Index, DefinedGVSummaries,
  315. Worklist, ImportList, ExportLists);
  316. static int ImportCount = 0;
  317. for (const auto &Edge : Summary.calls()) {
  318. ValueInfo VI = Edge.first;
  319. LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
  320. << "\n");
  321. if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
  322. LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
  323. << " reached.\n");
  324. continue;
  325. }
  326. if (DefinedGVSummaries.count(VI.getGUID())) {
  327. // FIXME: Consider not skipping import if the module contains
  328. // a non-prevailing def with interposable linkage. The prevailing copy
  329. // can safely be imported (see shouldImportGlobal()).
  330. LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
  331. continue;
  332. }
  333. auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
  334. if (Hotness == CalleeInfo::HotnessType::Hot)
  335. return ImportHotMultiplier;
  336. if (Hotness == CalleeInfo::HotnessType::Cold)
  337. return ImportColdMultiplier;
  338. if (Hotness == CalleeInfo::HotnessType::Critical)
  339. return ImportCriticalMultiplier;
  340. return 1.0;
  341. };
  342. const auto NewThreshold =
  343. Threshold * GetBonusMultiplier(Edge.second.getHotness());
  344. auto IT = ImportThresholds.insert(std::make_pair(
  345. VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr)));
  346. bool PreviouslyVisited = !IT.second;
  347. auto &ProcessedThreshold = std::get<0>(IT.first->second);
  348. auto &CalleeSummary = std::get<1>(IT.first->second);
  349. auto &FailureInfo = std::get<2>(IT.first->second);
  350. bool IsHotCallsite =
  351. Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
  352. bool IsCriticalCallsite =
  353. Edge.second.getHotness() == CalleeInfo::HotnessType::Critical;
  354. const FunctionSummary *ResolvedCalleeSummary = nullptr;
  355. if (CalleeSummary) {
  356. assert(PreviouslyVisited);
  357. // Since the traversal of the call graph is DFS, we can revisit a function
  358. // a second time with a higher threshold. In this case, it is added back
  359. // to the worklist with the new threshold (so that its own callee chains
  360. // can be considered with the higher threshold).
  361. if (NewThreshold <= ProcessedThreshold) {
  362. LLVM_DEBUG(
  363. dbgs() << "ignored! Target was already imported with Threshold "
  364. << ProcessedThreshold << "\n");
  365. continue;
  366. }
  367. // Update with new larger threshold.
  368. ProcessedThreshold = NewThreshold;
  369. ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
  370. } else {
  371. // If we already rejected importing a callee at the same or higher
  372. // threshold, don't waste time calling selectCallee.
  373. if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
  374. LLVM_DEBUG(
  375. dbgs() << "ignored! Target was already rejected with Threshold "
  376. << ProcessedThreshold << "\n");
  377. if (PrintImportFailures) {
  378. assert(FailureInfo &&
  379. "Expected FailureInfo for previously rejected candidate");
  380. FailureInfo->Attempts++;
  381. }
  382. continue;
  383. }
  384. FunctionImporter::ImportFailureReason Reason;
  385. CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
  386. Summary.modulePath(), Reason, VI.getGUID());
  387. if (!CalleeSummary) {
  388. // Update with new larger threshold if this was a retry (otherwise
  389. // we would have already inserted with NewThreshold above). Also
  390. // update failure info if requested.
  391. if (PreviouslyVisited) {
  392. ProcessedThreshold = NewThreshold;
  393. if (PrintImportFailures) {
  394. assert(FailureInfo &&
  395. "Expected FailureInfo for previously rejected candidate");
  396. FailureInfo->Reason = Reason;
  397. FailureInfo->Attempts++;
  398. FailureInfo->MaxHotness =
  399. std::max(FailureInfo->MaxHotness, Edge.second.getHotness());
  400. }
  401. } else if (PrintImportFailures) {
  402. assert(!FailureInfo &&
  403. "Expected no FailureInfo for newly rejected candidate");
  404. FailureInfo = std::make_unique<FunctionImporter::ImportFailureInfo>(
  405. VI, Edge.second.getHotness(), Reason, 1);
  406. }
  407. if (ForceImportAll) {
  408. std::string Msg = std::string("Failed to import function ") +
  409. VI.name().str() + " due to " +
  410. getFailureName(Reason);
  411. auto Error = make_error<StringError>(
  412. Msg, make_error_code(errc::not_supported));
  413. logAllUnhandledErrors(std::move(Error), errs(),
  414. "Error importing module: ");
  415. break;
  416. } else {
  417. LLVM_DEBUG(dbgs()
  418. << "ignored! No qualifying callee with summary found.\n");
  419. continue;
  420. }
  421. }
  422. // "Resolve" the summary
  423. CalleeSummary = CalleeSummary->getBaseObject();
  424. ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
  425. assert((ResolvedCalleeSummary->fflags().AlwaysInline || ForceImportAll ||
  426. (ResolvedCalleeSummary->instCount() <= NewThreshold)) &&
  427. "selectCallee() didn't honor the threshold");
  428. auto ExportModulePath = ResolvedCalleeSummary->modulePath();
  429. auto ILI = ImportList[ExportModulePath].insert(VI.getGUID());
  430. // We previously decided to import this GUID definition if it was already
  431. // inserted in the set of imports from the exporting module.
  432. bool PreviouslyImported = !ILI.second;
  433. if (!PreviouslyImported) {
  434. NumImportedFunctionsThinLink++;
  435. if (IsHotCallsite)
  436. NumImportedHotFunctionsThinLink++;
  437. if (IsCriticalCallsite)
  438. NumImportedCriticalFunctionsThinLink++;
  439. }
  440. // Any calls/references made by this function will be marked exported
  441. // later, in ComputeCrossModuleImport, after import decisions are
  442. // complete, which is more efficient than adding them here.
  443. if (ExportLists)
  444. (*ExportLists)[ExportModulePath].insert(VI);
  445. }
  446. auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
  447. // Adjust the threshold for next level of imported functions.
  448. // The threshold is different for hot callsites because we can then
  449. // inline chains of hot calls.
  450. if (IsHotCallsite)
  451. return Threshold * ImportHotInstrFactor;
  452. return Threshold * ImportInstrFactor;
  453. };
  454. const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
  455. ImportCount++;
  456. // Insert the newly imported function to the worklist.
  457. Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold);
  458. }
  459. }
  460. /// Given the list of globals defined in a module, compute the list of imports
  461. /// as well as the list of "exports", i.e. the list of symbols referenced from
  462. /// another module (that may require promotion).
  463. static void ComputeImportForModule(
  464. const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
  465. StringRef ModName, FunctionImporter::ImportMapTy &ImportList,
  466. StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
  467. // Worklist contains the list of function imported in this module, for which
  468. // we will analyse the callees and may import further down the callgraph.
  469. SmallVector<EdgeInfo, 128> Worklist;
  470. FunctionImporter::ImportThresholdsTy ImportThresholds;
  471. // Populate the worklist with the import for the functions in the current
  472. // module
  473. for (const auto &GVSummary : DefinedGVSummaries) {
  474. #ifndef NDEBUG
  475. // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID
  476. // so this map look up (and possibly others) can be avoided.
  477. auto VI = Index.getValueInfo(GVSummary.first);
  478. #endif
  479. if (!Index.isGlobalValueLive(GVSummary.second)) {
  480. LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
  481. continue;
  482. }
  483. auto *FuncSummary =
  484. dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
  485. if (!FuncSummary)
  486. // Skip import for global variables
  487. continue;
  488. LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
  489. computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
  490. DefinedGVSummaries, Worklist, ImportList,
  491. ExportLists, ImportThresholds);
  492. }
  493. // Process the newly imported functions and add callees to the worklist.
  494. while (!Worklist.empty()) {
  495. auto GVInfo = Worklist.pop_back_val();
  496. auto *Summary = std::get<0>(GVInfo);
  497. auto Threshold = std::get<1>(GVInfo);
  498. if (auto *FS = dyn_cast<FunctionSummary>(Summary))
  499. computeImportForFunction(*FS, Index, Threshold, DefinedGVSummaries,
  500. Worklist, ImportList, ExportLists,
  501. ImportThresholds);
  502. else
  503. computeImportForReferencedGlobals(*Summary, Index, DefinedGVSummaries,
  504. Worklist, ImportList, ExportLists);
  505. }
  506. // Print stats about functions considered but rejected for importing
  507. // when requested.
  508. if (PrintImportFailures) {
  509. dbgs() << "Missed imports into module " << ModName << "\n";
  510. for (auto &I : ImportThresholds) {
  511. auto &ProcessedThreshold = std::get<0>(I.second);
  512. auto &CalleeSummary = std::get<1>(I.second);
  513. auto &FailureInfo = std::get<2>(I.second);
  514. if (CalleeSummary)
  515. continue; // We are going to import.
  516. assert(FailureInfo);
  517. FunctionSummary *FS = nullptr;
  518. if (!FailureInfo->VI.getSummaryList().empty())
  519. FS = dyn_cast<FunctionSummary>(
  520. FailureInfo->VI.getSummaryList()[0]->getBaseObject());
  521. dbgs() << FailureInfo->VI
  522. << ": Reason = " << getFailureName(FailureInfo->Reason)
  523. << ", Threshold = " << ProcessedThreshold
  524. << ", Size = " << (FS ? (int)FS->instCount() : -1)
  525. << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness)
  526. << ", Attempts = " << FailureInfo->Attempts << "\n";
  527. }
  528. }
  529. }
  530. #ifndef NDEBUG
  531. static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, ValueInfo VI) {
  532. auto SL = VI.getSummaryList();
  533. return SL.empty()
  534. ? false
  535. : SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
  536. }
  537. static bool isGlobalVarSummary(const ModuleSummaryIndex &Index,
  538. GlobalValue::GUID G) {
  539. if (const auto &VI = Index.getValueInfo(G))
  540. return isGlobalVarSummary(Index, VI);
  541. return false;
  542. }
  543. template <class T>
  544. static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index,
  545. T &Cont) {
  546. unsigned NumGVS = 0;
  547. for (auto &V : Cont)
  548. if (isGlobalVarSummary(Index, V))
  549. ++NumGVS;
  550. return NumGVS;
  551. }
  552. #endif
  553. #ifndef NDEBUG
  554. static bool
  555. checkVariableImport(const ModuleSummaryIndex &Index,
  556. StringMap<FunctionImporter::ImportMapTy> &ImportLists,
  557. StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
  558. DenseSet<GlobalValue::GUID> FlattenedImports;
  559. for (auto &ImportPerModule : ImportLists)
  560. for (auto &ExportPerModule : ImportPerModule.second)
  561. FlattenedImports.insert(ExportPerModule.second.begin(),
  562. ExportPerModule.second.end());
  563. // Checks that all GUIDs of read/writeonly vars we see in export lists
  564. // are also in the import lists. Otherwise we my face linker undefs,
  565. // because readonly and writeonly vars are internalized in their
  566. // source modules.
  567. auto IsReadOrWriteOnlyVar = [&](StringRef ModulePath, const ValueInfo &VI) {
  568. auto *GVS = dyn_cast_or_null<GlobalVarSummary>(
  569. Index.findSummaryInModule(VI, ModulePath));
  570. return GVS && (Index.isReadOnly(GVS) || Index.isWriteOnly(GVS));
  571. };
  572. for (auto &ExportPerModule : ExportLists)
  573. for (auto &VI : ExportPerModule.second)
  574. if (!FlattenedImports.count(VI.getGUID()) &&
  575. IsReadOrWriteOnlyVar(ExportPerModule.first(), VI))
  576. return false;
  577. return true;
  578. }
  579. #endif
  580. /// Compute all the import and export for every module using the Index.
  581. void llvm::ComputeCrossModuleImport(
  582. const ModuleSummaryIndex &Index,
  583. const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
  584. StringMap<FunctionImporter::ImportMapTy> &ImportLists,
  585. StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
  586. // For each module that has function defined, compute the import/export lists.
  587. for (const auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
  588. auto &ImportList = ImportLists[DefinedGVSummaries.first()];
  589. LLVM_DEBUG(dbgs() << "Computing import for Module '"
  590. << DefinedGVSummaries.first() << "'\n");
  591. ComputeImportForModule(DefinedGVSummaries.second, Index,
  592. DefinedGVSummaries.first(), ImportList,
  593. &ExportLists);
  594. }
  595. // When computing imports we only added the variables and functions being
  596. // imported to the export list. We also need to mark any references and calls
  597. // they make as exported as well. We do this here, as it is more efficient
  598. // since we may import the same values multiple times into different modules
  599. // during the import computation.
  600. for (auto &ELI : ExportLists) {
  601. FunctionImporter::ExportSetTy NewExports;
  602. const auto &DefinedGVSummaries =
  603. ModuleToDefinedGVSummaries.lookup(ELI.first());
  604. for (auto &EI : ELI.second) {
  605. // Find the copy defined in the exporting module so that we can mark the
  606. // values it references in that specific definition as exported.
  607. // Below we will add all references and called values, without regard to
  608. // whether they are also defined in this module. We subsequently prune the
  609. // list to only include those defined in the exporting module, see comment
  610. // there as to why.
  611. auto DS = DefinedGVSummaries.find(EI.getGUID());
  612. // Anything marked exported during the import computation must have been
  613. // defined in the exporting module.
  614. assert(DS != DefinedGVSummaries.end());
  615. auto *S = DS->getSecond();
  616. S = S->getBaseObject();
  617. if (auto *GVS = dyn_cast<GlobalVarSummary>(S)) {
  618. // Export referenced functions and variables. We don't export/promote
  619. // objects referenced by writeonly variable initializer, because
  620. // we convert such variables initializers to "zeroinitializer".
  621. // See processGlobalForThinLTO.
  622. if (!Index.isWriteOnly(GVS))
  623. for (const auto &VI : GVS->refs())
  624. NewExports.insert(VI);
  625. } else {
  626. auto *FS = cast<FunctionSummary>(S);
  627. for (const auto &Edge : FS->calls())
  628. NewExports.insert(Edge.first);
  629. for (const auto &Ref : FS->refs())
  630. NewExports.insert(Ref);
  631. }
  632. }
  633. // Prune list computed above to only include values defined in the exporting
  634. // module. We do this after the above insertion since we may hit the same
  635. // ref/call target multiple times in above loop, and it is more efficient to
  636. // avoid a set lookup each time.
  637. for (auto EI = NewExports.begin(); EI != NewExports.end();) {
  638. if (!DefinedGVSummaries.count(EI->getGUID()))
  639. NewExports.erase(EI++);
  640. else
  641. ++EI;
  642. }
  643. ELI.second.insert(NewExports.begin(), NewExports.end());
  644. }
  645. assert(checkVariableImport(Index, ImportLists, ExportLists));
  646. #ifndef NDEBUG
  647. LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
  648. << " modules:\n");
  649. for (auto &ModuleImports : ImportLists) {
  650. auto ModName = ModuleImports.first();
  651. auto &Exports = ExportLists[ModName];
  652. unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
  653. LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
  654. << Exports.size() - NumGVS << " functions and " << NumGVS
  655. << " vars. Imports from " << ModuleImports.second.size()
  656. << " modules.\n");
  657. for (auto &Src : ModuleImports.second) {
  658. auto SrcModName = Src.first();
  659. unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
  660. LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
  661. << " functions imported from " << SrcModName << "\n");
  662. LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod
  663. << " global vars imported from " << SrcModName << "\n");
  664. }
  665. }
  666. #endif
  667. }
  668. #ifndef NDEBUG
  669. static void dumpImportListForModule(const ModuleSummaryIndex &Index,
  670. StringRef ModulePath,
  671. FunctionImporter::ImportMapTy &ImportList) {
  672. LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
  673. << ImportList.size() << " modules.\n");
  674. for (auto &Src : ImportList) {
  675. auto SrcModName = Src.first();
  676. unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
  677. LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
  678. << " functions imported from " << SrcModName << "\n");
  679. LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from "
  680. << SrcModName << "\n");
  681. }
  682. }
  683. #endif
  684. /// Compute all the imports for the given module in the Index.
  685. void llvm::ComputeCrossModuleImportForModule(
  686. StringRef ModulePath, const ModuleSummaryIndex &Index,
  687. FunctionImporter::ImportMapTy &ImportList) {
  688. // Collect the list of functions this module defines.
  689. // GUID -> Summary
  690. GVSummaryMapTy FunctionSummaryMap;
  691. Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
  692. // Compute the import list for this module.
  693. LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
  694. ComputeImportForModule(FunctionSummaryMap, Index, ModulePath, ImportList);
  695. #ifndef NDEBUG
  696. dumpImportListForModule(Index, ModulePath, ImportList);
  697. #endif
  698. }
  699. // Mark all external summaries in Index for import into the given module.
  700. // Used for distributed builds using a distributed index.
  701. void llvm::ComputeCrossModuleImportForModuleFromIndex(
  702. StringRef ModulePath, const ModuleSummaryIndex &Index,
  703. FunctionImporter::ImportMapTy &ImportList) {
  704. for (const auto &GlobalList : Index) {
  705. // Ignore entries for undefined references.
  706. if (GlobalList.second.SummaryList.empty())
  707. continue;
  708. auto GUID = GlobalList.first;
  709. assert(GlobalList.second.SummaryList.size() == 1 &&
  710. "Expected individual combined index to have one summary per GUID");
  711. auto &Summary = GlobalList.second.SummaryList[0];
  712. // Skip the summaries for the importing module. These are included to
  713. // e.g. record required linkage changes.
  714. if (Summary->modulePath() == ModulePath)
  715. continue;
  716. // Add an entry to provoke importing by thinBackend.
  717. ImportList[Summary->modulePath()].insert(GUID);
  718. }
  719. #ifndef NDEBUG
  720. dumpImportListForModule(Index, ModulePath, ImportList);
  721. #endif
  722. }
  723. // For SamplePGO, the indirect call targets for local functions will
  724. // have its original name annotated in profile. We try to find the
  725. // corresponding PGOFuncName as the GUID, and fix up the edges
  726. // accordingly.
  727. void updateValueInfoForIndirectCalls(ModuleSummaryIndex &Index,
  728. FunctionSummary *FS) {
  729. for (auto &EI : FS->mutableCalls()) {
  730. if (!EI.first.getSummaryList().empty())
  731. continue;
  732. auto GUID = Index.getGUIDFromOriginalID(EI.first.getGUID());
  733. if (GUID == 0)
  734. continue;
  735. // Update the edge to point directly to the correct GUID.
  736. auto VI = Index.getValueInfo(GUID);
  737. if (llvm::any_of(
  738. VI.getSummaryList(),
  739. [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
  740. // The mapping from OriginalId to GUID may return a GUID
  741. // that corresponds to a static variable. Filter it out here.
  742. // This can happen when
  743. // 1) There is a call to a library function which is not defined
  744. // in the index.
  745. // 2) There is a static variable with the OriginalGUID identical
  746. // to the GUID of the library function in 1);
  747. // When this happens the static variable in 2) will be found,
  748. // which needs to be filtered out.
  749. return SummaryPtr->getSummaryKind() ==
  750. GlobalValueSummary::GlobalVarKind;
  751. }))
  752. continue;
  753. EI.first = VI;
  754. }
  755. }
  756. void llvm::updateIndirectCalls(ModuleSummaryIndex &Index) {
  757. for (const auto &Entry : Index) {
  758. for (const auto &S : Entry.second.SummaryList) {
  759. if (auto *FS = dyn_cast<FunctionSummary>(S.get()))
  760. updateValueInfoForIndirectCalls(Index, FS);
  761. }
  762. }
  763. }
  764. void llvm::computeDeadSymbolsAndUpdateIndirectCalls(
  765. ModuleSummaryIndex &Index,
  766. const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
  767. function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
  768. assert(!Index.withGlobalValueDeadStripping());
  769. if (!ComputeDead ||
  770. // Don't do anything when nothing is live, this is friendly with tests.
  771. GUIDPreservedSymbols.empty()) {
  772. // Still need to update indirect calls.
  773. updateIndirectCalls(Index);
  774. return;
  775. }
  776. unsigned LiveSymbols = 0;
  777. SmallVector<ValueInfo, 128> Worklist;
  778. Worklist.reserve(GUIDPreservedSymbols.size() * 2);
  779. for (auto GUID : GUIDPreservedSymbols) {
  780. ValueInfo VI = Index.getValueInfo(GUID);
  781. if (!VI)
  782. continue;
  783. for (const auto &S : VI.getSummaryList())
  784. S->setLive(true);
  785. }
  786. // Add values flagged in the index as live roots to the worklist.
  787. for (const auto &Entry : Index) {
  788. auto VI = Index.getValueInfo(Entry);
  789. for (const auto &S : Entry.second.SummaryList) {
  790. if (auto *FS = dyn_cast<FunctionSummary>(S.get()))
  791. updateValueInfoForIndirectCalls(Index, FS);
  792. if (S->isLive()) {
  793. LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
  794. Worklist.push_back(VI);
  795. ++LiveSymbols;
  796. break;
  797. }
  798. }
  799. }
  800. // Make value live and add it to the worklist if it was not live before.
  801. auto visit = [&](ValueInfo VI, bool IsAliasee) {
  802. // FIXME: If we knew which edges were created for indirect call profiles,
  803. // we could skip them here. Any that are live should be reached via
  804. // other edges, e.g. reference edges. Otherwise, using a profile collected
  805. // on a slightly different binary might provoke preserving, importing
  806. // and ultimately promoting calls to functions not linked into this
  807. // binary, which increases the binary size unnecessarily. Note that
  808. // if this code changes, the importer needs to change so that edges
  809. // to functions marked dead are skipped.
  810. if (llvm::any_of(VI.getSummaryList(),
  811. [](const std::unique_ptr<llvm::GlobalValueSummary> &S) {
  812. return S->isLive();
  813. }))
  814. return;
  815. // We only keep live symbols that are known to be non-prevailing if any are
  816. // available_externally, linkonceodr, weakodr. Those symbols are discarded
  817. // later in the EliminateAvailableExternally pass and setting them to
  818. // not-live could break downstreams users of liveness information (PR36483)
  819. // or limit optimization opportunities.
  820. if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
  821. bool KeepAliveLinkage = false;
  822. bool Interposable = false;
  823. for (const auto &S : VI.getSummaryList()) {
  824. if (S->linkage() == GlobalValue::AvailableExternallyLinkage ||
  825. S->linkage() == GlobalValue::WeakODRLinkage ||
  826. S->linkage() == GlobalValue::LinkOnceODRLinkage)
  827. KeepAliveLinkage = true;
  828. else if (GlobalValue::isInterposableLinkage(S->linkage()))
  829. Interposable = true;
  830. }
  831. if (!IsAliasee) {
  832. if (!KeepAliveLinkage)
  833. return;
  834. if (Interposable)
  835. report_fatal_error(
  836. "Interposable and available_externally/linkonce_odr/weak_odr "
  837. "symbol");
  838. }
  839. }
  840. for (const auto &S : VI.getSummaryList())
  841. S->setLive(true);
  842. ++LiveSymbols;
  843. Worklist.push_back(VI);
  844. };
  845. while (!Worklist.empty()) {
  846. auto VI = Worklist.pop_back_val();
  847. for (const auto &Summary : VI.getSummaryList()) {
  848. if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
  849. // If this is an alias, visit the aliasee VI to ensure that all copies
  850. // are marked live and it is added to the worklist for further
  851. // processing of its references.
  852. visit(AS->getAliaseeVI(), true);
  853. continue;
  854. }
  855. for (auto Ref : Summary->refs())
  856. visit(Ref, false);
  857. if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
  858. for (auto Call : FS->calls())
  859. visit(Call.first, false);
  860. }
  861. }
  862. Index.setWithGlobalValueDeadStripping();
  863. unsigned DeadSymbols = Index.size() - LiveSymbols;
  864. LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
  865. << " symbols Dead \n");
  866. NumDeadSymbols += DeadSymbols;
  867. NumLiveSymbols += LiveSymbols;
  868. }
  869. // Compute dead symbols and propagate constants in combined index.
  870. void llvm::computeDeadSymbolsWithConstProp(
  871. ModuleSummaryIndex &Index,
  872. const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
  873. function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing,
  874. bool ImportEnabled) {
  875. computeDeadSymbolsAndUpdateIndirectCalls(Index, GUIDPreservedSymbols,
  876. isPrevailing);
  877. if (ImportEnabled)
  878. Index.propagateAttributes(GUIDPreservedSymbols);
  879. }
  880. /// Compute the set of summaries needed for a ThinLTO backend compilation of
  881. /// \p ModulePath.
  882. void llvm::gatherImportedSummariesForModule(
  883. StringRef ModulePath,
  884. const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
  885. const FunctionImporter::ImportMapTy &ImportList,
  886. std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
  887. // Include all summaries from the importing module.
  888. ModuleToSummariesForIndex[std::string(ModulePath)] =
  889. ModuleToDefinedGVSummaries.lookup(ModulePath);
  890. // Include summaries for imports.
  891. for (const auto &ILI : ImportList) {
  892. auto &SummariesForIndex =
  893. ModuleToSummariesForIndex[std::string(ILI.first())];
  894. const auto &DefinedGVSummaries =
  895. ModuleToDefinedGVSummaries.lookup(ILI.first());
  896. for (const auto &GI : ILI.second) {
  897. const auto &DS = DefinedGVSummaries.find(GI);
  898. assert(DS != DefinedGVSummaries.end() &&
  899. "Expected a defined summary for imported global value");
  900. SummariesForIndex[GI] = DS->second;
  901. }
  902. }
  903. }
  904. /// Emit the files \p ModulePath will import from into \p OutputFilename.
  905. std::error_code llvm::EmitImportsFiles(
  906. StringRef ModulePath, StringRef OutputFilename,
  907. const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
  908. std::error_code EC;
  909. raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::OF_None);
  910. if (EC)
  911. return EC;
  912. for (const auto &ILI : ModuleToSummariesForIndex)
  913. // The ModuleToSummariesForIndex map includes an entry for the current
  914. // Module (needed for writing out the index files). We don't want to
  915. // include it in the imports file, however, so filter it out.
  916. if (ILI.first != ModulePath)
  917. ImportsOS << ILI.first << "\n";
  918. return std::error_code();
  919. }
  920. bool llvm::convertToDeclaration(GlobalValue &GV) {
  921. LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
  922. << "\n");
  923. if (Function *F = dyn_cast<Function>(&GV)) {
  924. F->deleteBody();
  925. F->clearMetadata();
  926. F->setComdat(nullptr);
  927. } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
  928. V->setInitializer(nullptr);
  929. V->setLinkage(GlobalValue::ExternalLinkage);
  930. V->clearMetadata();
  931. V->setComdat(nullptr);
  932. } else {
  933. GlobalValue *NewGV;
  934. if (GV.getValueType()->isFunctionTy())
  935. NewGV =
  936. Function::Create(cast<FunctionType>(GV.getValueType()),
  937. GlobalValue::ExternalLinkage, GV.getAddressSpace(),
  938. "", GV.getParent());
  939. else
  940. NewGV =
  941. new GlobalVariable(*GV.getParent(), GV.getValueType(),
  942. /*isConstant*/ false, GlobalValue::ExternalLinkage,
  943. /*init*/ nullptr, "",
  944. /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
  945. GV.getType()->getAddressSpace());
  946. NewGV->takeName(&GV);
  947. GV.replaceAllUsesWith(NewGV);
  948. return false;
  949. }
  950. if (!GV.isImplicitDSOLocal())
  951. GV.setDSOLocal(false);
  952. return true;
  953. }
  954. void llvm::thinLTOFinalizeInModule(Module &TheModule,
  955. const GVSummaryMapTy &DefinedGlobals,
  956. bool PropagateAttrs) {
  957. DenseSet<Comdat *> NonPrevailingComdats;
  958. auto FinalizeInModule = [&](GlobalValue &GV, bool Propagate = false) {
  959. // See if the global summary analysis computed a new resolved linkage.
  960. const auto &GS = DefinedGlobals.find(GV.getGUID());
  961. if (GS == DefinedGlobals.end())
  962. return;
  963. if (Propagate)
  964. if (FunctionSummary *FS = dyn_cast<FunctionSummary>(GS->second)) {
  965. if (Function *F = dyn_cast<Function>(&GV)) {
  966. // TODO: propagate ReadNone and ReadOnly.
  967. if (FS->fflags().ReadNone && !F->doesNotAccessMemory())
  968. F->setDoesNotAccessMemory();
  969. if (FS->fflags().ReadOnly && !F->onlyReadsMemory())
  970. F->setOnlyReadsMemory();
  971. if (FS->fflags().NoRecurse && !F->doesNotRecurse())
  972. F->setDoesNotRecurse();
  973. if (FS->fflags().NoUnwind && !F->doesNotThrow())
  974. F->setDoesNotThrow();
  975. }
  976. }
  977. auto NewLinkage = GS->second->linkage();
  978. if (GlobalValue::isLocalLinkage(GV.getLinkage()) ||
  979. // Don't internalize anything here, because the code below
  980. // lacks necessary correctness checks. Leave this job to
  981. // LLVM 'internalize' pass.
  982. GlobalValue::isLocalLinkage(NewLinkage) ||
  983. // In case it was dead and already converted to declaration.
  984. GV.isDeclaration())
  985. return;
  986. // Set the potentially more constraining visibility computed from summaries.
  987. // The DefaultVisibility condition is because older GlobalValueSummary does
  988. // not record DefaultVisibility and we don't want to change protected/hidden
  989. // to default.
  990. if (GS->second->getVisibility() != GlobalValue::DefaultVisibility)
  991. GV.setVisibility(GS->second->getVisibility());
  992. if (NewLinkage == GV.getLinkage())
  993. return;
  994. // Check for a non-prevailing def that has interposable linkage
  995. // (e.g. non-odr weak or linkonce). In that case we can't simply
  996. // convert to available_externally, since it would lose the
  997. // interposable property and possibly get inlined. Simply drop
  998. // the definition in that case.
  999. if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
  1000. GlobalValue::isInterposableLinkage(GV.getLinkage())) {
  1001. if (!convertToDeclaration(GV))
  1002. // FIXME: Change this to collect replaced GVs and later erase
  1003. // them from the parent module once thinLTOResolvePrevailingGUID is
  1004. // changed to enable this for aliases.
  1005. llvm_unreachable("Expected GV to be converted");
  1006. } else {
  1007. // If all copies of the original symbol had global unnamed addr and
  1008. // linkonce_odr linkage, or if all of them had local unnamed addr linkage
  1009. // and are constants, then it should be an auto hide symbol. In that case
  1010. // the thin link would have marked it as CanAutoHide. Add hidden
  1011. // visibility to the symbol to preserve the property.
  1012. if (NewLinkage == GlobalValue::WeakODRLinkage &&
  1013. GS->second->canAutoHide()) {
  1014. assert(GV.canBeOmittedFromSymbolTable());
  1015. GV.setVisibility(GlobalValue::HiddenVisibility);
  1016. }
  1017. LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
  1018. << "` from " << GV.getLinkage() << " to " << NewLinkage
  1019. << "\n");
  1020. GV.setLinkage(NewLinkage);
  1021. }
  1022. // Remove declarations from comdats, including available_externally
  1023. // as this is a declaration for the linker, and will be dropped eventually.
  1024. // It is illegal for comdats to contain declarations.
  1025. auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
  1026. if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
  1027. if (GO->getComdat()->getName() == GO->getName())
  1028. NonPrevailingComdats.insert(GO->getComdat());
  1029. GO->setComdat(nullptr);
  1030. }
  1031. };
  1032. // Process functions and global now
  1033. for (auto &GV : TheModule)
  1034. FinalizeInModule(GV, PropagateAttrs);
  1035. for (auto &GV : TheModule.globals())
  1036. FinalizeInModule(GV);
  1037. for (auto &GV : TheModule.aliases())
  1038. FinalizeInModule(GV);
  1039. // For a non-prevailing comdat, all its members must be available_externally.
  1040. // FinalizeInModule has handled non-local-linkage GlobalValues. Here we handle
  1041. // local linkage GlobalValues.
  1042. if (NonPrevailingComdats.empty())
  1043. return;
  1044. for (auto &GO : TheModule.global_objects()) {
  1045. if (auto *C = GO.getComdat(); C && NonPrevailingComdats.count(C)) {
  1046. GO.setComdat(nullptr);
  1047. GO.setLinkage(GlobalValue::AvailableExternallyLinkage);
  1048. }
  1049. }
  1050. bool Changed;
  1051. do {
  1052. Changed = false;
  1053. // If an alias references a GlobalValue in a non-prevailing comdat, change
  1054. // it to available_externally. For simplicity we only handle GlobalValue and
  1055. // ConstantExpr with a base object. ConstantExpr without a base object is
  1056. // unlikely used in a COMDAT.
  1057. for (auto &GA : TheModule.aliases()) {
  1058. if (GA.hasAvailableExternallyLinkage())
  1059. continue;
  1060. GlobalObject *Obj = GA.getAliaseeObject();
  1061. assert(Obj && "aliasee without an base object is unimplemented");
  1062. if (Obj->hasAvailableExternallyLinkage()) {
  1063. GA.setLinkage(GlobalValue::AvailableExternallyLinkage);
  1064. Changed = true;
  1065. }
  1066. }
  1067. } while (Changed);
  1068. }
  1069. /// Run internalization on \p TheModule based on symmary analysis.
  1070. void llvm::thinLTOInternalizeModule(Module &TheModule,
  1071. const GVSummaryMapTy &DefinedGlobals) {
  1072. // Declare a callback for the internalize pass that will ask for every
  1073. // candidate GlobalValue if it can be internalized or not.
  1074. auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
  1075. // It may be the case that GV is on a chain of an ifunc, its alias and
  1076. // subsequent aliases. In this case, the summary for the value is not
  1077. // available.
  1078. if (isa<GlobalIFunc>(&GV) ||
  1079. (isa<GlobalAlias>(&GV) &&
  1080. isa<GlobalIFunc>(cast<GlobalAlias>(&GV)->getAliaseeObject())))
  1081. return true;
  1082. // Lookup the linkage recorded in the summaries during global analysis.
  1083. auto GS = DefinedGlobals.find(GV.getGUID());
  1084. if (GS == DefinedGlobals.end()) {
  1085. // Must have been promoted (possibly conservatively). Find original
  1086. // name so that we can access the correct summary and see if it can
  1087. // be internalized again.
  1088. // FIXME: Eventually we should control promotion instead of promoting
  1089. // and internalizing again.
  1090. StringRef OrigName =
  1091. ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
  1092. std::string OrigId = GlobalValue::getGlobalIdentifier(
  1093. OrigName, GlobalValue::InternalLinkage,
  1094. TheModule.getSourceFileName());
  1095. GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
  1096. if (GS == DefinedGlobals.end()) {
  1097. // Also check the original non-promoted non-globalized name. In some
  1098. // cases a preempted weak value is linked in as a local copy because
  1099. // it is referenced by an alias (IRLinker::linkGlobalValueProto).
  1100. // In that case, since it was originally not a local value, it was
  1101. // recorded in the index using the original name.
  1102. // FIXME: This may not be needed once PR27866 is fixed.
  1103. GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
  1104. assert(GS != DefinedGlobals.end());
  1105. }
  1106. }
  1107. return !GlobalValue::isLocalLinkage(GS->second->linkage());
  1108. };
  1109. // FIXME: See if we can just internalize directly here via linkage changes
  1110. // based on the index, rather than invoking internalizeModule.
  1111. internalizeModule(TheModule, MustPreserveGV);
  1112. }
  1113. /// Make alias a clone of its aliasee.
  1114. static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
  1115. Function *Fn = cast<Function>(GA->getAliaseeObject());
  1116. ValueToValueMapTy VMap;
  1117. Function *NewFn = CloneFunction(Fn, VMap);
  1118. // Clone should use the original alias's linkage, visibility and name, and we
  1119. // ensure all uses of alias instead use the new clone (casted if necessary).
  1120. NewFn->setLinkage(GA->getLinkage());
  1121. NewFn->setVisibility(GA->getVisibility());
  1122. GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
  1123. NewFn->takeName(GA);
  1124. return NewFn;
  1125. }
  1126. // Internalize values that we marked with specific attribute
  1127. // in processGlobalForThinLTO.
  1128. static void internalizeGVsAfterImport(Module &M) {
  1129. for (auto &GV : M.globals())
  1130. // Skip GVs which have been converted to declarations
  1131. // by dropDeadSymbols.
  1132. if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) {
  1133. GV.setLinkage(GlobalValue::InternalLinkage);
  1134. GV.setVisibility(GlobalValue::DefaultVisibility);
  1135. }
  1136. }
  1137. // Automatically import functions in Module \p DestModule based on the summaries
  1138. // index.
  1139. Expected<bool> FunctionImporter::importFunctions(
  1140. Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
  1141. LLVM_DEBUG(dbgs() << "Starting import for Module "
  1142. << DestModule.getModuleIdentifier() << "\n");
  1143. unsigned ImportedCount = 0, ImportedGVCount = 0;
  1144. IRMover Mover(DestModule);
  1145. // Do the actual import of functions now, one Module at a time
  1146. std::set<StringRef> ModuleNameOrderedList;
  1147. for (const auto &FunctionsToImportPerModule : ImportList) {
  1148. ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
  1149. }
  1150. for (const auto &Name : ModuleNameOrderedList) {
  1151. // Get the module for the import
  1152. const auto &FunctionsToImportPerModule = ImportList.find(Name);
  1153. assert(FunctionsToImportPerModule != ImportList.end());
  1154. Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
  1155. if (!SrcModuleOrErr)
  1156. return SrcModuleOrErr.takeError();
  1157. std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
  1158. assert(&DestModule.getContext() == &SrcModule->getContext() &&
  1159. "Context mismatch");
  1160. // If modules were created with lazy metadata loading, materialize it
  1161. // now, before linking it (otherwise this will be a noop).
  1162. if (Error Err = SrcModule->materializeMetadata())
  1163. return std::move(Err);
  1164. auto &ImportGUIDs = FunctionsToImportPerModule->second;
  1165. // Find the globals to import
  1166. SetVector<GlobalValue *> GlobalsToImport;
  1167. for (Function &F : *SrcModule) {
  1168. if (!F.hasName())
  1169. continue;
  1170. auto GUID = F.getGUID();
  1171. auto Import = ImportGUIDs.count(GUID);
  1172. LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function "
  1173. << GUID << " " << F.getName() << " from "
  1174. << SrcModule->getSourceFileName() << "\n");
  1175. if (Import) {
  1176. if (Error Err = F.materialize())
  1177. return std::move(Err);
  1178. if (EnableImportMetadata) {
  1179. // Add 'thinlto_src_module' metadata for statistics and debugging.
  1180. F.setMetadata(
  1181. "thinlto_src_module",
  1182. MDNode::get(DestModule.getContext(),
  1183. {MDString::get(DestModule.getContext(),
  1184. SrcModule->getSourceFileName())}));
  1185. }
  1186. GlobalsToImport.insert(&F);
  1187. }
  1188. }
  1189. for (GlobalVariable &GV : SrcModule->globals()) {
  1190. if (!GV.hasName())
  1191. continue;
  1192. auto GUID = GV.getGUID();
  1193. auto Import = ImportGUIDs.count(GUID);
  1194. LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global "
  1195. << GUID << " " << GV.getName() << " from "
  1196. << SrcModule->getSourceFileName() << "\n");
  1197. if (Import) {
  1198. if (Error Err = GV.materialize())
  1199. return std::move(Err);
  1200. ImportedGVCount += GlobalsToImport.insert(&GV);
  1201. }
  1202. }
  1203. for (GlobalAlias &GA : SrcModule->aliases()) {
  1204. if (!GA.hasName() || isa<GlobalIFunc>(GA.getAliaseeObject()))
  1205. continue;
  1206. auto GUID = GA.getGUID();
  1207. auto Import = ImportGUIDs.count(GUID);
  1208. LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias "
  1209. << GUID << " " << GA.getName() << " from "
  1210. << SrcModule->getSourceFileName() << "\n");
  1211. if (Import) {
  1212. if (Error Err = GA.materialize())
  1213. return std::move(Err);
  1214. // Import alias as a copy of its aliasee.
  1215. GlobalObject *GO = GA.getAliaseeObject();
  1216. if (Error Err = GO->materialize())
  1217. return std::move(Err);
  1218. auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
  1219. LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << GO->getGUID() << " "
  1220. << GO->getName() << " from "
  1221. << SrcModule->getSourceFileName() << "\n");
  1222. if (EnableImportMetadata) {
  1223. // Add 'thinlto_src_module' metadata for statistics and debugging.
  1224. Fn->setMetadata(
  1225. "thinlto_src_module",
  1226. MDNode::get(DestModule.getContext(),
  1227. {MDString::get(DestModule.getContext(),
  1228. SrcModule->getSourceFileName())}));
  1229. }
  1230. GlobalsToImport.insert(Fn);
  1231. }
  1232. }
  1233. // Upgrade debug info after we're done materializing all the globals and we
  1234. // have loaded all the required metadata!
  1235. UpgradeDebugInfo(*SrcModule);
  1236. // Set the partial sample profile ratio in the profile summary module flag
  1237. // of the imported source module, if applicable, so that the profile summary
  1238. // module flag will match with that of the destination module when it's
  1239. // imported.
  1240. SrcModule->setPartialSampleProfileRatio(Index);
  1241. // Link in the specified functions.
  1242. if (renameModuleForThinLTO(*SrcModule, Index, ClearDSOLocalOnDeclarations,
  1243. &GlobalsToImport))
  1244. return true;
  1245. if (PrintImports) {
  1246. for (const auto *GV : GlobalsToImport)
  1247. dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
  1248. << " from " << SrcModule->getSourceFileName() << "\n";
  1249. }
  1250. if (Error Err = Mover.move(std::move(SrcModule),
  1251. GlobalsToImport.getArrayRef(), nullptr,
  1252. /*IsPerformingImport=*/true))
  1253. report_fatal_error(Twine("Function Import: link error: ") +
  1254. toString(std::move(Err)));
  1255. ImportedCount += GlobalsToImport.size();
  1256. NumImportedModules++;
  1257. }
  1258. internalizeGVsAfterImport(DestModule);
  1259. NumImportedFunctions += (ImportedCount - ImportedGVCount);
  1260. NumImportedGlobalVars += ImportedGVCount;
  1261. LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
  1262. << " functions for Module "
  1263. << DestModule.getModuleIdentifier() << "\n");
  1264. LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
  1265. << " global variables for Module "
  1266. << DestModule.getModuleIdentifier() << "\n");
  1267. return ImportedCount;
  1268. }
  1269. static bool doImportingForModule(Module &M) {
  1270. if (SummaryFile.empty())
  1271. report_fatal_error("error: -function-import requires -summary-file\n");
  1272. Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
  1273. getModuleSummaryIndexForFile(SummaryFile);
  1274. if (!IndexPtrOrErr) {
  1275. logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
  1276. "Error loading file '" + SummaryFile + "': ");
  1277. return false;
  1278. }
  1279. std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
  1280. // First step is collecting the import list.
  1281. FunctionImporter::ImportMapTy ImportList;
  1282. // If requested, simply import all functions in the index. This is used
  1283. // when testing distributed backend handling via the opt tool, when
  1284. // we have distributed indexes containing exactly the summaries to import.
  1285. if (ImportAllIndex)
  1286. ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
  1287. ImportList);
  1288. else
  1289. ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
  1290. ImportList);
  1291. // Conservatively mark all internal values as promoted. This interface is
  1292. // only used when doing importing via the function importing pass. The pass
  1293. // is only enabled when testing importing via the 'opt' tool, which does
  1294. // not do the ThinLink that would normally determine what values to promote.
  1295. for (auto &I : *Index) {
  1296. for (auto &S : I.second.SummaryList) {
  1297. if (GlobalValue::isLocalLinkage(S->linkage()))
  1298. S->setLinkage(GlobalValue::ExternalLinkage);
  1299. }
  1300. }
  1301. // Next we need to promote to global scope and rename any local values that
  1302. // are potentially exported to other modules.
  1303. if (renameModuleForThinLTO(M, *Index, /*ClearDSOLocalOnDeclarations=*/false,
  1304. /*GlobalsToImport=*/nullptr)) {
  1305. errs() << "Error renaming module\n";
  1306. return false;
  1307. }
  1308. // Perform the import now.
  1309. auto ModuleLoader = [&M](StringRef Identifier) {
  1310. return loadFile(std::string(Identifier), M.getContext());
  1311. };
  1312. FunctionImporter Importer(*Index, ModuleLoader,
  1313. /*ClearDSOLocalOnDeclarations=*/false);
  1314. Expected<bool> Result = Importer.importFunctions(M, ImportList);
  1315. // FIXME: Probably need to propagate Errors through the pass manager.
  1316. if (!Result) {
  1317. logAllUnhandledErrors(Result.takeError(), errs(),
  1318. "Error importing module: ");
  1319. return false;
  1320. }
  1321. return *Result;
  1322. }
  1323. PreservedAnalyses FunctionImportPass::run(Module &M,
  1324. ModuleAnalysisManager &AM) {
  1325. if (!doImportingForModule(M))
  1326. return PreservedAnalyses::all();
  1327. return PreservedAnalyses::none();
  1328. }