blob: 233a36d2bc543b5ae12fb91e8012e328c970a4ce [file] [log] [blame]
Mehdi Amini42418ab2015-11-24 06:07:49 +00001//===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements Function import based on summaries.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/IPO/FunctionImport.h"
15
Mehdi Amini01e32132016-03-26 05:40:34 +000016#include "llvm/ADT/SmallVector.h"
Teresa Johnsond29478f2016-03-27 15:27:30 +000017#include "llvm/ADT/Statistic.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000018#include "llvm/ADT/StringSet.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000019#include "llvm/ADT/Triple.h"
Peter Collingbournec15d60b2017-05-01 20:42:32 +000020#include "llvm/Bitcode/BitcodeReader.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000021#include "llvm/IR/AutoUpgrade.h"
22#include "llvm/IR/DiagnosticPrinter.h"
23#include "llvm/IR/IntrinsicInst.h"
24#include "llvm/IR/Module.h"
Mehdi Aminifc06b832016-12-23 18:04:51 +000025#include "llvm/IR/Verifier.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000026#include "llvm/IRReader/IRReader.h"
27#include "llvm/Linker/Linker.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000028#include "llvm/Object/IRObjectFile.h"
Mehdi Amini42418ab2015-11-24 06:07:49 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/SourceMgr.h"
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000032#include "llvm/Transforms/IPO/Internalize.h"
Teresa Johnson488a8002016-02-10 18:11:31 +000033#include "llvm/Transforms/Utils/FunctionImportUtils.h"
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000034
Mehdi Amini01e32132016-03-26 05:40:34 +000035#define DEBUG_TYPE "function-import"
Mehdi Amini7e88d0d2015-12-09 08:17:35 +000036
Mehdi Amini42418ab2015-11-24 06:07:49 +000037using namespace llvm;
38
Teresa Johnson6c475a72017-01-05 21:34:18 +000039STATISTIC(NumImportedFunctions, "Number of functions imported");
40STATISTIC(NumImportedModules, "Number of modules imported from");
41STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
42STATISTIC(NumLiveSymbols, "Number of live symbols in index");
Teresa Johnsond29478f2016-03-27 15:27:30 +000043
Teresa Johnson39303612015-11-24 22:55:46 +000044/// Limit on instruction count of imported functions.
45static cl::opt<unsigned> ImportInstrLimit(
46 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
47 cl::desc("Only import functions with less than N instructions"));
48
Mehdi Amini40641742016-02-10 23:31:45 +000049static cl::opt<float>
50 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
51 cl::Hidden, cl::value_desc("x"),
52 cl::desc("As we import functions, multiply the "
53 "`import-instr-limit` threshold by this factor "
54 "before processing newly imported functions"));
Piotr Padlewskiba72b952016-09-29 17:32:07 +000055
Piotr Padlewskid2869472016-09-30 03:01:17 +000056static cl::opt<float> ImportHotInstrFactor(
57 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
58 cl::value_desc("x"),
59 cl::desc("As we import functions called from hot callsite, multiply the "
60 "`import-instr-limit` threshold by this factor "
61 "before processing newly imported functions"));
62
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000063static cl::opt<float> ImportHotMultiplier(
64 "import-hot-multiplier", cl::init(3.0), cl::Hidden, cl::value_desc("x"),
Piotr Padlewskiba72b952016-09-29 17:32:07 +000065 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
66
Dehao Chen64c46572017-07-07 21:01:00 +000067static cl::opt<float> ImportCriticalMultiplier(
68 "import-critical-multiplier", cl::init(100.0), cl::Hidden,
69 cl::value_desc("x"),
70 cl::desc(
71 "Multiply the `import-instr-limit` threshold for critical callsites"));
72
Piotr Padlewskiba72b952016-09-29 17:32:07 +000073// FIXME: This multiplier was not really tuned up.
74static cl::opt<float> ImportColdMultiplier(
75 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
76 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
Mehdi Amini40641742016-02-10 23:31:45 +000077
Teresa Johnsond29478f2016-03-27 15:27:30 +000078static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
79 cl::desc("Print imported functions"));
80
Teresa Johnson6c475a72017-01-05 21:34:18 +000081static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
82 cl::desc("Compute dead symbols"));
83
Piotr Padlewski3b776122016-07-08 23:01:49 +000084static cl::opt<bool> EnableImportMetadata(
85 "enable-import-metadata", cl::init(
86#if !defined(NDEBUG)
87 true /*Enabled with asserts.*/
88#else
89 false
90#endif
91 ),
92 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
93
Mehdi Amini42418ab2015-11-24 06:07:49 +000094// Load lazily a module from \p FileName in \p Context.
95static std::unique_ptr<Module> loadFile(const std::string &FileName,
96 LLVMContext &Context) {
97 SMDiagnostic Err;
98 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
Teresa Johnson6cba37c2016-01-22 00:15:53 +000099 // Metadata isn't loaded until functions are imported, to minimize
100 // the memory overhead.
Teresa Johnsona1080ee2016-01-08 14:17:41 +0000101 std::unique_ptr<Module> Result =
102 getLazyIRFileModule(FileName, Err, Context,
103 /* ShouldLazyLoadMetadata = */ true);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000104 if (!Result) {
105 Err.print("function-import", errs());
Mehdi Aminid7ad2212016-04-01 05:33:11 +0000106 report_fatal_error("Abort");
Mehdi Amini42418ab2015-11-24 06:07:49 +0000107 }
108
Mehdi Amini42418ab2015-11-24 06:07:49 +0000109 return Result;
110}
111
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000112namespace {
Mehdi Amini40641742016-02-10 23:31:45 +0000113
Mehdi Amini01e32132016-03-26 05:40:34 +0000114/// Given a list of possible callee implementation for a call site, select one
115/// that fits the \p Threshold.
116///
117/// FIXME: select "best" instead of first that fits. But what is "best"?
118/// - The smallest: more likely to be inlined.
119/// - The one with the least outgoing edges (already well optimized).
120/// - One from a module already being imported from in order to reduce the
121/// number of source modules parsed/linked.
122/// - One that has PGO data attached.
123/// - [insert you fancy metric here]
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000124static const GlobalValueSummary *
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000125selectCallee(const ModuleSummaryIndex &Index,
Peter Collingbourne9667b912017-05-04 18:03:25 +0000126 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
Teresa Johnson83aaf352017-01-12 22:04:45 +0000127 unsigned Threshold, StringRef CallerModulePath) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000128 auto It = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000129 CalleeSummaryList,
130 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
131 auto *GVSummary = SummaryPtr.get();
Rafael Espindolaf329be82016-05-11 01:26:06 +0000132 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000133 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000134 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000135 if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
136 GVSummary = &AS->getAliasee();
137 // Alias can't point to "available_externally". However when we import
138 // linkOnceODR the linkage does not change. So we import the alias
139 // and aliasee only in this case.
140 // FIXME: we should import alias as available_externally *function*,
141 // the destination module does need to know it is an alias.
142 if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
143 return false;
144 }
145
146 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000147
Teresa Johnson83aaf352017-01-12 22:04:45 +0000148 // If this is a local function, make sure we import the copy
149 // in the caller's module. The only time a local function can
150 // share an entry in the index is if there is a local with the same name
151 // in another module that had the same source file name (in a different
152 // directory), where each was compiled in their own directory so there
153 // was not distinguishing path.
154 // However, do the import from another module if there is only one
155 // entry in the list - in that case this must be a reference due
156 // to indirect call profile data, since a function pointer can point to
157 // a local in another module.
158 if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
159 CalleeSummaryList.size() > 1 &&
160 Summary->modulePath() != CallerModulePath)
161 return false;
162
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000163 if (Summary->instCount() > Threshold)
164 return false;
165
Teresa Johnson519465b2017-01-05 14:32:16 +0000166 if (Summary->notEligibleToImport())
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000167 return false;
168
Mehdi Amini01e32132016-03-26 05:40:34 +0000169 return true;
170 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000171 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000172 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000173
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000174 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000175}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000176
Teresa Johnson475b51a2016-12-15 20:48:19 +0000177using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
178 GlobalValue::GUID>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000179
Mehdi Amini01e32132016-03-26 05:40:34 +0000180/// Compute the list of functions to import for a given caller. Mark these
181/// imported functions and the symbols they reference in their source module as
182/// exported from their source module.
183static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000184 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000185 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000186 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000187 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000188 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000189 for (auto &Edge : Summary.calls()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000190 ValueInfo VI = Edge.first;
191 DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold
192 << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000193
Peter Collingbourne9667b912017-05-04 18:03:25 +0000194 if (VI.getSummaryList().empty()) {
Dehao Chen4a435e02017-03-14 17:33:01 +0000195 // For SamplePGO, the indirect call targets for local functions will
196 // have its original name annotated in profile. We try to find the
197 // corresponding PGOFuncName as the GUID.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000198 auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
Dehao Chen4a435e02017-03-14 17:33:01 +0000199 if (GUID == 0)
200 continue;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000201 VI = Index.getValueInfo(GUID);
202 if (!VI)
203 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +0000204 }
205
Peter Collingbourne9667b912017-05-04 18:03:25 +0000206 if (DefinedGVSummaries.count(VI.getGUID())) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000207 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
208 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000209 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000210
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000211 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
212 if (Hotness == CalleeInfo::HotnessType::Hot)
213 return ImportHotMultiplier;
214 if (Hotness == CalleeInfo::HotnessType::Cold)
215 return ImportColdMultiplier;
Dehao Chen64c46572017-07-07 21:01:00 +0000216 if (Hotness == CalleeInfo::HotnessType::Critical)
217 return ImportCriticalMultiplier;
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000218 return 1.0;
219 };
220
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000221 const auto NewThreshold =
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000222 Threshold * GetBonusMultiplier(Edge.second.Hotness);
Piotr Padlewskid2869472016-09-30 03:01:17 +0000223
Peter Collingbourne9667b912017-05-04 18:03:25 +0000224 auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
225 Summary.modulePath());
Mehdi Amini01e32132016-03-26 05:40:34 +0000226 if (!CalleeSummary) {
227 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
228 continue;
229 }
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000230 // "Resolve" the summary, traversing alias,
231 const FunctionSummary *ResolvedCalleeSummary;
Mehdi Amini6968ef72016-04-20 01:04:20 +0000232 if (isa<AliasSummary>(CalleeSummary)) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000233 ResolvedCalleeSummary = cast<FunctionSummary>(
234 &cast<AliasSummary>(CalleeSummary)->getAliasee());
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000235 assert(
236 GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
237 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini6968ef72016-04-20 01:04:20 +0000238 } else
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000239 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
240
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000241 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000242 "selectCallee() didn't honor the threshold");
243
Piotr Padlewskid2869472016-09-30 03:01:17 +0000244 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
245 // Adjust the threshold for next level of imported functions.
246 // The threshold is different for hot callsites because we can then
247 // inline chains of hot calls.
248 if (IsHotCallsite)
249 return Threshold * ImportHotInstrFactor;
250 return Threshold * ImportInstrFactor;
251 };
252
253 bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000254 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
255
256 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000257 auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
Teresa Johnson1b859a22016-12-15 18:21:01 +0000258 /// Since the traversal of the call graph is DFS, we can revisit a function
259 /// a second time with a higher threshold. In this case, it is added back to
260 /// the worklist with the new threshold.
261 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
262 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
263 << ProcessedThreshold << "\n");
264 continue;
265 }
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000266 bool PreviouslyImported = ProcessedThreshold != 0;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000267 // Mark this function as imported in this module, with the current Threshold
268 ProcessedThreshold = AdjThreshold;
269
270 // Make exports in the source module.
271 if (ExportLists) {
272 auto &ExportList = (*ExportLists)[ExportModulePath];
Peter Collingbourne9667b912017-05-04 18:03:25 +0000273 ExportList.insert(VI.getGUID());
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000274 if (!PreviouslyImported) {
275 // This is the first time this function was exported from its source
276 // module, so mark all functions and globals it references as exported
277 // to the outside if they are defined in the same source module.
Teresa Johnsonedddca22016-12-16 04:11:51 +0000278 // For efficiency, we unconditionally add all the referenced GUIDs
279 // to the ExportList for this module, and will prune out any not
280 // defined in the module later in a single pass.
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000281 for (auto &Edge : ResolvedCalleeSummary->calls()) {
282 auto CalleeGUID = Edge.first.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000283 ExportList.insert(CalleeGUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000284 }
285 for (auto &Ref : ResolvedCalleeSummary->refs()) {
286 auto GUID = Ref.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000287 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000288 }
Teresa Johnson1b859a22016-12-15 18:21:01 +0000289 }
290 }
Piotr Padlewskid2869472016-09-30 03:01:17 +0000291
Mehdi Amini01e32132016-03-26 05:40:34 +0000292 // Insert the newly imported function to the worklist.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000293 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
Teresa Johnsond450da32015-11-24 21:15:19 +0000294 }
295}
296
Mehdi Amini01e32132016-03-26 05:40:34 +0000297/// Given the list of globals defined in a module, compute the list of imports
298/// as well as the list of "exports", i.e. the list of symbols referenced from
299/// another module (that may require promotion).
300static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000301 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000302 FunctionImporter::ImportMapTy &ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000303 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000304 // Worklist contains the list of function imported in this module, for which
305 // we will analyse the callees and may import further down the callgraph.
306 SmallVector<EdgeInfo, 128> Worklist;
307
308 // Populate the worklist with the import for the functions in the current
309 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000310 for (auto &GVSummary : DefinedGVSummaries) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000311 if (!Index.isGlobalValueLive(GVSummary.second)) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000312 DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
313 continue;
314 }
Teresa Johnson28e457b2016-04-24 14:57:11 +0000315 auto *Summary = GVSummary.second;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000316 if (auto *AS = dyn_cast<AliasSummary>(Summary))
317 Summary = &AS->getAliasee();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000318 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
319 if (!FuncSummary)
320 // Skip import for global variables
321 continue;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000322 DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000323 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000324 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000325 ExportLists);
326 }
327
Piotr Padlewskid2869472016-09-30 03:01:17 +0000328 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000329 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000330 auto FuncInfo = Worklist.pop_back_val();
Teresa Johnson475b51a2016-12-15 20:48:19 +0000331 auto *Summary = std::get<0>(FuncInfo);
332 auto Threshold = std::get<1>(FuncInfo);
333 auto GUID = std::get<2>(FuncInfo);
334
335 // Check if we later added this summary with a higher threshold.
336 // If so, skip this entry.
337 auto ExportModulePath = Summary->modulePath();
338 auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
339 if (LatestProcessedThreshold > Threshold)
340 continue;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000341
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000342 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000343 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000344 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000345}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000346
Mehdi Amini01e32132016-03-26 05:40:34 +0000347} // anonymous namespace
348
Teresa Johnsonc86af332016-04-12 21:13:11 +0000349/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000350void llvm::ComputeCrossModuleImport(
351 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000352 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000353 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000354 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000355 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000356 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000357 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000358 DEBUG(dbgs() << "Computing import for Module '"
359 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000360 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000361 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000362 }
363
Teresa Johnsonedddca22016-12-16 04:11:51 +0000364 // When computing imports we added all GUIDs referenced by anything
365 // imported from the module to its ExportList. Now we prune each ExportList
366 // of any not defined in that module. This is more efficient than checking
367 // while computing imports because some of the summary lists may be long
368 // due to linkonce (comdat) copies.
369 for (auto &ELI : ExportLists) {
370 const auto &DefinedGVSummaries =
371 ModuleToDefinedGVSummaries.lookup(ELI.first());
372 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
373 if (!DefinedGVSummaries.count(*EI))
374 EI = ELI.second.erase(EI);
375 else
376 ++EI;
377 }
378 }
379
Mehdi Amini01e32132016-03-26 05:40:34 +0000380#ifndef NDEBUG
381 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
382 << " modules:\n");
383 for (auto &ModuleImports : ImportLists) {
384 auto ModName = ModuleImports.first();
385 auto &Exports = ExportLists[ModName];
386 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
387 << " functions. Imports from " << ModuleImports.second.size()
388 << " modules.\n");
389 for (auto &Src : ModuleImports.second) {
390 auto SrcModName = Src.first();
391 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
392 << SrcModName << "\n");
393 }
394 }
395#endif
396}
397
Teresa Johnsonc86af332016-04-12 21:13:11 +0000398/// Compute all the imports for the given module in the Index.
399void llvm::ComputeCrossModuleImportForModule(
400 StringRef ModulePath, const ModuleSummaryIndex &Index,
401 FunctionImporter::ImportMapTy &ImportList) {
402
403 // Collect the list of functions this module defines.
404 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000405 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000406 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000407
408 // Compute the import list for this module.
409 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000410 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000411
412#ifndef NDEBUG
413 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
414 << ImportList.size() << " modules.\n");
415 for (auto &Src : ImportList) {
416 auto SrcModName = Src.first();
417 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
418 << SrcModName << "\n");
419 }
420#endif
421}
422
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000423void llvm::computeDeadSymbols(
424 ModuleSummaryIndex &Index,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000425 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000426 assert(!Index.withGlobalValueDeadStripping());
Teresa Johnson6c475a72017-01-05 21:34:18 +0000427 if (!ComputeDead)
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000428 return;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000429 if (GUIDPreservedSymbols.empty())
430 // Don't do anything when nothing is live, this is friendly with tests.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000431 return;
432 unsigned LiveSymbols = 0;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000433 SmallVector<ValueInfo, 128> Worklist;
434 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
435 for (auto GUID : GUIDPreservedSymbols) {
436 ValueInfo VI = Index.getValueInfo(GUID);
437 if (!VI)
438 continue;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000439 for (auto &S : VI.getSummaryList())
440 S->setLive(true);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000441 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000442
Teresa Johnson6c475a72017-01-05 21:34:18 +0000443 // Add values flagged in the index as live roots to the worklist.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000444 for (const auto &Entry : Index)
445 for (auto &S : Entry.second.SummaryList)
446 if (S->isLive()) {
447 DEBUG(dbgs() << "Live root: " << Entry.first << "\n");
448 Worklist.push_back(ValueInfo(&Entry));
449 ++LiveSymbols;
450 break;
451 }
452
453 // Make value live and add it to the worklist if it was not live before.
454 // FIXME: we should only make the prevailing copy live here
455 auto visit = [&](ValueInfo VI) {
456 for (auto &S : VI.getSummaryList())
457 if (S->isLive())
458 return;
459 for (auto &S : VI.getSummaryList())
460 S->setLive(true);
461 ++LiveSymbols;
462 Worklist.push_back(VI);
463 };
Teresa Johnson6c475a72017-01-05 21:34:18 +0000464
465 while (!Worklist.empty()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000466 auto VI = Worklist.pop_back_val();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000467 for (auto &Summary : VI.getSummaryList()) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000468 for (auto Ref : Summary->refs())
469 visit(Ref);
470 if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
471 for (auto Call : FS->calls())
472 visit(Call.first);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000473 if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
474 auto AliaseeGUID = AS->getAliasee().getOriginalName();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000475 ValueInfo AliaseeVI = Index.getValueInfo(AliaseeGUID);
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000476 if (AliaseeVI)
477 visit(AliaseeVI);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000478 }
479 }
480 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000481 Index.setWithGlobalValueDeadStripping();
482
483 unsigned DeadSymbols = Index.size() - LiveSymbols;
484 DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
485 << " symbols Dead \n");
486 NumDeadSymbols += DeadSymbols;
487 NumLiveSymbols += LiveSymbols;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000488}
489
Teresa Johnson84174c32016-05-10 13:48:23 +0000490/// Compute the set of summaries needed for a ThinLTO backend compilation of
491/// \p ModulePath.
492void llvm::gatherImportedSummariesForModule(
493 StringRef ModulePath,
494 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000495 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000496 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
497 // Include all summaries from the importing module.
498 ModuleToSummariesForIndex[ModulePath] =
499 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000500 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000501 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000502 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
503 const auto &DefinedGVSummaries =
504 ModuleToDefinedGVSummaries.lookup(ILI.first());
505 for (auto &GI : ILI.second) {
506 const auto &DS = DefinedGVSummaries.find(GI.first);
507 assert(DS != DefinedGVSummaries.end() &&
508 "Expected a defined summary for imported global value");
509 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000510 }
511 }
512}
513
Teresa Johnson8570fe42016-05-10 15:54:09 +0000514/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000515std::error_code
516llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
517 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000518 std::error_code EC;
519 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
520 if (EC)
521 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000522 for (auto &ILI : ModuleImports)
523 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000524 return std::error_code();
525}
526
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000527/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
528void llvm::thinLTOResolveWeakForLinkerModule(
529 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000530 auto ConvertToDeclaration = [](GlobalValue &GV) {
531 DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
532 if (Function *F = dyn_cast<Function>(&GV)) {
533 F->deleteBody();
534 F->clearMetadata();
535 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
536 V->setInitializer(nullptr);
537 V->setLinkage(GlobalValue::ExternalLinkage);
538 V->clearMetadata();
539 } else
540 // For now we don't resolve or drop aliases. Once we do we'll
541 // need to add support here for creating either a function or
542 // variable declaration, and return the new GlobalValue* for
543 // the caller to use.
Davide Italiano91239082017-04-14 17:22:02 +0000544 llvm_unreachable("Expected function or variable");
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000545 };
546
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000547 auto updateLinkage = [&](GlobalValue &GV) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000548 // See if the global summary analysis computed a new resolved linkage.
549 const auto &GS = DefinedGlobals.find(GV.getGUID());
550 if (GS == DefinedGlobals.end())
551 return;
552 auto NewLinkage = GS->second->linkage();
553 if (NewLinkage == GV.getLinkage())
554 return;
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000555
556 // Switch the linkage to weakany if asked for, e.g. we do this for
557 // linker redefined symbols (via --wrap or --defsym).
Davide Italianof4891d22017-07-06 20:04:20 +0000558 // We record that the visibility should be changed here in `addThinLTO`
559 // as we need access to the resolution vectors for each input file in
560 // order to find which symbols have been redefined.
561 // We may consider reorganizing this code and moving the linkage recording
562 // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex.
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000563 if (NewLinkage == GlobalValue::WeakAnyLinkage) {
564 GV.setLinkage(NewLinkage);
565 return;
566 }
567
568 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
569 return;
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000570 // Check for a non-prevailing def that has interposable linkage
571 // (e.g. non-odr weak or linkonce). In that case we can't simply
572 // convert to available_externally, since it would lose the
573 // interposable property and possibly get inlined. Simply drop
574 // the definition in that case.
575 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
576 GlobalValue::isInterposableLinkage(GV.getLinkage()))
577 ConvertToDeclaration(GV);
578 else {
579 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
580 << GV.getLinkage() << " to " << NewLinkage << "\n");
581 GV.setLinkage(NewLinkage);
582 }
583 // Remove declarations from comdats, including available_externally
Teresa Johnson6107a412016-08-15 21:00:04 +0000584 // as this is a declaration for the linker, and will be dropped eventually.
585 // It is illegal for comdats to contain declarations.
586 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000587 if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
Teresa Johnson6107a412016-08-15 21:00:04 +0000588 GO->setComdat(nullptr);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000589 };
590
591 // Process functions and global now
592 for (auto &GV : TheModule)
593 updateLinkage(GV);
594 for (auto &GV : TheModule.globals())
595 updateLinkage(GV);
596 for (auto &GV : TheModule.aliases())
597 updateLinkage(GV);
598}
599
600/// Run internalization on \p TheModule based on symmary analysis.
601void llvm::thinLTOInternalizeModule(Module &TheModule,
602 const GVSummaryMapTy &DefinedGlobals) {
603 // Parse inline ASM and collect the list of symbols that are not defined in
604 // the current module.
605 StringSet<> AsmUndefinedRefs;
Peter Collingbourne863cbfb2016-12-01 06:51:47 +0000606 ModuleSymbolTable::CollectAsmSymbols(
Teresa Johnsond8204472017-03-09 00:19:49 +0000607 TheModule,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000608 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
609 if (Flags & object::BasicSymbolRef::SF_Undefined)
610 AsmUndefinedRefs.insert(Name);
611 });
612
613 // Declare a callback for the internalize pass that will ask for every
614 // candidate GlobalValue if it can be internalized or not.
615 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
616 // Can't be internalized if referenced in inline asm.
617 if (AsmUndefinedRefs.count(GV.getName()))
618 return true;
619
620 // Lookup the linkage recorded in the summaries during global analysis.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000621 auto GS = DefinedGlobals.find(GV.getGUID());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000622 if (GS == DefinedGlobals.end()) {
623 // Must have been promoted (possibly conservatively). Find original
624 // name so that we can access the correct summary and see if it can
625 // be internalized again.
626 // FIXME: Eventually we should control promotion instead of promoting
627 // and internalizing again.
628 StringRef OrigName =
629 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
630 std::string OrigId = GlobalValue::getGlobalIdentifier(
631 OrigName, GlobalValue::InternalLinkage,
632 TheModule.getSourceFileName());
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000633 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000634 if (GS == DefinedGlobals.end()) {
635 // Also check the original non-promoted non-globalized name. In some
636 // cases a preempted weak value is linked in as a local copy because
637 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
638 // In that case, since it was originally not a local value, it was
639 // recorded in the index using the original name.
640 // FIXME: This may not be needed once PR27866 is fixed.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000641 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000642 assert(GS != DefinedGlobals.end());
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000643 }
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000644 }
645 return !GlobalValue::isLocalLinkage(GS->second->linkage());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000646 };
647
648 // FIXME: See if we can just internalize directly here via linkage changes
649 // based on the index, rather than invoking internalizeModule.
650 llvm::internalizeModule(TheModule, MustPreserveGV);
651}
652
Mehdi Aminic8c55172015-12-03 02:37:33 +0000653// Automatically import functions in Module \p DestModule based on the summaries
654// index.
655//
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000656Expected<bool> FunctionImporter::importFunctions(
Adrian Prantl66043792017-05-19 23:32:21 +0000657 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000658 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000659 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000660 unsigned ImportedCount = 0;
661
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000662 IRMover Mover(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000663 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000664 std::set<StringRef> ModuleNameOrderedList;
665 for (auto &FunctionsToImportPerModule : ImportList) {
666 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
667 }
668 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000669 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000670 const auto &FunctionsToImportPerModule = ImportList.find(Name);
671 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +0000672 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
673 if (!SrcModuleOrErr)
674 return SrcModuleOrErr.takeError();
675 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000676 assert(&DestModule.getContext() == &SrcModule->getContext() &&
677 "Context mismatch");
678
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000679 // If modules were created with lazy metadata loading, materialize it
680 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000681 if (Error Err = SrcModule->materializeMetadata())
682 return std::move(Err);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000683
Mehdi Amini01e32132016-03-26 05:40:34 +0000684 auto &ImportGUIDs = FunctionsToImportPerModule->second;
685 // Find the globals to import
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000686 SetVector<GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000687 for (Function &F : *SrcModule) {
688 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000689 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000690 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000691 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000692 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000693 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000694 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000695 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000696 if (Error Err = F.materialize())
697 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000698 if (EnableImportMetadata) {
699 // Add 'thinlto_src_module' metadata for statistics and debugging.
700 F.setMetadata(
701 "thinlto_src_module",
702 llvm::MDNode::get(
703 DestModule.getContext(),
704 {llvm::MDString::get(DestModule.getContext(),
705 SrcModule->getSourceFileName())}));
706 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000707 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000708 }
709 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000710 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000711 if (!GV.hasName())
712 continue;
713 auto GUID = GV.getGUID();
714 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000715 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
716 << " " << GV.getName() << " from "
717 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000718 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000719 if (Error Err = GV.materialize())
720 return std::move(Err);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000721 GlobalsToImport.insert(&GV);
722 }
723 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000724 for (GlobalAlias &GA : SrcModule->aliases()) {
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000725 // FIXME: This should eventually be controlled entirely by the summary.
726 if (FunctionImportGlobalProcessing::doImportAsDefinition(
727 &GA, &GlobalsToImport)) {
728 GlobalsToImport.insert(&GA);
729 continue;
730 }
731
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000732 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000733 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000734 auto GUID = GA.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000735 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000736 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000737 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000738 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000739 if (Import) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000740 // Alias can't point to "available_externally". However when we import
Teresa Johnson9aae3952016-03-27 15:01:11 +0000741 // linkOnceODR the linkage does not change. So we import the alias
Mehdi Amini6968ef72016-04-20 01:04:20 +0000742 // and aliasee only in this case. This has been handled by
743 // computeImportForFunction()
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000744 GlobalObject *GO = GA.getBaseObject();
Mehdi Amini6968ef72016-04-20 01:04:20 +0000745 assert(GO->hasLinkOnceODRLinkage() &&
746 "Unexpected alias to a non-linkonceODR in import list");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000747#ifndef NDEBUG
748 if (!GlobalsToImport.count(GO))
749 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
750 << " " << GO->getName() << " from "
751 << SrcModule->getSourceFileName() << "\n");
752#endif
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000753 if (Error Err = GO->materialize())
754 return std::move(Err);
Mehdi Amini01e32132016-03-26 05:40:34 +0000755 GlobalsToImport.insert(GO);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000756 if (Error Err = GA.materialize())
757 return std::move(Err);
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000758 GlobalsToImport.insert(&GA);
Mehdi Amini01e32132016-03-26 05:40:34 +0000759 }
760 }
761
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000762 // Upgrade debug info after we're done materializing all the globals and we
763 // have loaded all the required metadata!
764 UpgradeDebugInfo(*SrcModule);
765
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000766 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000767 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000768 return true;
769
Teresa Johnsond29478f2016-03-27 15:27:30 +0000770 if (PrintImports) {
771 for (const auto *GV : GlobalsToImport)
772 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
773 << " from " << SrcModule->getSourceFileName() << "\n";
774 }
775
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000776 if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
777 [](GlobalValue &, IRMover::ValueAdder) {},
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +0000778 /*IsPerformingImport=*/true))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000779 report_fatal_error("Function Import: link error");
780
Mehdi Amini01e32132016-03-26 05:40:34 +0000781 ImportedCount += GlobalsToImport.size();
Teresa Johnson6c475a72017-01-05 21:34:18 +0000782 NumImportedModules++;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000783 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000784
Teresa Johnson6c475a72017-01-05 21:34:18 +0000785 NumImportedFunctions += ImportedCount;
Teresa Johnsond29478f2016-03-27 15:27:30 +0000786
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000787 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000788 << DestModule.getModuleIdentifier() << "\n");
789 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000790}
791
792/// Summary file to use for function importing when using -function-import from
793/// the command line.
794static cl::opt<std::string>
795 SummaryFile("summary-file",
796 cl::desc("The summary file to use for function importing."));
797
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000798static bool doImportingForModule(Module &M) {
799 if (SummaryFile.empty())
800 report_fatal_error("error: -function-import requires -summary-file\n");
801 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
802 getModuleSummaryIndexForFile(SummaryFile);
803 if (!IndexPtrOrErr) {
804 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
805 "Error loading file '" + SummaryFile + "': ");
806 return false;
Teresa Johnson21241572016-07-18 21:22:24 +0000807 }
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000808 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +0000809
810 // First step is collecting the import list.
811 FunctionImporter::ImportMapTy ImportList;
812 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
813 ImportList);
814
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000815 // Conservatively mark all internal values as promoted. This interface is
816 // only used when doing importing via the function importing pass. The pass
817 // is only enabled when testing importing via the 'opt' tool, which does
818 // not do the ThinLink that would normally determine what values to promote.
819 for (auto &I : *Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000820 for (auto &S : I.second.SummaryList) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000821 if (GlobalValue::isLocalLinkage(S->linkage()))
822 S->setLinkage(GlobalValue::ExternalLinkage);
823 }
824 }
825
Teresa Johnson21241572016-07-18 21:22:24 +0000826 // Next we need to promote to global scope and rename any local values that
827 // are potentially exported to other modules.
828 if (renameModuleForThinLTO(M, *Index, nullptr)) {
829 errs() << "Error renaming module\n";
830 return false;
831 }
832
833 // Perform the import now.
834 auto ModuleLoader = [&M](StringRef Identifier) {
835 return loadFile(Identifier, M.getContext());
836 };
837 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne37e24592017-02-02 18:42:25 +0000838 Expected<bool> Result = Importer.importFunctions(M, ImportList);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000839
840 // FIXME: Probably need to propagate Errors through the pass manager.
841 if (!Result) {
842 logAllUnhandledErrors(Result.takeError(), errs(),
843 "Error importing module: ");
844 return false;
845 }
846
847 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +0000848}
849
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000850namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000851/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +0000852class FunctionImportLegacyPass : public ModulePass {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000853public:
854 /// Pass identification, replacement for typeid
855 static char ID;
856
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000857 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +0000858 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000859
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000860 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000861
862 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000863 if (skipModule(M))
864 return false;
865
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000866 return doImportingForModule(M);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000867 }
868};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000869} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000870
Teresa Johnson21241572016-07-18 21:22:24 +0000871PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000872 ModuleAnalysisManager &AM) {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000873 if (!doImportingForModule(M))
Teresa Johnson21241572016-07-18 21:22:24 +0000874 return PreservedAnalyses::all();
875
876 return PreservedAnalyses::none();
877}
878
879char FunctionImportLegacyPass::ID = 0;
880INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
881 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +0000882
883namespace llvm {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000884Pass *createFunctionImportPass() {
885 return new FunctionImportLegacyPass();
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000886}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000887}