blob: 5f077a6aa4d27e88c1066eaff6506b0fd418fbce [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(
Dehao Chen8260d662017-07-28 01:02:34 +000064 "import-hot-multiplier", cl::init(10.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();
Teresa Johnson73305f82017-08-19 18:04:25 +0000132 // For SamplePGO, in computeImportForFunction the OriginalId
133 // may have been used to locate the callee summary list (See
134 // comment there).
135 // The mapping from OriginalId to GUID may return a GUID
136 // that corresponds to a static variable. Filter it out here.
137 // This can happen when
138 // 1) There is a call to a library function which is not defined
139 // in the index.
140 // 2) There is a static variable with the OriginalGUID identical
141 // to the GUID of the library function in 1);
142 // When this happens, the logic for SamplePGO kicks in and
143 // the static variable in 2) will be found, which needs to be
144 // filtered out.
145 if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
146 return false;
Rafael Espindolaf329be82016-05-11 01:26:06 +0000147 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
Mehdi Amini5b85d8d2016-05-03 00:27:28 +0000148 // There is no point in importing these, we can't inline them
Mehdi Amini01e32132016-03-26 05:40:34 +0000149 return false;
Davide Italiano82c7d372017-07-27 18:38:09 +0000150 if (isa<AliasSummary>(GVSummary))
David Blaikie2f0cc472017-07-27 15:09:06 +0000151 // Aliases can't point to "available_externally".
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000152 // FIXME: we should import alias as available_externally *function*,
David Blaikie2f0cc472017-07-27 15:09:06 +0000153 // the destination module does not need to know it is an alias.
154 return false;
Mehdi Amini2c719cc2016-04-20 04:17:36 +0000155
156 auto *Summary = cast<FunctionSummary>(GVSummary);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000157
Teresa Johnson83aaf352017-01-12 22:04:45 +0000158 // If this is a local function, make sure we import the copy
159 // in the caller's module. The only time a local function can
160 // share an entry in the index is if there is a local with the same name
161 // in another module that had the same source file name (in a different
162 // directory), where each was compiled in their own directory so there
163 // was not distinguishing path.
164 // However, do the import from another module if there is only one
165 // entry in the list - in that case this must be a reference due
166 // to indirect call profile data, since a function pointer can point to
167 // a local in another module.
168 if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
169 CalleeSummaryList.size() > 1 &&
170 Summary->modulePath() != CallerModulePath)
171 return false;
172
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000173 if (Summary->instCount() > Threshold)
174 return false;
175
Teresa Johnson519465b2017-01-05 14:32:16 +0000176 if (Summary->notEligibleToImport())
Mehdi Aminib4e1e822016-04-27 00:32:13 +0000177 return false;
178
Mehdi Amini01e32132016-03-26 05:40:34 +0000179 return true;
180 });
Teresa Johnson28e457b2016-04-24 14:57:11 +0000181 if (It == CalleeSummaryList.end())
Mehdi Amini01e32132016-03-26 05:40:34 +0000182 return nullptr;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000183
Teresa Johnsonf9dc3de2017-07-17 19:25:38 +0000184 return cast<GlobalValueSummary>(It->get());
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000185}
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000186
Teresa Johnson475b51a2016-12-15 20:48:19 +0000187using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
188 GlobalValue::GUID>;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000189
Mehdi Amini01e32132016-03-26 05:40:34 +0000190/// Compute the list of functions to import for a given caller. Mark these
191/// imported functions and the symbols they reference in their source module as
192/// exported from their source module.
193static void computeImportForFunction(
Teresa Johnson3255eec2016-04-10 15:17:26 +0000194 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000195 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000196 SmallVectorImpl<EdgeInfo> &Worklist,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000197 FunctionImporter::ImportMapTy &ImportList,
Teresa Johnsonc86af332016-04-12 21:13:11 +0000198 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000199 for (auto &Edge : Summary.calls()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000200 ValueInfo VI = Edge.first;
201 DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold
202 << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000203
Peter Collingbourne9667b912017-05-04 18:03:25 +0000204 if (VI.getSummaryList().empty()) {
Dehao Chen4a435e02017-03-14 17:33:01 +0000205 // For SamplePGO, the indirect call targets for local functions will
206 // have its original name annotated in profile. We try to find the
207 // corresponding PGOFuncName as the GUID.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000208 auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
Dehao Chen4a435e02017-03-14 17:33:01 +0000209 if (GUID == 0)
210 continue;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000211 VI = Index.getValueInfo(GUID);
212 if (!VI)
213 continue;
Dehao Chen4a435e02017-03-14 17:33:01 +0000214 }
215
Peter Collingbourne9667b912017-05-04 18:03:25 +0000216 if (DefinedGVSummaries.count(VI.getGUID())) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000217 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
218 continue;
Teresa Johnsond450da32015-11-24 21:15:19 +0000219 }
Mehdi Amini01e32132016-03-26 05:40:34 +0000220
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000221 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
222 if (Hotness == CalleeInfo::HotnessType::Hot)
223 return ImportHotMultiplier;
224 if (Hotness == CalleeInfo::HotnessType::Cold)
225 return ImportColdMultiplier;
Dehao Chen64c46572017-07-07 21:01:00 +0000226 if (Hotness == CalleeInfo::HotnessType::Critical)
227 return ImportCriticalMultiplier;
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000228 return 1.0;
229 };
230
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000231 const auto NewThreshold =
Piotr Padlewskiba72b952016-09-29 17:32:07 +0000232 Threshold * GetBonusMultiplier(Edge.second.Hotness);
Piotr Padlewskid2869472016-09-30 03:01:17 +0000233
Peter Collingbourne9667b912017-05-04 18:03:25 +0000234 auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
235 Summary.modulePath());
Mehdi Amini01e32132016-03-26 05:40:34 +0000236 if (!CalleeSummary) {
237 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
238 continue;
239 }
David Blaikie2f0cc472017-07-27 15:09:06 +0000240
241 // "Resolve" the summary
242 assert(!isa<AliasSummary>(CalleeSummary) &&
243 "Unexpected alias in import list");
244 const auto *ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000245
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000246 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
Mehdi Amini01e32132016-03-26 05:40:34 +0000247 "selectCallee() didn't honor the threshold");
248
Piotr Padlewskid2869472016-09-30 03:01:17 +0000249 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
250 // Adjust the threshold for next level of imported functions.
251 // The threshold is different for hot callsites because we can then
252 // inline chains of hot calls.
253 if (IsHotCallsite)
254 return Threshold * ImportHotInstrFactor;
255 return Threshold * ImportInstrFactor;
256 };
257
258 bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000259 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
260
261 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000262 auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
Teresa Johnson1b859a22016-12-15 18:21:01 +0000263 /// Since the traversal of the call graph is DFS, we can revisit a function
264 /// a second time with a higher threshold. In this case, it is added back to
265 /// the worklist with the new threshold.
266 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
267 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
268 << ProcessedThreshold << "\n");
269 continue;
270 }
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000271 bool PreviouslyImported = ProcessedThreshold != 0;
Teresa Johnson1b859a22016-12-15 18:21:01 +0000272 // Mark this function as imported in this module, with the current Threshold
273 ProcessedThreshold = AdjThreshold;
274
275 // Make exports in the source module.
276 if (ExportLists) {
277 auto &ExportList = (*ExportLists)[ExportModulePath];
Peter Collingbourne9667b912017-05-04 18:03:25 +0000278 ExportList.insert(VI.getGUID());
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000279 if (!PreviouslyImported) {
280 // This is the first time this function was exported from its source
281 // module, so mark all functions and globals it references as exported
282 // to the outside if they are defined in the same source module.
Teresa Johnsonedddca22016-12-16 04:11:51 +0000283 // For efficiency, we unconditionally add all the referenced GUIDs
284 // to the ExportList for this module, and will prune out any not
285 // defined in the module later in a single pass.
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000286 for (auto &Edge : ResolvedCalleeSummary->calls()) {
287 auto CalleeGUID = Edge.first.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000288 ExportList.insert(CalleeGUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000289 }
290 for (auto &Ref : ResolvedCalleeSummary->refs()) {
291 auto GUID = Ref.getGUID();
Teresa Johnsonedddca22016-12-16 04:11:51 +0000292 ExportList.insert(GUID);
Teresa Johnson19f2aa72016-12-15 23:50:06 +0000293 }
Teresa Johnson1b859a22016-12-15 18:21:01 +0000294 }
295 }
Piotr Padlewskid2869472016-09-30 03:01:17 +0000296
Mehdi Amini01e32132016-03-26 05:40:34 +0000297 // Insert the newly imported function to the worklist.
Peter Collingbourne9667b912017-05-04 18:03:25 +0000298 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
Teresa Johnsond450da32015-11-24 21:15:19 +0000299 }
300}
301
Mehdi Amini01e32132016-03-26 05:40:34 +0000302/// Given the list of globals defined in a module, compute the list of imports
303/// as well as the list of "exports", i.e. the list of symbols referenced from
304/// another module (that may require promotion).
305static void ComputeImportForModule(
Teresa Johnsonc851d212016-04-25 21:09:51 +0000306 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000307 FunctionImporter::ImportMapTy &ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000308 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000309 // Worklist contains the list of function imported in this module, for which
310 // we will analyse the callees and may import further down the callgraph.
311 SmallVector<EdgeInfo, 128> Worklist;
312
313 // Populate the worklist with the import for the functions in the current
314 // module
Teresa Johnson28e457b2016-04-24 14:57:11 +0000315 for (auto &GVSummary : DefinedGVSummaries) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000316 if (!Index.isGlobalValueLive(GVSummary.second)) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000317 DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
318 continue;
319 }
Teresa Johnson28e457b2016-04-24 14:57:11 +0000320 auto *Summary = GVSummary.second;
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000321 if (auto *AS = dyn_cast<AliasSummary>(Summary))
322 Summary = &AS->getAliasee();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000323 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
324 if (!FuncSummary)
325 // Skip import for global variables
326 continue;
Xinliang David Li24524f32017-08-11 17:49:20 +0000327 DEBUG(dbgs() << "Initialize import for " << GVSummary.first << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000328 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000329 DefinedGVSummaries, Worklist, ImportList,
Mehdi Amini01e32132016-03-26 05:40:34 +0000330 ExportLists);
331 }
332
Piotr Padlewskid2869472016-09-30 03:01:17 +0000333 // Process the newly imported functions and add callees to the worklist.
Mehdi Amini42418ab2015-11-24 06:07:49 +0000334 while (!Worklist.empty()) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000335 auto FuncInfo = Worklist.pop_back_val();
Teresa Johnson475b51a2016-12-15 20:48:19 +0000336 auto *Summary = std::get<0>(FuncInfo);
337 auto Threshold = std::get<1>(FuncInfo);
338 auto GUID = std::get<2>(FuncInfo);
339
340 // Check if we later added this summary with a higher threshold.
341 // If so, skip this entry.
342 auto ExportModulePath = Summary->modulePath();
343 auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
344 if (LatestProcessedThreshold > Threshold)
345 continue;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000346
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000347 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
Mehdi Amini9b490f12016-08-16 05:47:12 +0000348 Worklist, ImportList, ExportLists);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000349 }
Mehdi Aminic8c55172015-12-03 02:37:33 +0000350}
Mehdi Aminiffe2e4a2015-12-02 04:34:28 +0000351
Mehdi Amini01e32132016-03-26 05:40:34 +0000352} // anonymous namespace
353
Teresa Johnsonc86af332016-04-12 21:13:11 +0000354/// Compute all the import and export for every module using the Index.
Mehdi Amini01e32132016-03-26 05:40:34 +0000355void llvm::ComputeCrossModuleImport(
356 const ModuleSummaryIndex &Index,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000357 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini01e32132016-03-26 05:40:34 +0000358 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000359 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000360 // For each module that has function defined, compute the import/export lists.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000361 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Amini9b490f12016-08-16 05:47:12 +0000362 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000363 DEBUG(dbgs() << "Computing import for Module '"
364 << DefinedGVSummaries.first() << "'\n");
Mehdi Amini9b490f12016-08-16 05:47:12 +0000365 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000366 &ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000367 }
368
Teresa Johnsonedddca22016-12-16 04:11:51 +0000369 // When computing imports we added all GUIDs referenced by anything
370 // imported from the module to its ExportList. Now we prune each ExportList
371 // of any not defined in that module. This is more efficient than checking
372 // while computing imports because some of the summary lists may be long
373 // due to linkonce (comdat) copies.
374 for (auto &ELI : ExportLists) {
375 const auto &DefinedGVSummaries =
376 ModuleToDefinedGVSummaries.lookup(ELI.first());
377 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
378 if (!DefinedGVSummaries.count(*EI))
379 EI = ELI.second.erase(EI);
380 else
381 ++EI;
382 }
383 }
384
Mehdi Amini01e32132016-03-26 05:40:34 +0000385#ifndef NDEBUG
386 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
387 << " modules:\n");
388 for (auto &ModuleImports : ImportLists) {
389 auto ModName = ModuleImports.first();
390 auto &Exports = ExportLists[ModName];
391 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
392 << " functions. Imports from " << ModuleImports.second.size()
393 << " modules.\n");
394 for (auto &Src : ModuleImports.second) {
395 auto SrcModName = Src.first();
396 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
397 << SrcModName << "\n");
398 }
399 }
400#endif
401}
402
Teresa Johnsonc86af332016-04-12 21:13:11 +0000403/// Compute all the imports for the given module in the Index.
404void llvm::ComputeCrossModuleImportForModule(
405 StringRef ModulePath, const ModuleSummaryIndex &Index,
406 FunctionImporter::ImportMapTy &ImportList) {
407
408 // Collect the list of functions this module defines.
409 // GUID -> Summary
Teresa Johnsonc851d212016-04-25 21:09:51 +0000410 GVSummaryMapTy FunctionSummaryMap;
Teresa Johnson28e457b2016-04-24 14:57:11 +0000411 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000412
413 // Compute the import list for this module.
414 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
Teresa Johnson28e457b2016-04-24 14:57:11 +0000415 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
Teresa Johnsonc86af332016-04-12 21:13:11 +0000416
417#ifndef NDEBUG
418 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
419 << ImportList.size() << " modules.\n");
420 for (auto &Src : ImportList) {
421 auto SrcModName = Src.first();
422 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
423 << SrcModName << "\n");
424 }
425#endif
426}
427
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000428void llvm::computeDeadSymbols(
429 ModuleSummaryIndex &Index,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000430 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000431 assert(!Index.withGlobalValueDeadStripping());
Teresa Johnson6c475a72017-01-05 21:34:18 +0000432 if (!ComputeDead)
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000433 return;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000434 if (GUIDPreservedSymbols.empty())
435 // Don't do anything when nothing is live, this is friendly with tests.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000436 return;
437 unsigned LiveSymbols = 0;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000438 SmallVector<ValueInfo, 128> Worklist;
439 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
440 for (auto GUID : GUIDPreservedSymbols) {
441 ValueInfo VI = Index.getValueInfo(GUID);
442 if (!VI)
443 continue;
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000444 for (auto &S : VI.getSummaryList())
445 S->setLive(true);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000446 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000447
Teresa Johnson6c475a72017-01-05 21:34:18 +0000448 // Add values flagged in the index as live roots to the worklist.
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000449 for (const auto &Entry : Index)
450 for (auto &S : Entry.second.SummaryList)
451 if (S->isLive()) {
452 DEBUG(dbgs() << "Live root: " << Entry.first << "\n");
453 Worklist.push_back(ValueInfo(&Entry));
454 ++LiveSymbols;
455 break;
456 }
457
458 // Make value live and add it to the worklist if it was not live before.
459 // FIXME: we should only make the prevailing copy live here
460 auto visit = [&](ValueInfo VI) {
461 for (auto &S : VI.getSummaryList())
462 if (S->isLive())
463 return;
464 for (auto &S : VI.getSummaryList())
465 S->setLive(true);
466 ++LiveSymbols;
467 Worklist.push_back(VI);
468 };
Teresa Johnson6c475a72017-01-05 21:34:18 +0000469
470 while (!Worklist.empty()) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000471 auto VI = Worklist.pop_back_val();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000472 for (auto &Summary : VI.getSummaryList()) {
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000473 for (auto Ref : Summary->refs())
474 visit(Ref);
475 if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
476 for (auto Call : FS->calls())
477 visit(Call.first);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000478 if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
479 auto AliaseeGUID = AS->getAliasee().getOriginalName();
Peter Collingbourne9667b912017-05-04 18:03:25 +0000480 ValueInfo AliaseeVI = Index.getValueInfo(AliaseeGUID);
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000481 if (AliaseeVI)
482 visit(AliaseeVI);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000483 }
484 }
485 }
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000486 Index.setWithGlobalValueDeadStripping();
487
488 unsigned DeadSymbols = Index.size() - LiveSymbols;
489 DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
490 << " symbols Dead \n");
491 NumDeadSymbols += DeadSymbols;
492 NumLiveSymbols += LiveSymbols;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000493}
494
Teresa Johnson84174c32016-05-10 13:48:23 +0000495/// Compute the set of summaries needed for a ThinLTO backend compilation of
496/// \p ModulePath.
497void llvm::gatherImportedSummariesForModule(
498 StringRef ModulePath,
499 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000500 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson84174c32016-05-10 13:48:23 +0000501 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
502 // Include all summaries from the importing module.
503 ModuleToSummariesForIndex[ModulePath] =
504 ModuleToDefinedGVSummaries.lookup(ModulePath);
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000505 // Include summaries for imports.
Mehdi Amini88c491d2016-08-16 05:49:12 +0000506 for (auto &ILI : ImportList) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000507 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
508 const auto &DefinedGVSummaries =
509 ModuleToDefinedGVSummaries.lookup(ILI.first());
510 for (auto &GI : ILI.second) {
511 const auto &DS = DefinedGVSummaries.find(GI.first);
512 assert(DS != DefinedGVSummaries.end() &&
513 "Expected a defined summary for imported global value");
514 SummariesForIndex[GI.first] = DS->second;
Teresa Johnson84174c32016-05-10 13:48:23 +0000515 }
516 }
517}
518
Teresa Johnson8570fe42016-05-10 15:54:09 +0000519/// Emit the files \p ModulePath will import from into \p OutputFilename.
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000520std::error_code
521llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
522 const FunctionImporter::ImportMapTy &ModuleImports) {
Teresa Johnson8570fe42016-05-10 15:54:09 +0000523 std::error_code EC;
524 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
525 if (EC)
526 return EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000527 for (auto &ILI : ModuleImports)
528 ImportsOS << ILI.first() << "\n";
Teresa Johnson8570fe42016-05-10 15:54:09 +0000529 return std::error_code();
530}
531
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000532/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
533void llvm::thinLTOResolveWeakForLinkerModule(
534 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000535 auto ConvertToDeclaration = [](GlobalValue &GV) {
536 DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
537 if (Function *F = dyn_cast<Function>(&GV)) {
538 F->deleteBody();
539 F->clearMetadata();
540 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
541 V->setInitializer(nullptr);
542 V->setLinkage(GlobalValue::ExternalLinkage);
543 V->clearMetadata();
544 } else
545 // For now we don't resolve or drop aliases. Once we do we'll
546 // need to add support here for creating either a function or
547 // variable declaration, and return the new GlobalValue* for
548 // the caller to use.
Davide Italiano91239082017-04-14 17:22:02 +0000549 llvm_unreachable("Expected function or variable");
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000550 };
551
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000552 auto updateLinkage = [&](GlobalValue &GV) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000553 // See if the global summary analysis computed a new resolved linkage.
554 const auto &GS = DefinedGlobals.find(GV.getGUID());
555 if (GS == DefinedGlobals.end())
556 return;
557 auto NewLinkage = GS->second->linkage();
558 if (NewLinkage == GV.getLinkage())
559 return;
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000560
561 // Switch the linkage to weakany if asked for, e.g. we do this for
562 // linker redefined symbols (via --wrap or --defsym).
Davide Italianof4891d22017-07-06 20:04:20 +0000563 // We record that the visibility should be changed here in `addThinLTO`
564 // as we need access to the resolution vectors for each input file in
565 // order to find which symbols have been redefined.
566 // We may consider reorganizing this code and moving the linkage recording
567 // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex.
Davide Italiano6a5fbe52017-07-06 19:58:26 +0000568 if (NewLinkage == GlobalValue::WeakAnyLinkage) {
569 GV.setLinkage(NewLinkage);
570 return;
571 }
572
573 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
574 return;
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000575 // Check for a non-prevailing def that has interposable linkage
576 // (e.g. non-odr weak or linkonce). In that case we can't simply
577 // convert to available_externally, since it would lose the
578 // interposable property and possibly get inlined. Simply drop
579 // the definition in that case.
580 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
581 GlobalValue::isInterposableLinkage(GV.getLinkage()))
582 ConvertToDeclaration(GV);
583 else {
584 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
585 << GV.getLinkage() << " to " << NewLinkage << "\n");
586 GV.setLinkage(NewLinkage);
587 }
588 // Remove declarations from comdats, including available_externally
Teresa Johnson6107a412016-08-15 21:00:04 +0000589 // as this is a declaration for the linker, and will be dropped eventually.
590 // It is illegal for comdats to contain declarations.
591 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000592 if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
Teresa Johnson6107a412016-08-15 21:00:04 +0000593 GO->setComdat(nullptr);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000594 };
595
596 // Process functions and global now
597 for (auto &GV : TheModule)
598 updateLinkage(GV);
599 for (auto &GV : TheModule.globals())
600 updateLinkage(GV);
601 for (auto &GV : TheModule.aliases())
602 updateLinkage(GV);
603}
604
605/// Run internalization on \p TheModule based on symmary analysis.
606void llvm::thinLTOInternalizeModule(Module &TheModule,
607 const GVSummaryMapTy &DefinedGlobals) {
608 // Parse inline ASM and collect the list of symbols that are not defined in
609 // the current module.
610 StringSet<> AsmUndefinedRefs;
Peter Collingbourne863cbfb2016-12-01 06:51:47 +0000611 ModuleSymbolTable::CollectAsmSymbols(
Teresa Johnsond8204472017-03-09 00:19:49 +0000612 TheModule,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000613 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
614 if (Flags & object::BasicSymbolRef::SF_Undefined)
615 AsmUndefinedRefs.insert(Name);
616 });
617
618 // Declare a callback for the internalize pass that will ask for every
619 // candidate GlobalValue if it can be internalized or not.
620 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
621 // Can't be internalized if referenced in inline asm.
622 if (AsmUndefinedRefs.count(GV.getName()))
623 return true;
624
625 // Lookup the linkage recorded in the summaries during global analysis.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000626 auto GS = DefinedGlobals.find(GV.getGUID());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000627 if (GS == DefinedGlobals.end()) {
628 // Must have been promoted (possibly conservatively). Find original
629 // name so that we can access the correct summary and see if it can
630 // be internalized again.
631 // FIXME: Eventually we should control promotion instead of promoting
632 // and internalizing again.
633 StringRef OrigName =
634 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
635 std::string OrigId = GlobalValue::getGlobalIdentifier(
636 OrigName, GlobalValue::InternalLinkage,
637 TheModule.getSourceFileName());
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000638 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000639 if (GS == DefinedGlobals.end()) {
640 // Also check the original non-promoted non-globalized name. In some
641 // cases a preempted weak value is linked in as a local copy because
642 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
643 // In that case, since it was originally not a local value, it was
644 // recorded in the index using the original name.
645 // FIXME: This may not be needed once PR27866 is fixed.
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000646 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000647 assert(GS != DefinedGlobals.end());
Teresa Johnson7ab1f692016-06-09 01:14:13 +0000648 }
Peter Collingbournec3d677f2017-05-09 22:43:31 +0000649 }
650 return !GlobalValue::isLocalLinkage(GS->second->linkage());
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000651 };
652
653 // FIXME: See if we can just internalize directly here via linkage changes
654 // based on the index, rather than invoking internalizeModule.
655 llvm::internalizeModule(TheModule, MustPreserveGV);
656}
657
Mehdi Aminic8c55172015-12-03 02:37:33 +0000658// Automatically import functions in Module \p DestModule based on the summaries
659// index.
660//
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000661Expected<bool> FunctionImporter::importFunctions(
Adrian Prantl66043792017-05-19 23:32:21 +0000662 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini5411d052015-12-08 23:04:19 +0000663 DEBUG(dbgs() << "Starting import for Module "
Mehdi Amini311fef62015-12-03 02:58:14 +0000664 << DestModule.getModuleIdentifier() << "\n");
Mehdi Aminic8c55172015-12-03 02:37:33 +0000665 unsigned ImportedCount = 0;
666
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000667 IRMover Mover(DestModule);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000668 // Do the actual import of functions now, one Module at a time
Mehdi Amini01e32132016-03-26 05:40:34 +0000669 std::set<StringRef> ModuleNameOrderedList;
670 for (auto &FunctionsToImportPerModule : ImportList) {
671 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
672 }
673 for (auto &Name : ModuleNameOrderedList) {
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000674 // Get the module for the import
Mehdi Amini01e32132016-03-26 05:40:34 +0000675 const auto &FunctionsToImportPerModule = ImportList.find(Name);
676 assert(FunctionsToImportPerModule != ImportList.end());
Peter Collingbourned9445c42016-11-13 07:00:17 +0000677 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
678 if (!SrcModuleOrErr)
679 return SrcModuleOrErr.takeError();
680 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000681 assert(&DestModule.getContext() == &SrcModule->getContext() &&
682 "Context mismatch");
683
Teresa Johnson6cba37c2016-01-22 00:15:53 +0000684 // If modules were created with lazy metadata loading, materialize it
685 // now, before linking it (otherwise this will be a noop).
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000686 if (Error Err = SrcModule->materializeMetadata())
687 return std::move(Err);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000688
Mehdi Amini01e32132016-03-26 05:40:34 +0000689 auto &ImportGUIDs = FunctionsToImportPerModule->second;
690 // Find the globals to import
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000691 SetVector<GlobalValue *> GlobalsToImport;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000692 for (Function &F : *SrcModule) {
693 if (!F.hasName())
Teresa Johnson0beb8582016-04-04 18:52:23 +0000694 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000695 auto GUID = F.getGUID();
Teresa Johnson0beb8582016-04-04 18:52:23 +0000696 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000697 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000698 << " " << F.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000699 << SrcModule->getSourceFileName() << "\n");
Teresa Johnson0beb8582016-04-04 18:52:23 +0000700 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000701 if (Error Err = F.materialize())
702 return std::move(Err);
Piotr Padlewski3b776122016-07-08 23:01:49 +0000703 if (EnableImportMetadata) {
704 // Add 'thinlto_src_module' metadata for statistics and debugging.
705 F.setMetadata(
706 "thinlto_src_module",
707 llvm::MDNode::get(
708 DestModule.getContext(),
709 {llvm::MDString::get(DestModule.getContext(),
710 SrcModule->getSourceFileName())}));
711 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000712 GlobalsToImport.insert(&F);
Mehdi Amini01e32132016-03-26 05:40:34 +0000713 }
714 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000715 for (GlobalVariable &GV : SrcModule->globals()) {
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000716 if (!GV.hasName())
717 continue;
718 auto GUID = GV.getGUID();
719 auto Import = ImportGUIDs.count(GUID);
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000720 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
721 << " " << GV.getName() << " from "
722 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000723 if (Import) {
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000724 if (Error Err = GV.materialize())
725 return std::move(Err);
Mehdi Amini2d28f7a2016-04-16 06:56:44 +0000726 GlobalsToImport.insert(&GV);
727 }
728 }
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000729 for (GlobalAlias &GA : SrcModule->aliases()) {
730 if (!GA.hasName())
Mehdi Amini01e32132016-03-26 05:40:34 +0000731 continue;
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000732 auto GUID = GA.getGUID();
Teresa Johnson2df7fc72017-08-29 18:15:34 +0000733 assert(!ImportGUIDs.count(GUID) && "Unexpected alias in import list");
734 DEBUG(dbgs() << "Not importing alias " << GUID
Piotr Padlewski1f685e02016-07-06 18:12:23 +0000735 << " " << GA.getName() << " from "
Mehdi Aminiaeb1e592016-04-19 09:21:30 +0000736 << SrcModule->getSourceFileName() << "\n");
Mehdi Amini01e32132016-03-26 05:40:34 +0000737 }
738
Mehdi Amini19ef4fa2017-01-04 22:54:33 +0000739 // Upgrade debug info after we're done materializing all the globals and we
740 // have loaded all the required metadata!
741 UpgradeDebugInfo(*SrcModule);
742
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000743 // Link in the specified functions.
Mehdi Amini01e32132016-03-26 05:40:34 +0000744 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
Mehdi Amini8d051852016-03-19 00:40:31 +0000745 return true;
746
Teresa Johnsond29478f2016-03-27 15:27:30 +0000747 if (PrintImports) {
748 for (const auto *GV : GlobalsToImport)
749 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
750 << " from " << SrcModule->getSourceFileName() << "\n";
751 }
752
Peter Collingbourne6d8f8172017-02-03 16:56:27 +0000753 if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
754 [](GlobalValue &, IRMover::ValueAdder) {},
Peter Collingbournee6fd9ff2017-02-03 17:01:14 +0000755 /*IsPerformingImport=*/true))
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000756 report_fatal_error("Function Import: link error");
757
Mehdi Amini01e32132016-03-26 05:40:34 +0000758 ImportedCount += GlobalsToImport.size();
Teresa Johnson6c475a72017-01-05 21:34:18 +0000759 NumImportedModules++;
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000760 }
Teresa Johnsone5a61912015-12-17 17:14:09 +0000761
Teresa Johnson6c475a72017-01-05 21:34:18 +0000762 NumImportedFunctions += ImportedCount;
Teresa Johnsond29478f2016-03-27 15:27:30 +0000763
Mehdi Amini7e88d0d2015-12-09 08:17:35 +0000764 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
Mehdi Aminic8c55172015-12-03 02:37:33 +0000765 << DestModule.getModuleIdentifier() << "\n");
766 return ImportedCount;
Mehdi Amini42418ab2015-11-24 06:07:49 +0000767}
768
769/// Summary file to use for function importing when using -function-import from
770/// the command line.
771static cl::opt<std::string>
772 SummaryFile("summary-file",
773 cl::desc("The summary file to use for function importing."));
774
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000775static bool doImportingForModule(Module &M) {
776 if (SummaryFile.empty())
777 report_fatal_error("error: -function-import requires -summary-file\n");
778 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
779 getModuleSummaryIndexForFile(SummaryFile);
780 if (!IndexPtrOrErr) {
781 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
782 "Error loading file '" + SummaryFile + "': ");
783 return false;
Teresa Johnson21241572016-07-18 21:22:24 +0000784 }
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000785 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
Teresa Johnson21241572016-07-18 21:22:24 +0000786
787 // First step is collecting the import list.
788 FunctionImporter::ImportMapTy ImportList;
789 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
790 ImportList);
791
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000792 // Conservatively mark all internal values as promoted. This interface is
793 // only used when doing importing via the function importing pass. The pass
794 // is only enabled when testing importing via the 'opt' tool, which does
795 // not do the ThinLink that would normally determine what values to promote.
796 for (auto &I : *Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000797 for (auto &S : I.second.SummaryList) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000798 if (GlobalValue::isLocalLinkage(S->linkage()))
799 S->setLinkage(GlobalValue::ExternalLinkage);
800 }
801 }
802
Teresa Johnson21241572016-07-18 21:22:24 +0000803 // Next we need to promote to global scope and rename any local values that
804 // are potentially exported to other modules.
805 if (renameModuleForThinLTO(M, *Index, nullptr)) {
806 errs() << "Error renaming module\n";
807 return false;
808 }
809
810 // Perform the import now.
811 auto ModuleLoader = [&M](StringRef Identifier) {
812 return loadFile(Identifier, M.getContext());
813 };
814 FunctionImporter Importer(*Index, ModuleLoader);
Peter Collingbourne37e24592017-02-02 18:42:25 +0000815 Expected<bool> Result = Importer.importFunctions(M, ImportList);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000816
817 // FIXME: Probably need to propagate Errors through the pass manager.
818 if (!Result) {
819 logAllUnhandledErrors(Result.takeError(), errs(),
820 "Error importing module: ");
821 return false;
822 }
823
824 return *Result;
Teresa Johnson21241572016-07-18 21:22:24 +0000825}
826
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000827namespace {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000828/// Pass that performs cross-module function import provided a summary file.
Teresa Johnson21241572016-07-18 21:22:24 +0000829class FunctionImportLegacyPass : public ModulePass {
Mehdi Amini42418ab2015-11-24 06:07:49 +0000830public:
831 /// Pass identification, replacement for typeid
832 static char ID;
833
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000834 /// Specify pass name for debug output
Mehdi Amini117296c2016-10-01 02:56:57 +0000835 StringRef getPassName() const override { return "Function Importing"; }
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000836
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000837 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000838
839 bool runOnModule(Module &M) override {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000840 if (skipModule(M))
841 return false;
842
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000843 return doImportingForModule(M);
Mehdi Amini42418ab2015-11-24 06:07:49 +0000844 }
845};
Benjamin Kramerfe2b5412015-12-24 10:03:35 +0000846} // anonymous namespace
Mehdi Amini42418ab2015-11-24 06:07:49 +0000847
Teresa Johnson21241572016-07-18 21:22:24 +0000848PreservedAnalyses FunctionImportPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000849 ModuleAnalysisManager &AM) {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000850 if (!doImportingForModule(M))
Teresa Johnson21241572016-07-18 21:22:24 +0000851 return PreservedAnalyses::all();
852
853 return PreservedAnalyses::none();
854}
855
856char FunctionImportLegacyPass::ID = 0;
857INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
858 "Summary Based Function Import", false, false)
Mehdi Amini42418ab2015-11-24 06:07:49 +0000859
860namespace llvm {
Peter Collingbourne598bd2a2016-12-21 00:50:12 +0000861Pass *createFunctionImportPass() {
862 return new FunctionImportLegacyPass();
Teresa Johnson5fcbdb72015-12-07 19:21:11 +0000863}
Mehdi Amini42418ab2015-11-24 06:07:49 +0000864}