+ // Add the function to the import list
+ auto &Entry = ModuleToFunctionsToImportMap[SrcModule.getModuleIdentifier()];
+ Entry.insert(F);
+
+ // Process the newly imported functions and add callees to the worklist.
+ F->materialize();
+ findExternalCalls(DestModule, *F, Index, CalledFunctions, Worklist);
+ }
+}
+
+// Automatically import functions in Module \p DestModule based on the summaries
+// index.
+//
+// The current implementation imports every called functions that exists in the
+// summaries index.
+bool FunctionImporter::importFunctions(Module &DestModule) {
+ DEBUG(dbgs() << "Starting import for Module "
+ << DestModule.getModuleIdentifier() << "\n");
+ unsigned ImportedCount = 0;
+
+ /// First step is collecting the called external functions.
+ StringSet<> CalledFunctions;
+ SmallVector<StringRef, 64> Worklist;
+ for (auto &F : DestModule) {
+ if (F.isDeclaration() || F.hasFnAttribute(Attribute::OptimizeNone))
+ continue;
+ findExternalCalls(DestModule, F, Index, CalledFunctions, Worklist);
+ }
+ if (Worklist.empty())
+ return false;
+
+ /// Second step: for every call to an external function, try to import it.
+
+ // Linker that will be used for importing function
+ Linker TheLinker(DestModule);
+
+ // Map of Module -> List of Function to import from the Module
+ std::map<StringRef, DenseSet<const GlobalValue *>>
+ ModuleToFunctionsToImportMap;
+
+ // Analyze the summaries and get the list of functions to import by
+ // populating ModuleToFunctionsToImportMap
+ ModuleLazyLoaderCache ModuleLoaderCache(ModuleLoader);
+ GetImportList(DestModule, Worklist, CalledFunctions,
+ ModuleToFunctionsToImportMap, Index, ModuleLoaderCache);
+ assert(Worklist.empty() && "Worklist hasn't been flushed in GetImportList");
+
+ StringMap<std::unique_ptr<DenseMap<unsigned, MDNode *>>>
+ ModuleToTempMDValsMap;
+
+ // Do the actual import of functions now, one Module at a time
+ for (auto &FunctionsToImportPerModule : ModuleToFunctionsToImportMap) {
+ // Get the module for the import
+ auto &FunctionsToImport = FunctionsToImportPerModule.second;
+ std::unique_ptr<Module> SrcModule =
+ ModuleLoaderCache.takeModule(FunctionsToImportPerModule.first);
+ assert(&DestModule.getContext() == &SrcModule->getContext() &&
+ "Context mismatch");
+
+ // Save the mapping of value ids to temporary metadata created when
+ // importing this function. If we have already imported from this module,
+ // add new temporary metadata to the existing mapping.
+ auto &TempMDVals = ModuleToTempMDValsMap[SrcModule->getModuleIdentifier()];
+ if (!TempMDVals)
+ TempMDVals = llvm::make_unique<DenseMap<unsigned, MDNode *>>();
+
+ // Link in the specified functions.
+ if (TheLinker.linkInModule(std::move(SrcModule), Linker::Flags::None,
+ &Index, &FunctionsToImport, TempMDVals.get()))