blob: 77f1d342e1168d915f749a25048e871f9e1e676d [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"
43#include "llvm/Support/Path.h"
44#include "llvm/Support/SHA1.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000045#include "llvm/Support/TargetRegistry.h"
46#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000047#include "llvm/Support/Threading.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000048#include "llvm/Target/TargetMachine.h"
49#include "llvm/Transforms/IPO.h"
50#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000051#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000052#include "llvm/Transforms/IPO/PassManagerBuilder.h"
53#include "llvm/Transforms/ObjCARC.h"
54#include "llvm/Transforms/Utils/FunctionImportUtils.h"
55
Mehdi Amini819e9cd2016-05-16 19:33:07 +000056#include <numeric>
57
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000058using namespace llvm;
59
Mehdi Amini1aafabf2016-04-16 07:02:16 +000060#define DEBUG_TYPE "thinlto"
61
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000062namespace llvm {
63// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
64extern cl::opt<bool> LTODiscardValueNames;
65}
66
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000067namespace {
68
Teresa Johnsonec544c52016-10-19 17:35:01 +000069static cl::opt<int>
70 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000071
72static void diagnosticHandler(const DiagnosticInfo &DI) {
73 DiagnosticPrinterRawOStream DP(errs());
74 DI.print(DP);
75 errs() << '\n';
76}
77
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000078// Simple helper to save temporary files for debug.
79static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
80 unsigned count, StringRef Suffix) {
81 if (TempDir.empty())
82 return;
83 // User asked to save temps, let dump the bitcode file after import.
Teresa Johnsonc44a1222016-08-15 23:24:57 +000084 std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000085 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000086 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000087 if (EC)
88 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
89 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +000090 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000091}
92
Teresa Johnson4d2613f2016-05-24 17:24:25 +000093static const GlobalValueSummary *
94getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
95 // If there is any strong definition anywhere, get it.
96 auto StrongDefForLinker = llvm::find_if(
97 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
98 auto Linkage = Summary->linkage();
99 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
100 !GlobalValue::isWeakForLinker(Linkage);
101 });
102 if (StrongDefForLinker != GVSummaryList.end())
103 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000104 // Get the first *linker visible* definition for this global in the summary
105 // list.
106 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000107 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
108 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000109 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
110 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000111 // Extern templates can be emitted as available_externally.
112 if (FirstDefForLinker == GVSummaryList.end())
113 return nullptr;
114 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000115}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000116
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000117// Populate map of GUID to the prevailing copy for any multiply defined
118// symbols. Currently assume first copy is prevailing, or any strong
119// definition. Can be refined with Linker information in the future.
120static void computePrevailingCopies(
121 const ModuleSummaryIndex &Index,
122 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000123 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
124 return GVSummaryList.size() > 1;
125 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000126
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000127 for (auto &I : Index) {
128 if (HasMultipleCopies(I.second))
129 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000130 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000131}
132
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000133static StringMap<MemoryBufferRef>
134generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
135 StringMap<MemoryBufferRef> ModuleMap;
136 for (auto &ModuleBuffer : Modules) {
137 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
138 ModuleMap.end() &&
139 "Expect unique Buffer Identifier");
140 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
141 }
142 return ModuleMap;
143}
144
Teresa Johnson26ab5772016-03-15 00:04:37 +0000145static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000146 if (renameModuleForThinLTO(TheModule, Index))
147 report_fatal_error("renameModuleForThinLTO failed");
148}
149
Mehdi Amini01e32132016-03-26 05:40:34 +0000150static void
151crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
152 StringMap<MemoryBufferRef> &ModuleMap,
153 const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000154 ModuleLoader Loader(TheModule.getContext(), ModuleMap);
155 FunctionImporter Importer(Index, Loader);
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000156 if (!Importer.importFunctions(TheModule, ImportList))
157 report_fatal_error("importFunctions failed");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000158}
159
160static void optimizeModule(Module &TheModule, TargetMachine &TM) {
161 // Populate the PassManager
162 PassManagerBuilder PMB;
163 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
164 PMB.Inliner = createFunctionInliningPass();
165 // FIXME: should get it from the bitcode?
166 PMB.OptLevel = 3;
167 PMB.LoopVectorize = true;
168 PMB.SLPVectorize = true;
169 PMB.VerifyInput = true;
170 PMB.VerifyOutput = false;
171
172 legacy::PassManager PM;
173
174 // Add the TTI (required to inform the vectorizer about register size for
175 // instance)
176 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
177
178 // Add optimizations
179 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000180
181 PM.run(TheModule);
182}
183
Mehdi Amini059464f2016-04-24 03:18:01 +0000184// Convert the PreservedSymbols map from "Name" based to "GUID" based.
185static DenseSet<GlobalValue::GUID>
186computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
187 const Triple &TheTriple) {
188 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
189 for (auto &Entry : PreservedSymbols) {
190 StringRef Name = Entry.first();
191 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
192 Name = Name.drop_front();
193 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
194 }
195 return GUIDPreservedSymbols;
196}
197
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000198std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
199 TargetMachine &TM) {
200 SmallVector<char, 128> OutputBuffer;
201
202 // CodeGen
203 {
204 raw_svector_ostream OS(OutputBuffer);
205 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000206
207 // If the bitcode files contain ARC code and were compiled with optimization,
208 // the ObjCARCContractPass must be run, so do it unconditionally here.
209 PM.add(createObjCARCContractPass());
210
211 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000212 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
213 /* DisableVerify */ true))
214 report_fatal_error("Failed to setup codegen");
215
216 // Run codegen now. resulting binary is in OutputBuffer.
217 PM.run(TheModule);
218 }
219 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
220}
221
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000222/// Manage caching for a single Module.
223class ModuleCacheEntry {
224 SmallString<128> EntryPath;
225
226public:
227 // Create a cache entry. This compute a unique hash for the Module considering
228 // the current list of export/import, and offer an interface to query to
229 // access the content in the cache.
230 ModuleCacheEntry(
231 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
232 const FunctionImporter::ImportMapTy &ImportList,
233 const FunctionImporter::ExportSetTy &ExportList,
234 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000235 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000236 const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
237 if (CachePath.empty())
238 return;
239
Mehdi Amini00fa1402016-10-08 04:44:18 +0000240 if (!Index.modulePaths().count(ModuleID))
241 // The module does not have an entry, it can't have a hash at all
242 return;
243
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000244 // Compute the unique hash for this entry
245 // This is based on the current compiler version, the module itself, the
246 // export list, the hash for every single module in the import list, the
247 // list of ResolvedODR for the module, and the list of preserved symbols.
248
Mehdi Aminif82bda02016-10-08 04:44:23 +0000249 // Include the hash for the current module
250 auto ModHash = Index.getModuleHash(ModuleID);
251
252 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
253 // No hash entry, no caching!
254 return;
255
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000256 SHA1 Hasher;
257
258 // Start with the compiler revision
259 Hasher.update(LLVM_VERSION_STRING);
260#ifdef HAVE_LLVM_REVISION
261 Hasher.update(LLVM_REVISION);
262#endif
263
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000264 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
265 for (auto F : ExportList)
266 // The export list can impact the internalization, be conservative here
267 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
268
269 // Include the hash for every module we import functions from
270 for (auto &Entry : ImportList) {
271 auto ModHash = Index.getModuleHash(Entry.first());
272 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
273 }
274
275 // Include the hash for the resolved ODR.
276 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000277 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000278 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000279 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000280 sizeof(GlobalValue::LinkageTypes)));
281 }
282
283 // Include the hash for the preserved symbols.
284 for (auto &Entry : PreservedSymbols) {
285 if (DefinedFunctions.count(Entry))
286 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000287 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000288 }
289
290 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
291 }
292
Mehdi Amini059464f2016-04-24 03:18:01 +0000293 // Access the path to this entry in the cache.
294 StringRef getEntryPath() { return EntryPath; }
295
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000296 // Try loading the buffer for this cache entry.
297 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
298 if (EntryPath.empty())
299 return std::error_code();
300 return MemoryBuffer::getFile(EntryPath);
301 }
302
303 // Cache the Produced object file
Mehdi Amini001bb412016-05-16 19:11:59 +0000304 std::unique_ptr<MemoryBuffer>
305 write(std::unique_ptr<MemoryBuffer> OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000306 if (EntryPath.empty())
Mehdi Amini001bb412016-05-16 19:11:59 +0000307 return OutputBuffer;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000308
309 // Write to a temporary to avoid race condition
310 SmallString<128> TempFilename;
311 int TempFD;
312 std::error_code EC =
313 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
314 if (EC) {
315 errs() << "Error: " << EC.message() << "\n";
316 report_fatal_error("ThinLTO: Can't get a temporary file");
317 }
318 {
319 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini001bb412016-05-16 19:11:59 +0000320 OS << OutputBuffer->getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000321 }
322 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000323 EC = sys::fs::rename(TempFilename, EntryPath);
324 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000325 sys::fs::remove(TempFilename);
326 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
327 if (EC)
328 report_fatal_error(Twine("Failed to open ") + EntryPath +
329 " to save cached entry\n");
Mehdi Amini001bb412016-05-16 19:11:59 +0000330 OS << OutputBuffer->getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000331 }
Mehdi Amini001bb412016-05-16 19:11:59 +0000332 auto ReloadedBufferOrErr = MemoryBuffer::getFile(EntryPath);
333 if (auto EC = ReloadedBufferOrErr.getError()) {
334 // FIXME diagnose
335 errs() << "error: can't reload cached file '" << EntryPath
336 << "': " << EC.message() << "\n";
337 return OutputBuffer;
338 }
339 return std::move(*ReloadedBufferOrErr);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000340 }
341};
342
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000343static std::unique_ptr<MemoryBuffer>
344ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
345 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
346 const FunctionImporter::ImportMapTy &ImportList,
347 const FunctionImporter::ExportSetTy &ExportList,
348 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
349 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000350 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000351 bool DisableCodeGen, StringRef SaveTempsDir,
352 unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000353
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000354 // "Benchmark"-like optimization: single-source case
355 bool SingleModule = (ModuleMap.size() == 1);
356
357 if (!SingleModule) {
358 promoteModule(TheModule, Index);
359
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000360 // Apply summary-based LinkOnce/Weak resolution decisions.
361 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000362
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000363 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000364 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000365 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000366
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000367 // Be friendly and don't nuke totally the module when the client didn't
368 // supply anything to preserve.
369 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
370 // Apply summary-based internalization decisions.
371 thinLTOInternalizeModule(TheModule, DefinedGlobals);
372 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000373
374 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000375 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000376
377 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000378 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000379
380 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000381 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000382 }
383
384 optimizeModule(TheModule, TM);
385
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000386 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000387
Mehdi Amini43b657b2016-04-01 06:47:02 +0000388 if (DisableCodeGen) {
389 // Configured to stop before CodeGen, serialize the bitcode and return.
390 SmallVector<char, 128> OutputBuffer;
391 {
392 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000393 ProfileSummaryInfo PSI(TheModule);
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000394 auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000395 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000396 }
397 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
398 }
399
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000400 return codegenModule(TheModule, TM);
401}
402
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000403/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
404/// for caching, and in the \p Index for application during the ThinLTO
405/// backends. This is needed for correctness for exported symbols (ensure
406/// at least one copy kept) and a compile-time optimization (to drop duplicate
407/// copies when possible).
408static void resolveWeakForLinkerInIndex(
409 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000410 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
411 &ResolvedODR) {
412
413 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
414 computePrevailingCopies(Index, PrevailingCopy);
415
416 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
417 const auto &Prevailing = PrevailingCopy.find(GUID);
418 // Not in map means that there was only one copy, which must be prevailing.
419 if (Prevailing == PrevailingCopy.end())
420 return true;
421 return Prevailing->second == S;
422 };
423
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000424 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
425 GlobalValue::GUID GUID,
426 GlobalValue::LinkageTypes NewLinkage) {
427 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
428 };
429
Peter Collingbourne73589f32016-07-07 18:31:51 +0000430 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000431}
432
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000433// Initialize the TargetMachine builder for a given Triple
434static void initTMBuilder(TargetMachineBuilder &TMBuilder,
435 const Triple &TheTriple) {
436 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
437 // FIXME this looks pretty terrible...
438 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
439 if (TheTriple.getArch() == llvm::Triple::x86_64)
440 TMBuilder.MCpu = "core2";
441 else if (TheTriple.getArch() == llvm::Triple::x86)
442 TMBuilder.MCpu = "yonah";
443 else if (TheTriple.getArch() == llvm::Triple::aarch64)
444 TMBuilder.MCpu = "cyclone";
445 }
446 TMBuilder.TheTriple = std::move(TheTriple);
447}
448
449} // end anonymous namespace
450
451void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
452 MemoryBufferRef Buffer(Data, Identifier);
453 if (Modules.empty()) {
454 // First module added, so initialize the triple and some options
455 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000456 StringRef TripleStr;
457 ErrorOr<std::string> TripleOrErr =
458 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
459 if (TripleOrErr)
460 TripleStr = *TripleOrErr;
461 Triple TheTriple(TripleStr);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000462 initTMBuilder(TMBuilder, Triple(TheTriple));
463 }
464#ifndef NDEBUG
465 else {
466 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000467 StringRef TripleStr;
468 ErrorOr<std::string> TripleOrErr =
469 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
470 if (TripleOrErr)
471 TripleStr = *TripleOrErr;
472 assert(TMBuilder.TheTriple.str() == TripleStr &&
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000473 "ThinLTO modules with different triple not supported");
474 }
475#endif
476 Modules.push_back(Buffer);
477}
478
479void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
480 PreservedSymbols.insert(Name);
481}
482
483void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000484 // FIXME: At the moment, we don't take advantage of this extra information,
485 // we're conservatively considering cross-references as preserved.
486 // CrossReferencedSymbols.insert(Name);
487 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000488}
489
490// TargetMachine factory
491std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
492 std::string ErrMsg;
493 const Target *TheTarget =
494 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
495 if (!TheTarget) {
496 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
497 }
498
499 // Use MAttr as the default set of features.
500 SubtargetFeatures Features(MAttr);
501 Features.getDefaultSubtargetFeatures(TheTriple);
502 std::string FeatureStr = Features.getString();
503 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
504 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
505 CodeModel::Default, CGOptLevel));
506}
507
508/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000509 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000510 * "thin-link".
511 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000512std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
513 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000514 uint64_t NextModuleId = 0;
515 for (auto &ModuleBuffer : Modules) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000516 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
517 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer,
Teresa Johnson6fb3f192016-04-22 01:52:00 +0000518 diagnosticHandler);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000519 if (std::error_code EC = ObjOrErr.getError()) {
520 // FIXME diagnose
Teresa Johnson26ab5772016-03-15 00:04:37 +0000521 errs() << "error: can't create ModuleSummaryIndexObjectFile for buffer: "
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000522 << EC.message() << "\n";
523 return nullptr;
524 }
525 auto Index = (*ObjOrErr)->takeIndex();
526 if (CombinedIndex) {
527 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
528 } else {
529 CombinedIndex = std::move(Index);
530 }
531 }
532 return CombinedIndex;
533}
534
535/**
536 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000537 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000538 */
539void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000540 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000541 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000542 auto ModuleIdentifier = TheModule.getModuleIdentifier();
543 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000544 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000545 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000546
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000547 // Generate import/export list
548 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
549 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
550 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
551 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000552
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000553 // Resolve LinkOnce/Weak symbols.
554 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000555 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000556
557 thinLTOResolveWeakForLinkerModule(
558 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000559
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000560 promoteModule(TheModule, Index);
561}
562
563/**
564 * Perform cross-module importing for the module identified by ModuleIdentifier.
565 */
566void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000567 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000568 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000569 auto ModuleCount = Index.modulePaths().size();
570
571 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000572 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000573 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000574
575 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000576 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
577 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000578 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
579 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000580 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
581
582 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000583}
584
585/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000586 * Compute the list of summaries needed for importing into module.
587 */
588void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
589 StringRef ModulePath, ModuleSummaryIndex &Index,
590 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
591 auto ModuleCount = Index.modulePaths().size();
592
593 // Collect for each module the list of function it defines (GUID -> Summary).
594 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
595 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
596
597 // Generate import/export list
598 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
599 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
600 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
601 ExportLists);
602
603 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000604 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000605 ModuleToSummariesForIndex);
606}
607
608/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000609 * Emit the list of files needed for importing into module.
610 */
611void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
612 StringRef OutputName,
613 ModuleSummaryIndex &Index) {
614 auto ModuleCount = Index.modulePaths().size();
615
616 // Collect for each module the list of function it defines (GUID -> Summary).
617 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
618 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
619
620 // Generate import/export list
621 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
622 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
623 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
624 ExportLists);
625
626 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000627 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000628 report_fatal_error(Twine("Failed to open ") + OutputName +
629 " to save imports lists\n");
630}
631
632/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000633 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000634 */
635void ThinLTOCodeGenerator::internalize(Module &TheModule,
636 ModuleSummaryIndex &Index) {
637 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
638 auto ModuleCount = Index.modulePaths().size();
639 auto ModuleIdentifier = TheModule.getModuleIdentifier();
640
641 // Convert the preserved symbols set from string to GUID
642 auto GUIDPreservedSymbols =
643 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
644
645 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000646 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000647 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
648
649 // Generate import/export list
650 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
651 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
652 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
653 ExportLists);
654 auto &ExportList = ExportLists[ModuleIdentifier];
655
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000656 // Be friendly and don't nuke totally the module when the client didn't
657 // supply anything to preserve.
658 if (ExportList.empty() && GUIDPreservedSymbols.empty())
659 return;
660
Mehdi Amini059464f2016-04-24 03:18:01 +0000661 // Internalization
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000662 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
663 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000664 return (ExportList != ExportLists.end() &&
665 ExportList->second.count(GUID)) ||
666 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000667 };
668 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
669 thinLTOInternalizeModule(TheModule,
670 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000671}
672
673/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000674 * Perform post-importing ThinLTO optimizations.
675 */
676void ThinLTOCodeGenerator::optimize(Module &TheModule) {
677 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000678
679 // Optimize now
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000680 optimizeModule(TheModule, *TMBuilder.create());
681}
682
683/**
684 * Perform ThinLTO CodeGen.
685 */
686std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
687 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
688 return codegenModule(TheModule, *TMBuilder.create());
689}
690
691// Main entry point for the ThinLTO processing
692void ThinLTOCodeGenerator::run() {
Mehdi Amini43b657b2016-04-01 06:47:02 +0000693 if (CodeGenOnly) {
694 // Perform only parallel codegen and return.
695 ThreadPool Pool;
696 assert(ProducedBinaries.empty() && "The generator should not be reused");
697 ProducedBinaries.resize(Modules.size());
698 int count = 0;
699 for (auto &ModuleBuffer : Modules) {
700 Pool.async([&](int count) {
701 LLVMContext Context;
702 Context.setDiscardValueNames(LTODiscardValueNames);
703
704 // Parse module now
705 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
706
707 // CodeGen
708 ProducedBinaries[count] = codegen(*TheModule);
709 }, count++);
710 }
711
712 return;
713 }
714
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000715 // Sequential linking phase
716 auto Index = linkCombinedIndex();
717
718 // Save temps: index.
719 if (!SaveTempsDir.empty()) {
720 auto SaveTempPath = SaveTempsDir + "index.bc";
721 std::error_code EC;
722 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
723 if (EC)
724 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
725 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000726 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000727 }
728
729 // Prepare the resulting object vector
730 assert(ProducedBinaries.empty() && "The generator should not be reused");
731 ProducedBinaries.resize(Modules.size());
732
733 // Prepare the module map.
734 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000735 auto ModuleCount = Modules.size();
736
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000737 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000738 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000739 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
740
Mehdi Amini01e32132016-03-26 05:40:34 +0000741 // Collect the import/export lists for all modules from the call-graph in the
742 // combined index.
743 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
744 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000745 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
746 ExportLists);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000747
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000748 // Convert the preserved symbols set from string to GUID, this is needed for
Mehdi Amini059464f2016-04-24 03:18:01 +0000749 // computing the caching hash and the internalization.
750 auto GUIDPreservedSymbols =
751 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000752
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000753 // We use a std::map here to be able to have a defined ordering when
754 // producing a hash for the cache entry.
755 // FIXME: we should be able to compute the caching hash for the entry based
756 // on the index, and nuke this map.
757 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
758
759 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
760 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000761 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000762
763 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
764 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000765 return (ExportList != ExportLists.end() &&
766 ExportList->second.count(GUID)) ||
767 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000768 };
769
770 // Use global summary-based analysis to identify symbols that can be
771 // internalized (because they aren't exported or preserved as per callback).
772 // Changes are made in the index, consumed in the ThinLTO backends.
773 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
774
Teresa Johnson141149f2016-05-24 18:44:01 +0000775 // Make sure that every module has an entry in the ExportLists and
776 // ResolvedODR maps to enable threaded access to these maps below.
777 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000778 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000779 ResolvedODR[DefinedGVSummaries.first()];
780 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000781
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000782 // Compute the ordering we will process the inputs: the rough heuristic here
783 // is to sort them per size so that the largest module get schedule as soon as
784 // possible. This is purely a compile-time optimization.
785 std::vector<int> ModulesOrdering;
786 ModulesOrdering.resize(Modules.size());
787 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
788 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
789 [&](int LeftIndex, int RightIndex) {
790 auto LSize = Modules[LeftIndex].getBufferSize();
791 auto RSize = Modules[RightIndex].getBufferSize();
792 return LSize > RSize;
793 });
794
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000795 // Parallel optimizer + codegen
796 {
797 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000798 for (auto IndexCount : ModulesOrdering) {
799 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000800 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000801 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000802 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000803
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000804 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
805
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000806 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000807 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
808 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000809 ResolvedODR[ModuleIdentifier],
810 DefinedFunctions, GUIDPreservedSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000811
812 {
813 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000814 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
815 << CacheEntry.getEntryPath() << "' for buffer " << count
816 << " " << ModuleIdentifier << "\n");
817
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000818 if (ErrOrBuffer) {
819 // Cache Hit!
820 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
821 return;
822 }
823 }
824
825 LLVMContext Context;
826 Context.setDiscardValueNames(LTODiscardValueNames);
827 Context.enableDebugTypeODRUniquing();
828
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000829 // Parse module now
830 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
831
832 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000833 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000834
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000835 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000836 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000837 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000838 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000839 ExportList, GUIDPreservedSymbols,
840 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Amini059464f2016-04-24 03:18:01 +0000841 DisableCodeGen, SaveTempsDir, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000842
Mehdi Amini001bb412016-05-16 19:11:59 +0000843 OutputBuffer = CacheEntry.write(std::move(OutputBuffer));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000844 ProducedBinaries[count] = std::move(OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000845 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000846 }
847 }
848
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000849 CachePruning(CacheOptions.Path)
Pavel Labath757ca882016-10-24 10:59:17 +0000850 .setPruningInterval(std::chrono::seconds(CacheOptions.PruningInterval))
851 .setEntryExpiration(std::chrono::seconds(CacheOptions.Expiration))
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000852 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
853 .prune();
854
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000855 // If statistics were requested, print them out now.
856 if (llvm::AreStatisticsEnabled())
857 llvm::PrintStatistics();
858}