blob: fdb54ee3eb832ad379d3661b31633a76628516e2 [file] [log] [blame]
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001//===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===//
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 the Thin Link Time Optimization library. This library is
11// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Peter Collingbourne5c732202016-07-14 21:21:16 +000015#include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000016
Mehdi Aminif95f77a2016-04-21 05:54:23 +000017#ifdef HAVE_LLVM_REVISION
18#include "LLVMLTORevision.h"
19#endif
Mehdi Amini059464f2016-04-24 03:18:01 +000020
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000021#include "llvm/ADT/Statistic.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000022#include "llvm/ADT/StringExtras.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000023#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000024#include "llvm/Analysis/ProfileSummaryInfo.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000025#include "llvm/Analysis/TargetLibraryInfo.h"
26#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000027#include "llvm/Bitcode/BitcodeReader.h"
28#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000029#include "llvm/Bitcode/BitcodeWriterPass.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000030#include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000031#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000032#include "llvm/IR/LLVMContext.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000033#include "llvm/IR/LegacyPassManager.h"
34#include "llvm/IR/Mangler.h"
35#include "llvm/IRReader/IRReader.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000036#include "llvm/LTO/LTO.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000037#include "llvm/Linker/Linker.h"
38#include "llvm/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000039#include "llvm/Object/IRObjectFile.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000040#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000041#include "llvm/Support/CachePruning.h"
42#include "llvm/Support/Debug.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000043#include "llvm/Support/Error.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000044#include "llvm/Support/Path.h"
45#include "llvm/Support/SHA1.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000046#include "llvm/Support/TargetRegistry.h"
47#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000048#include "llvm/Support/Threading.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000049#include "llvm/Support/ToolOutputFile.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000050#include "llvm/Target/TargetMachine.h"
51#include "llvm/Transforms/IPO.h"
52#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000053#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000054#include "llvm/Transforms/IPO/PassManagerBuilder.h"
55#include "llvm/Transforms/ObjCARC.h"
56#include "llvm/Transforms/Utils/FunctionImportUtils.h"
57
Mehdi Amini819e9cd2016-05-16 19:33:07 +000058#include <numeric>
59
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000060using namespace llvm;
61
Mehdi Amini1aafabf2016-04-16 07:02:16 +000062#define DEBUG_TYPE "thinlto"
63
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000064namespace llvm {
65// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
66extern cl::opt<bool> LTODiscardValueNames;
Mehdi Amini19f176b2016-11-19 18:20:05 +000067extern cl::opt<std::string> LTORemarksFilename;
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000068}
69
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000070namespace {
71
Teresa Johnsonec544c52016-10-19 17:35:01 +000072static cl::opt<int>
73 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000074
Mehdi Amini19f176b2016-11-19 18:20:05 +000075Expected<std::unique_ptr<tool_output_file>>
76setupOptimizationRemarks(LLVMContext &Ctx, int Count) {
77 if (LTORemarksFilename.empty())
78 return nullptr;
79
80 std::string FileName =
81 LTORemarksFilename + ".thin." + llvm::utostr(Count) + ".yaml";
82 std::error_code EC;
83 auto DiagnosticOutputFile =
84 llvm::make_unique<tool_output_file>(FileName, EC, sys::fs::F_None);
85 if (EC)
86 return errorCodeToError(EC);
87 Ctx.setDiagnosticsOutputFile(
88 llvm::make_unique<yaml::Output>(DiagnosticOutputFile->os()));
89 DiagnosticOutputFile->keep();
90 return std::move(DiagnosticOutputFile);
91}
92
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000093// Simple helper to save temporary files for debug.
94static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
95 unsigned count, StringRef Suffix) {
96 if (TempDir.empty())
97 return;
98 // User asked to save temps, let dump the bitcode file after import.
Teresa Johnsonc44a1222016-08-15 23:24:57 +000099 std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000100 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000101 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000102 if (EC)
103 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
104 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +0000105 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000106}
107
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000108static const GlobalValueSummary *
109getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
110 // If there is any strong definition anywhere, get it.
111 auto StrongDefForLinker = llvm::find_if(
112 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
113 auto Linkage = Summary->linkage();
114 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
115 !GlobalValue::isWeakForLinker(Linkage);
116 });
117 if (StrongDefForLinker != GVSummaryList.end())
118 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000119 // Get the first *linker visible* definition for this global in the summary
120 // list.
121 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000122 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
123 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000124 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
125 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000126 // Extern templates can be emitted as available_externally.
127 if (FirstDefForLinker == GVSummaryList.end())
128 return nullptr;
129 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000130}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000131
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000132// Populate map of GUID to the prevailing copy for any multiply defined
133// symbols. Currently assume first copy is prevailing, or any strong
134// definition. Can be refined with Linker information in the future.
135static void computePrevailingCopies(
136 const ModuleSummaryIndex &Index,
137 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000138 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
139 return GVSummaryList.size() > 1;
140 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000141
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000142 for (auto &I : Index) {
143 if (HasMultipleCopies(I.second))
144 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000145 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000146}
147
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000148static StringMap<MemoryBufferRef>
149generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
150 StringMap<MemoryBufferRef> ModuleMap;
151 for (auto &ModuleBuffer : Modules) {
152 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
153 ModuleMap.end() &&
154 "Expect unique Buffer Identifier");
155 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
156 }
157 return ModuleMap;
158}
159
Teresa Johnson26ab5772016-03-15 00:04:37 +0000160static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000161 if (renameModuleForThinLTO(TheModule, Index))
162 report_fatal_error("renameModuleForThinLTO failed");
163}
164
Mehdi Amini01e32132016-03-26 05:40:34 +0000165static void
166crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
167 StringMap<MemoryBufferRef> &ModuleMap,
168 const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000169 ModuleLoader Loader(TheModule.getContext(), ModuleMap);
170 FunctionImporter Importer(Index, Loader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000171 if (!Importer.importFunctions(TheModule, ImportList))
172 report_fatal_error("importFunctions failed");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000173}
174
175static void optimizeModule(Module &TheModule, TargetMachine &TM) {
176 // Populate the PassManager
177 PassManagerBuilder PMB;
178 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
179 PMB.Inliner = createFunctionInliningPass();
180 // FIXME: should get it from the bitcode?
181 PMB.OptLevel = 3;
182 PMB.LoopVectorize = true;
183 PMB.SLPVectorize = true;
184 PMB.VerifyInput = true;
185 PMB.VerifyOutput = false;
186
187 legacy::PassManager PM;
188
189 // Add the TTI (required to inform the vectorizer about register size for
190 // instance)
191 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
192
193 // Add optimizations
194 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000195
196 PM.run(TheModule);
197}
198
Mehdi Amini059464f2016-04-24 03:18:01 +0000199// Convert the PreservedSymbols map from "Name" based to "GUID" based.
200static DenseSet<GlobalValue::GUID>
201computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
202 const Triple &TheTriple) {
203 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
204 for (auto &Entry : PreservedSymbols) {
205 StringRef Name = Entry.first();
206 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
207 Name = Name.drop_front();
208 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
209 }
210 return GUIDPreservedSymbols;
211}
212
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000213std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
214 TargetMachine &TM) {
215 SmallVector<char, 128> OutputBuffer;
216
217 // CodeGen
218 {
219 raw_svector_ostream OS(OutputBuffer);
220 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000221
222 // If the bitcode files contain ARC code and were compiled with optimization,
223 // the ObjCARCContractPass must be run, so do it unconditionally here.
224 PM.add(createObjCARCContractPass());
225
226 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000227 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
228 /* DisableVerify */ true))
229 report_fatal_error("Failed to setup codegen");
230
231 // Run codegen now. resulting binary is in OutputBuffer.
232 PM.run(TheModule);
233 }
234 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
235}
236
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000237/// Manage caching for a single Module.
238class ModuleCacheEntry {
239 SmallString<128> EntryPath;
240
241public:
242 // Create a cache entry. This compute a unique hash for the Module considering
243 // the current list of export/import, and offer an interface to query to
244 // access the content in the cache.
245 ModuleCacheEntry(
246 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
247 const FunctionImporter::ImportMapTy &ImportList,
248 const FunctionImporter::ExportSetTy &ExportList,
249 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000250 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000251 const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
252 if (CachePath.empty())
253 return;
254
Mehdi Amini00fa1402016-10-08 04:44:18 +0000255 if (!Index.modulePaths().count(ModuleID))
256 // The module does not have an entry, it can't have a hash at all
257 return;
258
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000259 // Compute the unique hash for this entry
260 // This is based on the current compiler version, the module itself, the
261 // export list, the hash for every single module in the import list, the
262 // list of ResolvedODR for the module, and the list of preserved symbols.
263
Mehdi Aminif82bda02016-10-08 04:44:23 +0000264 // Include the hash for the current module
265 auto ModHash = Index.getModuleHash(ModuleID);
266
267 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
268 // No hash entry, no caching!
269 return;
270
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000271 SHA1 Hasher;
272
273 // Start with the compiler revision
274 Hasher.update(LLVM_VERSION_STRING);
275#ifdef HAVE_LLVM_REVISION
276 Hasher.update(LLVM_REVISION);
277#endif
278
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000279 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
280 for (auto F : ExportList)
281 // The export list can impact the internalization, be conservative here
282 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
283
284 // Include the hash for every module we import functions from
285 for (auto &Entry : ImportList) {
286 auto ModHash = Index.getModuleHash(Entry.first());
287 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
288 }
289
290 // Include the hash for the resolved ODR.
291 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000292 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000293 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000294 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000295 sizeof(GlobalValue::LinkageTypes)));
296 }
297
298 // Include the hash for the preserved symbols.
299 for (auto &Entry : PreservedSymbols) {
300 if (DefinedFunctions.count(Entry))
301 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000302 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000303 }
304
305 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
306 }
307
Mehdi Amini059464f2016-04-24 03:18:01 +0000308 // Access the path to this entry in the cache.
309 StringRef getEntryPath() { return EntryPath; }
310
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000311 // Try loading the buffer for this cache entry.
312 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
313 if (EntryPath.empty())
314 return std::error_code();
315 return MemoryBuffer::getFile(EntryPath);
316 }
317
318 // Cache the Produced object file
Mehdi Amini001bb412016-05-16 19:11:59 +0000319 std::unique_ptr<MemoryBuffer>
320 write(std::unique_ptr<MemoryBuffer> OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000321 if (EntryPath.empty())
Mehdi Amini001bb412016-05-16 19:11:59 +0000322 return OutputBuffer;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000323
324 // Write to a temporary to avoid race condition
325 SmallString<128> TempFilename;
326 int TempFD;
327 std::error_code EC =
328 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
329 if (EC) {
330 errs() << "Error: " << EC.message() << "\n";
331 report_fatal_error("ThinLTO: Can't get a temporary file");
332 }
333 {
334 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini001bb412016-05-16 19:11:59 +0000335 OS << OutputBuffer->getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000336 }
337 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000338 EC = sys::fs::rename(TempFilename, EntryPath);
339 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000340 sys::fs::remove(TempFilename);
341 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
342 if (EC)
343 report_fatal_error(Twine("Failed to open ") + EntryPath +
344 " to save cached entry\n");
Mehdi Amini001bb412016-05-16 19:11:59 +0000345 OS << OutputBuffer->getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000346 }
Mehdi Amini001bb412016-05-16 19:11:59 +0000347 auto ReloadedBufferOrErr = MemoryBuffer::getFile(EntryPath);
348 if (auto EC = ReloadedBufferOrErr.getError()) {
349 // FIXME diagnose
350 errs() << "error: can't reload cached file '" << EntryPath
351 << "': " << EC.message() << "\n";
352 return OutputBuffer;
353 }
354 return std::move(*ReloadedBufferOrErr);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000355 }
356};
357
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000358static std::unique_ptr<MemoryBuffer>
359ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
360 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
361 const FunctionImporter::ImportMapTy &ImportList,
362 const FunctionImporter::ExportSetTy &ExportList,
363 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
364 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000365 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000366 bool DisableCodeGen, StringRef SaveTempsDir,
367 unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000368
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000369 // "Benchmark"-like optimization: single-source case
370 bool SingleModule = (ModuleMap.size() == 1);
371
372 if (!SingleModule) {
373 promoteModule(TheModule, Index);
374
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000375 // Apply summary-based LinkOnce/Weak resolution decisions.
376 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000377
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000378 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000379 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000380 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000381
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000382 // Be friendly and don't nuke totally the module when the client didn't
383 // supply anything to preserve.
384 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
385 // Apply summary-based internalization decisions.
386 thinLTOInternalizeModule(TheModule, DefinedGlobals);
387 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000388
389 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000390 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000391
392 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000393 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000394
395 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000396 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000397 }
398
399 optimizeModule(TheModule, TM);
400
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000401 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000402
Mehdi Amini43b657b2016-04-01 06:47:02 +0000403 if (DisableCodeGen) {
404 // Configured to stop before CodeGen, serialize the bitcode and return.
405 SmallVector<char, 128> OutputBuffer;
406 {
407 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000408 ProfileSummaryInfo PSI(TheModule);
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000409 auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000410 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000411 }
412 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
413 }
414
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000415 return codegenModule(TheModule, TM);
416}
417
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000418/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
419/// for caching, and in the \p Index for application during the ThinLTO
420/// backends. This is needed for correctness for exported symbols (ensure
421/// at least one copy kept) and a compile-time optimization (to drop duplicate
422/// copies when possible).
423static void resolveWeakForLinkerInIndex(
424 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000425 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
426 &ResolvedODR) {
427
428 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
429 computePrevailingCopies(Index, PrevailingCopy);
430
431 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
432 const auto &Prevailing = PrevailingCopy.find(GUID);
433 // Not in map means that there was only one copy, which must be prevailing.
434 if (Prevailing == PrevailingCopy.end())
435 return true;
436 return Prevailing->second == S;
437 };
438
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000439 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
440 GlobalValue::GUID GUID,
441 GlobalValue::LinkageTypes NewLinkage) {
442 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
443 };
444
Peter Collingbourne73589f32016-07-07 18:31:51 +0000445 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000446}
447
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000448// Initialize the TargetMachine builder for a given Triple
449static void initTMBuilder(TargetMachineBuilder &TMBuilder,
450 const Triple &TheTriple) {
451 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
452 // FIXME this looks pretty terrible...
453 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
454 if (TheTriple.getArch() == llvm::Triple::x86_64)
455 TMBuilder.MCpu = "core2";
456 else if (TheTriple.getArch() == llvm::Triple::x86)
457 TMBuilder.MCpu = "yonah";
458 else if (TheTriple.getArch() == llvm::Triple::aarch64)
459 TMBuilder.MCpu = "cyclone";
460 }
461 TMBuilder.TheTriple = std::move(TheTriple);
462}
463
464} // end anonymous namespace
465
466void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
467 MemoryBufferRef Buffer(Data, Identifier);
468 if (Modules.empty()) {
469 // First module added, so initialize the triple and some options
470 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000471 StringRef TripleStr;
472 ErrorOr<std::string> TripleOrErr =
473 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
474 if (TripleOrErr)
475 TripleStr = *TripleOrErr;
476 Triple TheTriple(TripleStr);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000477 initTMBuilder(TMBuilder, Triple(TheTriple));
478 }
479#ifndef NDEBUG
480 else {
481 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000482 StringRef TripleStr;
483 ErrorOr<std::string> TripleOrErr =
484 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
485 if (TripleOrErr)
486 TripleStr = *TripleOrErr;
487 assert(TMBuilder.TheTriple.str() == TripleStr &&
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000488 "ThinLTO modules with different triple not supported");
489 }
490#endif
491 Modules.push_back(Buffer);
492}
493
494void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
495 PreservedSymbols.insert(Name);
496}
497
498void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000499 // FIXME: At the moment, we don't take advantage of this extra information,
500 // we're conservatively considering cross-references as preserved.
501 // CrossReferencedSymbols.insert(Name);
502 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000503}
504
505// TargetMachine factory
506std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
507 std::string ErrMsg;
508 const Target *TheTarget =
509 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
510 if (!TheTarget) {
511 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
512 }
513
514 // Use MAttr as the default set of features.
515 SubtargetFeatures Features(MAttr);
516 Features.getDefaultSubtargetFeatures(TheTriple);
517 std::string FeatureStr = Features.getString();
518 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
519 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
520 CodeModel::Default, CGOptLevel));
521}
522
523/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000524 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000525 * "thin-link".
526 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000527std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
528 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000529 uint64_t NextModuleId = 0;
530 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000531 Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
532 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer);
533 if (!ObjOrErr) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000534 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000535 logAllUnhandledErrors(
536 ObjOrErr.takeError(), errs(),
537 "error: can't create ModuleSummaryIndexObjectFile for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000538 return nullptr;
539 }
540 auto Index = (*ObjOrErr)->takeIndex();
541 if (CombinedIndex) {
542 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
543 } else {
544 CombinedIndex = std::move(Index);
545 }
546 }
547 return CombinedIndex;
548}
549
550/**
551 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000552 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000553 */
554void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000555 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000556 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000557 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000558
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000559 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000560 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000561 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000562
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000563 // Generate import/export list
564 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
565 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
566 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
567 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000568
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000569 // Resolve LinkOnce/Weak symbols.
570 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000571 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000572
573 thinLTOResolveWeakForLinkerModule(
574 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000575
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000576 // Convert the preserved symbols set from string to GUID
577 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
578 PreservedSymbols, Triple(TheModule.getTargetTriple()));
579
580 // Promote the exported values in the index, so that they are promoted
581 // in the module.
582 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
583 const auto &ExportList = ExportLists.find(ModuleIdentifier);
584 return (ExportList != ExportLists.end() &&
585 ExportList->second.count(GUID)) ||
586 GUIDPreservedSymbols.count(GUID);
587 };
588 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
589
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000590 promoteModule(TheModule, Index);
591}
592
593/**
594 * Perform cross-module importing for the module identified by ModuleIdentifier.
595 */
596void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000597 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000598 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000599 auto ModuleCount = Index.modulePaths().size();
600
601 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000602 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000603 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000604
605 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000606 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
607 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000608 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
609 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000610 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
611
612 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000613}
614
615/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000616 * Compute the list of summaries needed for importing into module.
617 */
618void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
619 StringRef ModulePath, ModuleSummaryIndex &Index,
620 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
621 auto ModuleCount = Index.modulePaths().size();
622
623 // Collect for each module the list of function it defines (GUID -> Summary).
624 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
625 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
626
627 // Generate import/export list
628 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
629 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
630 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
631 ExportLists);
632
633 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000634 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000635 ModuleToSummariesForIndex);
636}
637
638/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000639 * Emit the list of files needed for importing into module.
640 */
641void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
642 StringRef OutputName,
643 ModuleSummaryIndex &Index) {
644 auto ModuleCount = Index.modulePaths().size();
645
646 // Collect for each module the list of function it defines (GUID -> Summary).
647 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
648 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
649
650 // Generate import/export list
651 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
652 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
653 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
654 ExportLists);
655
656 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000657 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000658 report_fatal_error(Twine("Failed to open ") + OutputName +
659 " to save imports lists\n");
660}
661
662/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000663 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000664 */
665void ThinLTOCodeGenerator::internalize(Module &TheModule,
666 ModuleSummaryIndex &Index) {
667 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
668 auto ModuleCount = Index.modulePaths().size();
669 auto ModuleIdentifier = TheModule.getModuleIdentifier();
670
671 // Convert the preserved symbols set from string to GUID
672 auto GUIDPreservedSymbols =
673 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
674
675 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000676 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000677 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
678
679 // Generate import/export list
680 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
681 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
682 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
683 ExportLists);
684 auto &ExportList = ExportLists[ModuleIdentifier];
685
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000686 // Be friendly and don't nuke totally the module when the client didn't
687 // supply anything to preserve.
688 if (ExportList.empty() && GUIDPreservedSymbols.empty())
689 return;
690
Mehdi Amini059464f2016-04-24 03:18:01 +0000691 // Internalization
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000692 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
693 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000694 return (ExportList != ExportLists.end() &&
695 ExportList->second.count(GUID)) ||
696 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000697 };
698 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
699 thinLTOInternalizeModule(TheModule,
700 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000701}
702
703/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000704 * Perform post-importing ThinLTO optimizations.
705 */
706void ThinLTOCodeGenerator::optimize(Module &TheModule) {
707 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000708
709 // Optimize now
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000710 optimizeModule(TheModule, *TMBuilder.create());
711}
712
713/**
714 * Perform ThinLTO CodeGen.
715 */
716std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
717 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
718 return codegenModule(TheModule, *TMBuilder.create());
719}
720
721// Main entry point for the ThinLTO processing
722void ThinLTOCodeGenerator::run() {
Mehdi Amini43b657b2016-04-01 06:47:02 +0000723 if (CodeGenOnly) {
724 // Perform only parallel codegen and return.
725 ThreadPool Pool;
726 assert(ProducedBinaries.empty() && "The generator should not be reused");
727 ProducedBinaries.resize(Modules.size());
728 int count = 0;
729 for (auto &ModuleBuffer : Modules) {
730 Pool.async([&](int count) {
731 LLVMContext Context;
732 Context.setDiscardValueNames(LTODiscardValueNames);
733
734 // Parse module now
735 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
736
737 // CodeGen
738 ProducedBinaries[count] = codegen(*TheModule);
739 }, count++);
740 }
741
742 return;
743 }
744
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000745 // Sequential linking phase
746 auto Index = linkCombinedIndex();
747
748 // Save temps: index.
749 if (!SaveTempsDir.empty()) {
750 auto SaveTempPath = SaveTempsDir + "index.bc";
751 std::error_code EC;
752 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
753 if (EC)
754 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
755 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000756 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000757 }
758
759 // Prepare the resulting object vector
760 assert(ProducedBinaries.empty() && "The generator should not be reused");
761 ProducedBinaries.resize(Modules.size());
762
763 // Prepare the module map.
764 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000765 auto ModuleCount = Modules.size();
766
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000767 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000768 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000769 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
770
Mehdi Amini01e32132016-03-26 05:40:34 +0000771 // Collect the import/export lists for all modules from the call-graph in the
772 // combined index.
773 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
774 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000775 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
776 ExportLists);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000777
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000778 // Convert the preserved symbols set from string to GUID, this is needed for
Mehdi Amini059464f2016-04-24 03:18:01 +0000779 // computing the caching hash and the internalization.
780 auto GUIDPreservedSymbols =
781 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000782
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000783 // We use a std::map here to be able to have a defined ordering when
784 // producing a hash for the cache entry.
785 // FIXME: we should be able to compute the caching hash for the entry based
786 // on the index, and nuke this map.
787 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
788
789 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
790 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000791 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000792
793 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
794 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000795 return (ExportList != ExportLists.end() &&
796 ExportList->second.count(GUID)) ||
797 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000798 };
799
800 // Use global summary-based analysis to identify symbols that can be
801 // internalized (because they aren't exported or preserved as per callback).
802 // Changes are made in the index, consumed in the ThinLTO backends.
803 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
804
Teresa Johnson141149f2016-05-24 18:44:01 +0000805 // Make sure that every module has an entry in the ExportLists and
806 // ResolvedODR maps to enable threaded access to these maps below.
807 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000808 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000809 ResolvedODR[DefinedGVSummaries.first()];
810 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000811
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000812 // Compute the ordering we will process the inputs: the rough heuristic here
813 // is to sort them per size so that the largest module get schedule as soon as
814 // possible. This is purely a compile-time optimization.
815 std::vector<int> ModulesOrdering;
816 ModulesOrdering.resize(Modules.size());
817 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
818 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
819 [&](int LeftIndex, int RightIndex) {
820 auto LSize = Modules[LeftIndex].getBufferSize();
821 auto RSize = Modules[RightIndex].getBufferSize();
822 return LSize > RSize;
823 });
824
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000825 // Parallel optimizer + codegen
826 {
827 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000828 for (auto IndexCount : ModulesOrdering) {
829 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000830 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000831 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000832 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000833
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000834 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
835
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000836 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000837 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
838 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000839 ResolvedODR[ModuleIdentifier],
840 DefinedFunctions, GUIDPreservedSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000841
842 {
843 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000844 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
845 << CacheEntry.getEntryPath() << "' for buffer " << count
846 << " " << ModuleIdentifier << "\n");
847
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000848 if (ErrOrBuffer) {
849 // Cache Hit!
850 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
851 return;
852 }
853 }
854
855 LLVMContext Context;
856 Context.setDiscardValueNames(LTODiscardValueNames);
857 Context.enableDebugTypeODRUniquing();
Mehdi Amini19f176b2016-11-19 18:20:05 +0000858 auto DiagFileOrErr = setupOptimizationRemarks(Context, count);
859 if (!DiagFileOrErr) {
860 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
861 report_fatal_error("ThinLTO: Can't get an output file for the "
862 "remarks");
863 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000864
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000865 // Parse module now
866 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
867
868 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000869 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000870
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000871 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000872 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000873 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000874 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000875 ExportList, GUIDPreservedSymbols,
876 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Amini059464f2016-04-24 03:18:01 +0000877 DisableCodeGen, SaveTempsDir, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000878
Mehdi Amini001bb412016-05-16 19:11:59 +0000879 OutputBuffer = CacheEntry.write(std::move(OutputBuffer));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000880 ProducedBinaries[count] = std::move(OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000881 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000882 }
883 }
884
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000885 CachePruning(CacheOptions.Path)
Pavel Labath757ca882016-10-24 10:59:17 +0000886 .setPruningInterval(std::chrono::seconds(CacheOptions.PruningInterval))
887 .setEntryExpiration(std::chrono::seconds(CacheOptions.Expiration))
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000888 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
889 .prune();
890
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000891 // If statistics were requested, print them out now.
892 if (llvm::AreStatisticsEnabled())
893 llvm::PrintStatistics();
894}