FunctionImport.cpp 59 KB

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