blob: 8afe13d8e16f056a80333339b686c29973a382a3 [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 Johnsoncec0cae2016-03-14 21:18:10 +000027#include "llvm/Bitcode/BitcodeWriterPass.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000028#include "llvm/Bitcode/ReaderWriter.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000029#include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000030#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000031#include "llvm/IR/LLVMContext.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000032#include "llvm/IR/LegacyPassManager.h"
33#include "llvm/IR/Mangler.h"
34#include "llvm/IRReader/IRReader.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000035#include "llvm/LTO/LTO.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000036#include "llvm/Linker/Linker.h"
37#include "llvm/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000038#include "llvm/Object/IRObjectFile.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000039#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000040#include "llvm/Support/CachePruning.h"
41#include "llvm/Support/Debug.h"
42#include "llvm/Support/Path.h"
43#include "llvm/Support/SHA1.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000044#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/ThreadPool.h"
46#include "llvm/Target/TargetMachine.h"
47#include "llvm/Transforms/IPO.h"
48#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000049#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000050#include "llvm/Transforms/IPO/PassManagerBuilder.h"
51#include "llvm/Transforms/ObjCARC.h"
52#include "llvm/Transforms/Utils/FunctionImportUtils.h"
53
Mehdi Amini819e9cd2016-05-16 19:33:07 +000054#include <numeric>
55
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000056using namespace llvm;
57
Mehdi Amini1aafabf2016-04-16 07:02:16 +000058#define DEBUG_TYPE "thinlto"
59
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000060namespace llvm {
61// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
62extern cl::opt<bool> LTODiscardValueNames;
63}
64
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000065namespace {
66
67static cl::opt<int> ThreadCount("threads",
68 cl::init(std::thread::hardware_concurrency()));
69
70static void diagnosticHandler(const DiagnosticInfo &DI) {
71 DiagnosticPrinterRawOStream DP(errs());
72 DI.print(DP);
73 errs() << '\n';
74}
75
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000076// Simple helper to save temporary files for debug.
77static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
78 unsigned count, StringRef Suffix) {
79 if (TempDir.empty())
80 return;
81 // User asked to save temps, let dump the bitcode file after import.
Teresa Johnsonc44a1222016-08-15 23:24:57 +000082 std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000083 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000084 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000085 if (EC)
86 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
87 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +000088 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000089}
90
Teresa Johnson4d2613f2016-05-24 17:24:25 +000091static const GlobalValueSummary *
92getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
93 // If there is any strong definition anywhere, get it.
94 auto StrongDefForLinker = llvm::find_if(
95 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
96 auto Linkage = Summary->linkage();
97 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
98 !GlobalValue::isWeakForLinker(Linkage);
99 });
100 if (StrongDefForLinker != GVSummaryList.end())
101 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000102 // Get the first *linker visible* definition for this global in the summary
103 // list.
104 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000105 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
106 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000107 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
108 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000109 // Extern templates can be emitted as available_externally.
110 if (FirstDefForLinker == GVSummaryList.end())
111 return nullptr;
112 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000113}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000114
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000115// Populate map of GUID to the prevailing copy for any multiply defined
116// symbols. Currently assume first copy is prevailing, or any strong
117// definition. Can be refined with Linker information in the future.
118static void computePrevailingCopies(
119 const ModuleSummaryIndex &Index,
120 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000121 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
122 return GVSummaryList.size() > 1;
123 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000124
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000125 for (auto &I : Index) {
126 if (HasMultipleCopies(I.second))
127 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000128 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000129}
130
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000131static StringMap<MemoryBufferRef>
132generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
133 StringMap<MemoryBufferRef> ModuleMap;
134 for (auto &ModuleBuffer : Modules) {
135 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
136 ModuleMap.end() &&
137 "Expect unique Buffer Identifier");
138 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
139 }
140 return ModuleMap;
141}
142
Teresa Johnson26ab5772016-03-15 00:04:37 +0000143static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000144 if (renameModuleForThinLTO(TheModule, Index))
145 report_fatal_error("renameModuleForThinLTO failed");
146}
147
Mehdi Amini01e32132016-03-26 05:40:34 +0000148static void
149crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
150 StringMap<MemoryBufferRef> &ModuleMap,
151 const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000152 ModuleLoader Loader(TheModule.getContext(), ModuleMap);
153 FunctionImporter Importer(Index, Loader);
Mehdi Amini01e32132016-03-26 05:40:34 +0000154 Importer.importFunctions(TheModule, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000155}
156
157static void optimizeModule(Module &TheModule, TargetMachine &TM) {
158 // Populate the PassManager
159 PassManagerBuilder PMB;
160 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
161 PMB.Inliner = createFunctionInliningPass();
162 // FIXME: should get it from the bitcode?
163 PMB.OptLevel = 3;
164 PMB.LoopVectorize = true;
165 PMB.SLPVectorize = true;
166 PMB.VerifyInput = true;
167 PMB.VerifyOutput = false;
168
169 legacy::PassManager PM;
170
171 // Add the TTI (required to inform the vectorizer about register size for
172 // instance)
173 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
174
175 // Add optimizations
176 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000177
178 PM.run(TheModule);
179}
180
Mehdi Amini059464f2016-04-24 03:18:01 +0000181// Convert the PreservedSymbols map from "Name" based to "GUID" based.
182static DenseSet<GlobalValue::GUID>
183computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
184 const Triple &TheTriple) {
185 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
186 for (auto &Entry : PreservedSymbols) {
187 StringRef Name = Entry.first();
188 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
189 Name = Name.drop_front();
190 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
191 }
192 return GUIDPreservedSymbols;
193}
194
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000195std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
196 TargetMachine &TM) {
197 SmallVector<char, 128> OutputBuffer;
198
199 // CodeGen
200 {
201 raw_svector_ostream OS(OutputBuffer);
202 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000203
204 // If the bitcode files contain ARC code and were compiled with optimization,
205 // the ObjCARCContractPass must be run, so do it unconditionally here.
206 PM.add(createObjCARCContractPass());
207
208 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000209 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
210 /* DisableVerify */ true))
211 report_fatal_error("Failed to setup codegen");
212
213 // Run codegen now. resulting binary is in OutputBuffer.
214 PM.run(TheModule);
215 }
216 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
217}
218
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000219/// Manage caching for a single Module.
220class ModuleCacheEntry {
221 SmallString<128> EntryPath;
222
223public:
224 // Create a cache entry. This compute a unique hash for the Module considering
225 // the current list of export/import, and offer an interface to query to
226 // access the content in the cache.
227 ModuleCacheEntry(
228 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
229 const FunctionImporter::ImportMapTy &ImportList,
230 const FunctionImporter::ExportSetTy &ExportList,
231 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000232 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000233 const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
234 if (CachePath.empty())
235 return;
236
Mehdi Amini00fa1402016-10-08 04:44:18 +0000237 if (!Index.modulePaths().count(ModuleID))
238 // The module does not have an entry, it can't have a hash at all
239 return;
240
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000241 // Compute the unique hash for this entry
242 // This is based on the current compiler version, the module itself, the
243 // export list, the hash for every single module in the import list, the
244 // list of ResolvedODR for the module, and the list of preserved symbols.
245
246 SHA1 Hasher;
247
248 // Start with the compiler revision
249 Hasher.update(LLVM_VERSION_STRING);
250#ifdef HAVE_LLVM_REVISION
251 Hasher.update(LLVM_REVISION);
252#endif
253
254 // Include the hash for the current module
255 auto ModHash = Index.getModuleHash(ModuleID);
256 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
257 for (auto F : ExportList)
258 // The export list can impact the internalization, be conservative here
259 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
260
261 // Include the hash for every module we import functions from
262 for (auto &Entry : ImportList) {
263 auto ModHash = Index.getModuleHash(Entry.first());
264 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
265 }
266
267 // Include the hash for the resolved ODR.
268 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000269 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000270 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000271 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000272 sizeof(GlobalValue::LinkageTypes)));
273 }
274
275 // Include the hash for the preserved symbols.
276 for (auto &Entry : PreservedSymbols) {
277 if (DefinedFunctions.count(Entry))
278 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000279 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000280 }
281
282 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
283 }
284
Mehdi Amini059464f2016-04-24 03:18:01 +0000285 // Access the path to this entry in the cache.
286 StringRef getEntryPath() { return EntryPath; }
287
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000288 // Try loading the buffer for this cache entry.
289 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
290 if (EntryPath.empty())
291 return std::error_code();
292 return MemoryBuffer::getFile(EntryPath);
293 }
294
295 // Cache the Produced object file
Mehdi Amini001bb412016-05-16 19:11:59 +0000296 std::unique_ptr<MemoryBuffer>
297 write(std::unique_ptr<MemoryBuffer> OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000298 if (EntryPath.empty())
Mehdi Amini001bb412016-05-16 19:11:59 +0000299 return OutputBuffer;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000300
301 // Write to a temporary to avoid race condition
302 SmallString<128> TempFilename;
303 int TempFD;
304 std::error_code EC =
305 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
306 if (EC) {
307 errs() << "Error: " << EC.message() << "\n";
308 report_fatal_error("ThinLTO: Can't get a temporary file");
309 }
310 {
311 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini001bb412016-05-16 19:11:59 +0000312 OS << OutputBuffer->getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000313 }
314 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000315 EC = sys::fs::rename(TempFilename, EntryPath);
316 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000317 sys::fs::remove(TempFilename);
318 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
319 if (EC)
320 report_fatal_error(Twine("Failed to open ") + EntryPath +
321 " to save cached entry\n");
Mehdi Amini001bb412016-05-16 19:11:59 +0000322 OS << OutputBuffer->getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000323 }
Mehdi Amini001bb412016-05-16 19:11:59 +0000324 auto ReloadedBufferOrErr = MemoryBuffer::getFile(EntryPath);
325 if (auto EC = ReloadedBufferOrErr.getError()) {
326 // FIXME diagnose
327 errs() << "error: can't reload cached file '" << EntryPath
328 << "': " << EC.message() << "\n";
329 return OutputBuffer;
330 }
331 return std::move(*ReloadedBufferOrErr);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000332 }
333};
334
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000335static std::unique_ptr<MemoryBuffer>
336ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
337 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
338 const FunctionImporter::ImportMapTy &ImportList,
339 const FunctionImporter::ExportSetTy &ExportList,
340 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
341 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000342 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000343 bool DisableCodeGen, StringRef SaveTempsDir,
344 unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000345
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000346 // "Benchmark"-like optimization: single-source case
347 bool SingleModule = (ModuleMap.size() == 1);
348
349 if (!SingleModule) {
350 promoteModule(TheModule, Index);
351
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000352 // Apply summary-based LinkOnce/Weak resolution decisions.
353 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000354
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000355 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000356 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000357 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000358
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000359 // Be friendly and don't nuke totally the module when the client didn't
360 // supply anything to preserve.
361 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
362 // Apply summary-based internalization decisions.
363 thinLTOInternalizeModule(TheModule, DefinedGlobals);
364 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000365
366 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000367 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000368
369 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000370 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000371
372 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000373 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000374 }
375
376 optimizeModule(TheModule, TM);
377
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000378 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000379
Mehdi Amini43b657b2016-04-01 06:47:02 +0000380 if (DisableCodeGen) {
381 // Configured to stop before CodeGen, serialize the bitcode and return.
382 SmallVector<char, 128> OutputBuffer;
383 {
384 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000385 ProfileSummaryInfo PSI(TheModule);
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000386 auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000387 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000388 }
389 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
390 }
391
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000392 return codegenModule(TheModule, TM);
393}
394
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000395/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
396/// for caching, and in the \p Index for application during the ThinLTO
397/// backends. This is needed for correctness for exported symbols (ensure
398/// at least one copy kept) and a compile-time optimization (to drop duplicate
399/// copies when possible).
400static void resolveWeakForLinkerInIndex(
401 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000402 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
403 &ResolvedODR) {
404
405 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
406 computePrevailingCopies(Index, PrevailingCopy);
407
408 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
409 const auto &Prevailing = PrevailingCopy.find(GUID);
410 // Not in map means that there was only one copy, which must be prevailing.
411 if (Prevailing == PrevailingCopy.end())
412 return true;
413 return Prevailing->second == S;
414 };
415
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000416 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
417 GlobalValue::GUID GUID,
418 GlobalValue::LinkageTypes NewLinkage) {
419 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
420 };
421
Peter Collingbourne73589f32016-07-07 18:31:51 +0000422 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000423}
424
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000425// Initialize the TargetMachine builder for a given Triple
426static void initTMBuilder(TargetMachineBuilder &TMBuilder,
427 const Triple &TheTriple) {
428 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
429 // FIXME this looks pretty terrible...
430 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
431 if (TheTriple.getArch() == llvm::Triple::x86_64)
432 TMBuilder.MCpu = "core2";
433 else if (TheTriple.getArch() == llvm::Triple::x86)
434 TMBuilder.MCpu = "yonah";
435 else if (TheTriple.getArch() == llvm::Triple::aarch64)
436 TMBuilder.MCpu = "cyclone";
437 }
438 TMBuilder.TheTriple = std::move(TheTriple);
439}
440
441} // end anonymous namespace
442
443void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
444 MemoryBufferRef Buffer(Data, Identifier);
445 if (Modules.empty()) {
446 // First module added, so initialize the triple and some options
447 LLVMContext Context;
448 Triple TheTriple(getBitcodeTargetTriple(Buffer, Context));
449 initTMBuilder(TMBuilder, Triple(TheTriple));
450 }
451#ifndef NDEBUG
452 else {
453 LLVMContext Context;
454 assert(TMBuilder.TheTriple.str() ==
455 getBitcodeTargetTriple(Buffer, Context) &&
456 "ThinLTO modules with different triple not supported");
457 }
458#endif
459 Modules.push_back(Buffer);
460}
461
462void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
463 PreservedSymbols.insert(Name);
464}
465
466void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000467 // FIXME: At the moment, we don't take advantage of this extra information,
468 // we're conservatively considering cross-references as preserved.
469 // CrossReferencedSymbols.insert(Name);
470 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000471}
472
473// TargetMachine factory
474std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
475 std::string ErrMsg;
476 const Target *TheTarget =
477 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
478 if (!TheTarget) {
479 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
480 }
481
482 // Use MAttr as the default set of features.
483 SubtargetFeatures Features(MAttr);
484 Features.getDefaultSubtargetFeatures(TheTriple);
485 std::string FeatureStr = Features.getString();
486 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
487 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
488 CodeModel::Default, CGOptLevel));
489}
490
491/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000492 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000493 * "thin-link".
494 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000495std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
496 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000497 uint64_t NextModuleId = 0;
498 for (auto &ModuleBuffer : Modules) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000499 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
500 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer,
Teresa Johnson6fb3f192016-04-22 01:52:00 +0000501 diagnosticHandler);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000502 if (std::error_code EC = ObjOrErr.getError()) {
503 // FIXME diagnose
Teresa Johnson26ab5772016-03-15 00:04:37 +0000504 errs() << "error: can't create ModuleSummaryIndexObjectFile for buffer: "
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000505 << EC.message() << "\n";
506 return nullptr;
507 }
508 auto Index = (*ObjOrErr)->takeIndex();
509 if (CombinedIndex) {
510 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
511 } else {
512 CombinedIndex = std::move(Index);
513 }
514 }
515 return CombinedIndex;
516}
517
518/**
519 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000520 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000521 */
522void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000523 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000524 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000525 auto ModuleIdentifier = TheModule.getModuleIdentifier();
526 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000527 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000528 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000529
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000530 // Generate import/export list
531 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
532 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
533 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
534 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000535
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000536 // Resolve LinkOnce/Weak symbols.
537 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000538 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000539
540 thinLTOResolveWeakForLinkerModule(
541 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000542
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000543 promoteModule(TheModule, Index);
544}
545
546/**
547 * Perform cross-module importing for the module identified by ModuleIdentifier.
548 */
549void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000550 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000551 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000552 auto ModuleCount = Index.modulePaths().size();
553
554 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000555 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000556 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000557
558 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000559 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
560 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000561 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
562 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000563 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
564
565 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000566}
567
568/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000569 * Compute the list of summaries needed for importing into module.
570 */
571void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
572 StringRef ModulePath, ModuleSummaryIndex &Index,
573 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
574 auto ModuleCount = Index.modulePaths().size();
575
576 // Collect for each module the list of function it defines (GUID -> Summary).
577 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
578 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
579
580 // Generate import/export list
581 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
582 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
583 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
584 ExportLists);
585
586 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000587 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000588 ModuleToSummariesForIndex);
589}
590
591/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000592 * Emit the list of files needed for importing into module.
593 */
594void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
595 StringRef OutputName,
596 ModuleSummaryIndex &Index) {
597 auto ModuleCount = Index.modulePaths().size();
598
599 // Collect for each module the list of function it defines (GUID -> Summary).
600 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
601 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
602
603 // Generate import/export list
604 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
605 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
606 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
607 ExportLists);
608
609 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000610 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000611 report_fatal_error(Twine("Failed to open ") + OutputName +
612 " to save imports lists\n");
613}
614
615/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000616 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000617 */
618void ThinLTOCodeGenerator::internalize(Module &TheModule,
619 ModuleSummaryIndex &Index) {
620 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
621 auto ModuleCount = Index.modulePaths().size();
622 auto ModuleIdentifier = TheModule.getModuleIdentifier();
623
624 // Convert the preserved symbols set from string to GUID
625 auto GUIDPreservedSymbols =
626 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
627
628 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000629 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000630 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
631
632 // Generate import/export list
633 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
634 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
635 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
636 ExportLists);
637 auto &ExportList = ExportLists[ModuleIdentifier];
638
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000639 // Be friendly and don't nuke totally the module when the client didn't
640 // supply anything to preserve.
641 if (ExportList.empty() && GUIDPreservedSymbols.empty())
642 return;
643
Mehdi Amini059464f2016-04-24 03:18:01 +0000644 // Internalization
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000645 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
646 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000647 return (ExportList != ExportLists.end() &&
648 ExportList->second.count(GUID)) ||
649 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000650 };
651 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
652 thinLTOInternalizeModule(TheModule,
653 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000654}
655
656/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000657 * Perform post-importing ThinLTO optimizations.
658 */
659void ThinLTOCodeGenerator::optimize(Module &TheModule) {
660 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000661
662 // Optimize now
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000663 optimizeModule(TheModule, *TMBuilder.create());
664}
665
666/**
667 * Perform ThinLTO CodeGen.
668 */
669std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
670 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
671 return codegenModule(TheModule, *TMBuilder.create());
672}
673
674// Main entry point for the ThinLTO processing
675void ThinLTOCodeGenerator::run() {
Mehdi Amini43b657b2016-04-01 06:47:02 +0000676 if (CodeGenOnly) {
677 // Perform only parallel codegen and return.
678 ThreadPool Pool;
679 assert(ProducedBinaries.empty() && "The generator should not be reused");
680 ProducedBinaries.resize(Modules.size());
681 int count = 0;
682 for (auto &ModuleBuffer : Modules) {
683 Pool.async([&](int count) {
684 LLVMContext Context;
685 Context.setDiscardValueNames(LTODiscardValueNames);
686
687 // Parse module now
688 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
689
690 // CodeGen
691 ProducedBinaries[count] = codegen(*TheModule);
692 }, count++);
693 }
694
695 return;
696 }
697
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000698 // Sequential linking phase
699 auto Index = linkCombinedIndex();
700
701 // Save temps: index.
702 if (!SaveTempsDir.empty()) {
703 auto SaveTempPath = SaveTempsDir + "index.bc";
704 std::error_code EC;
705 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
706 if (EC)
707 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
708 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000709 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000710 }
711
712 // Prepare the resulting object vector
713 assert(ProducedBinaries.empty() && "The generator should not be reused");
714 ProducedBinaries.resize(Modules.size());
715
716 // Prepare the module map.
717 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000718 auto ModuleCount = Modules.size();
719
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000720 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000721 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000722 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
723
Mehdi Amini01e32132016-03-26 05:40:34 +0000724 // Collect the import/export lists for all modules from the call-graph in the
725 // combined index.
726 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
727 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000728 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
729 ExportLists);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000730
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000731 // Convert the preserved symbols set from string to GUID, this is needed for
Mehdi Amini059464f2016-04-24 03:18:01 +0000732 // computing the caching hash and the internalization.
733 auto GUIDPreservedSymbols =
734 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000735
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000736 // We use a std::map here to be able to have a defined ordering when
737 // producing a hash for the cache entry.
738 // FIXME: we should be able to compute the caching hash for the entry based
739 // on the index, and nuke this map.
740 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
741
742 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
743 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000744 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000745
746 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
747 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000748 return (ExportList != ExportLists.end() &&
749 ExportList->second.count(GUID)) ||
750 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000751 };
752
753 // Use global summary-based analysis to identify symbols that can be
754 // internalized (because they aren't exported or preserved as per callback).
755 // Changes are made in the index, consumed in the ThinLTO backends.
756 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
757
Teresa Johnson141149f2016-05-24 18:44:01 +0000758 // Make sure that every module has an entry in the ExportLists and
759 // ResolvedODR maps to enable threaded access to these maps below.
760 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000761 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000762 ResolvedODR[DefinedGVSummaries.first()];
763 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000764
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000765 // Compute the ordering we will process the inputs: the rough heuristic here
766 // is to sort them per size so that the largest module get schedule as soon as
767 // possible. This is purely a compile-time optimization.
768 std::vector<int> ModulesOrdering;
769 ModulesOrdering.resize(Modules.size());
770 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
771 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
772 [&](int LeftIndex, int RightIndex) {
773 auto LSize = Modules[LeftIndex].getBufferSize();
774 auto RSize = Modules[RightIndex].getBufferSize();
775 return LSize > RSize;
776 });
777
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000778 // Parallel optimizer + codegen
779 {
780 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000781 for (auto IndexCount : ModulesOrdering) {
782 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000783 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000784 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000785 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000786
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000787 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
788
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000789 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000790 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
791 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000792 ResolvedODR[ModuleIdentifier],
793 DefinedFunctions, GUIDPreservedSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000794
795 {
796 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000797 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
798 << CacheEntry.getEntryPath() << "' for buffer " << count
799 << " " << ModuleIdentifier << "\n");
800
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000801 if (ErrOrBuffer) {
802 // Cache Hit!
803 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
804 return;
805 }
806 }
807
808 LLVMContext Context;
809 Context.setDiscardValueNames(LTODiscardValueNames);
810 Context.enableDebugTypeODRUniquing();
811
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000812 // Parse module now
813 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
814
815 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000816 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000817
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000818 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000819 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000820 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000821 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000822 ExportList, GUIDPreservedSymbols,
823 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Amini059464f2016-04-24 03:18:01 +0000824 DisableCodeGen, SaveTempsDir, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000825
Mehdi Amini001bb412016-05-16 19:11:59 +0000826 OutputBuffer = CacheEntry.write(std::move(OutputBuffer));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000827 ProducedBinaries[count] = std::move(OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000828 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000829 }
830 }
831
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000832 CachePruning(CacheOptions.Path)
833 .setPruningInterval(CacheOptions.PruningInterval)
834 .setEntryExpiration(CacheOptions.Expiration)
835 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
836 .prune();
837
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000838 // If statistics were requested, print them out now.
839 if (llvm::AreStatisticsEnabled())
840 llvm::PrintStatistics();
841}