blob: 0cb47f2b34bfe0c0fa5b6a87b2ab34de1f6994c4 [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
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000017#include "llvm/ADT/Statistic.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000018#include "llvm/ADT/StringExtras.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000019#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000020#include "llvm/Analysis/ProfileSummaryInfo.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000023#include "llvm/Bitcode/BitcodeReader.h"
24#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000025#include "llvm/Bitcode/BitcodeWriterPass.h"
Nico Weber432a3882018-04-30 14:59:11 +000026#include "llvm/Config/llvm-config.h"
Adrian Prantl981a7992017-05-20 00:00:08 +000027#include "llvm/IR/DebugInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000028#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000029#include "llvm/IR/LLVMContext.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000030#include "llvm/IR/LegacyPassManager.h"
31#include "llvm/IR/Mangler.h"
Fedor Sergeeva43fd952018-09-26 13:01:43 +000032#include "llvm/IR/PassTimingInfo.h"
Adrian Prantl981a7992017-05-20 00:00:08 +000033#include "llvm/IR/Verifier.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000034#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/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000037#include "llvm/Object/IRObjectFile.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000038#include "llvm/Support/CachePruning.h"
39#include "llvm/Support/Debug.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000040#include "llvm/Support/Error.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000041#include "llvm/Support/Path.h"
42#include "llvm/Support/SHA1.h"
Weiming Zhao79f2d092018-04-16 03:44:03 +000043#include "llvm/Support/SmallVectorMemoryBuffer.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000044#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000046#include "llvm/Support/Threading.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000047#include "llvm/Support/ToolOutputFile.h"
Peter Collingbourne942fa562017-04-13 01:26:12 +000048#include "llvm/Support/VCSRevision.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000049#include "llvm/Target/TargetMachine.h"
50#include "llvm/Transforms/IPO.h"
51#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000052#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000053#include "llvm/Transforms/IPO/PassManagerBuilder.h"
54#include "llvm/Transforms/ObjCARC.h"
55#include "llvm/Transforms/Utils/FunctionImportUtils.h"
56
Mehdi Amini819e9cd2016-05-16 19:33:07 +000057#include <numeric>
58
Andrew Ng089303d2018-07-04 14:17:10 +000059#if !defined(_MSC_VER) && !defined(__MINGW32__)
60#include <unistd.h>
61#else
62#include <io.h>
63#endif
64
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000065using namespace llvm;
66
Mehdi Amini1aafabf2016-04-16 07:02:16 +000067#define DEBUG_TYPE "thinlto"
68
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000069namespace llvm {
70// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
71extern cl::opt<bool> LTODiscardValueNames;
Mehdi Amini19f176b2016-11-19 18:20:05 +000072extern cl::opt<std::string> LTORemarksFilename;
Adam Nemet4c207a62016-12-02 17:53:56 +000073extern cl::opt<bool> LTOPassRemarksWithHotness;
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000074}
75
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000076namespace {
77
Teresa Johnsonec544c52016-10-19 17:35:01 +000078static cl::opt<int>
79 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000080
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000081// Simple helper to save temporary files for debug.
82static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
83 unsigned count, StringRef Suffix) {
84 if (TempDir.empty())
85 return;
86 // User asked to save temps, let dump the bitcode file after import.
Benjamin Kramer3a13ed62017-12-28 16:58:54 +000087 std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000088 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000089 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000090 if (EC)
91 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
92 " to save optimized bitcode\n");
Rafael Espindola6a86e252018-02-14 19:11:32 +000093 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000094}
95
Teresa Johnson4d2613f2016-05-24 17:24:25 +000096static const GlobalValueSummary *
97getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
98 // If there is any strong definition anywhere, get it.
99 auto StrongDefForLinker = llvm::find_if(
100 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
101 auto Linkage = Summary->linkage();
102 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
103 !GlobalValue::isWeakForLinker(Linkage);
104 });
105 if (StrongDefForLinker != GVSummaryList.end())
106 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000107 // Get the first *linker visible* definition for this global in the summary
108 // list.
109 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000110 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
111 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000112 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
113 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000114 // Extern templates can be emitted as available_externally.
115 if (FirstDefForLinker == GVSummaryList.end())
116 return nullptr;
117 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000118}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000119
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000120// Populate map of GUID to the prevailing copy for any multiply defined
121// symbols. Currently assume first copy is prevailing, or any strong
122// definition. Can be refined with Linker information in the future.
123static void computePrevailingCopies(
124 const ModuleSummaryIndex &Index,
125 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000126 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
127 return GVSummaryList.size() > 1;
128 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000129
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000130 for (auto &I : Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000131 if (HasMultipleCopies(I.second.SummaryList))
132 PrevailingCopy[I.first] =
133 getFirstDefinitionForLinker(I.second.SummaryList);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000134 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000135}
136
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000137static StringMap<MemoryBufferRef>
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000138generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000139 StringMap<MemoryBufferRef> ModuleMap;
140 for (auto &ModuleBuffer : Modules) {
141 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
142 ModuleMap.end() &&
143 "Expect unique Buffer Identifier");
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000144 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000145 }
146 return ModuleMap;
147}
148
Teresa Johnson26ab5772016-03-15 00:04:37 +0000149static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000150 if (renameModuleForThinLTO(TheModule, Index))
151 report_fatal_error("renameModuleForThinLTO failed");
152}
153
Adrian Prantl981a7992017-05-20 00:00:08 +0000154namespace {
155class ThinLTODiagnosticInfo : public DiagnosticInfo {
156 const Twine &Msg;
157public:
158 ThinLTODiagnosticInfo(const Twine &DiagMsg,
159 DiagnosticSeverity Severity = DS_Error)
160 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
161 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
162};
163}
164
165/// Verify the module and strip broken debug info.
166static void verifyLoadedModule(Module &TheModule) {
167 bool BrokenDebugInfo = false;
Adrian Prantla8b2ddb2017-10-02 18:31:29 +0000168 if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
Adrian Prantl981a7992017-05-20 00:00:08 +0000169 report_fatal_error("Broken module found, compilation aborted!");
170 if (BrokenDebugInfo) {
171 TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
172 "Invalid debug info found, debug info will be stripped", DS_Warning));
173 StripDebugInfo(TheModule);
174 }
175}
176
Peter Collingbournedac43b42016-12-01 05:52:32 +0000177static std::unique_ptr<Module>
178loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000179 bool Lazy, bool IsImporting) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000180 SMDiagnostic Err;
181 Expected<std::unique_ptr<Module>> ModuleOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000182 Lazy
183 ? getLazyBitcodeModule(Buffer, Context,
184 /* ShouldLazyLoadMetadata */ true, IsImporting)
185 : parseBitcodeFile(Buffer, Context);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000186 if (!ModuleOrErr) {
187 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
188 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
189 SourceMgr::DK_Error, EIB.message());
190 Err.print("ThinLTO", errs());
191 });
192 report_fatal_error("Can't load module, abort.");
193 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000194 if (!Lazy)
195 verifyLoadedModule(*ModuleOrErr.get());
Peter Collingbournedac43b42016-12-01 05:52:32 +0000196 return std::move(ModuleOrErr.get());
197}
198
Mehdi Amini01e32132016-03-26 05:40:34 +0000199static void
200crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
201 StringMap<MemoryBufferRef> &ModuleMap,
202 const FunctionImporter::ImportMapTy &ImportList) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000203 auto Loader = [&](StringRef Identifier) {
204 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000205 /*Lazy=*/true, /*IsImporting*/ true);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000206 };
207
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000208 FunctionImporter Importer(Index, Loader);
Adrian Prantl66043792017-05-19 23:32:21 +0000209 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
Mehdi Amini83a807e2017-01-08 00:30:27 +0000210 if (!Result) {
211 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
212 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
213 SourceMgr::DK_Error, EIB.message());
214 Err.print("ThinLTO", errs());
215 });
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000216 report_fatal_error("importFunctions failed");
Mehdi Amini83a807e2017-01-08 00:30:27 +0000217 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000218 // Verify again after cross-importing.
219 verifyLoadedModule(TheModule);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000220}
221
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000222static void optimizeModule(Module &TheModule, TargetMachine &TM,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000223 unsigned OptLevel, bool Freestanding) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000224 // Populate the PassManager
225 PassManagerBuilder PMB;
226 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000227 if (Freestanding)
228 PMB.LibraryInfo->disableAllFunctions();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000229 PMB.Inliner = createFunctionInliningPass();
230 // FIXME: should get it from the bitcode?
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000231 PMB.OptLevel = OptLevel;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000232 PMB.LoopVectorize = true;
233 PMB.SLPVectorize = true;
Adrian Prantl981a7992017-05-20 00:00:08 +0000234 // Already did this in verifyLoadedModule().
235 PMB.VerifyInput = false;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000236 PMB.VerifyOutput = false;
237
238 legacy::PassManager PM;
239
240 // Add the TTI (required to inform the vectorizer about register size for
241 // instance)
242 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
243
244 // Add optimizations
245 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000246
247 PM.run(TheModule);
248}
249
Mehdi Amini059464f2016-04-24 03:18:01 +0000250// Convert the PreservedSymbols map from "Name" based to "GUID" based.
251static DenseSet<GlobalValue::GUID>
Mehdi Amini1380edf2017-02-03 07:41:43 +0000252computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
253 const Triple &TheTriple) {
254 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
255 for (auto &Entry : PreservedSymbols) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000256 StringRef Name = Entry.first();
257 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
258 Name = Name.drop_front();
Mehdi Amini1380edf2017-02-03 07:41:43 +0000259 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
Mehdi Amini059464f2016-04-24 03:18:01 +0000260 }
Mehdi Amini1380edf2017-02-03 07:41:43 +0000261 return GUIDPreservedSymbols;
Mehdi Amini059464f2016-04-24 03:18:01 +0000262}
263
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000264std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
265 TargetMachine &TM) {
266 SmallVector<char, 128> OutputBuffer;
267
268 // CodeGen
269 {
270 raw_svector_ostream OS(OutputBuffer);
271 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000272
273 // If the bitcode files contain ARC code and were compiled with optimization,
274 // the ObjCARCContractPass must be run, so do it unconditionally here.
275 PM.add(createObjCARCContractPass());
276
277 // Setup the codegen now.
Peter Collingbourne9a451142018-05-21 20:16:41 +0000278 if (TM.addPassesToEmitFile(PM, OS, nullptr, TargetMachine::CGFT_ObjectFile,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000279 /* DisableVerify */ true))
280 report_fatal_error("Failed to setup codegen");
281
282 // Run codegen now. resulting binary is in OutputBuffer.
283 PM.run(TheModule);
284 }
Weiming Zhao79f2d092018-04-16 03:44:03 +0000285 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000286}
287
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000288/// Manage caching for a single Module.
289class ModuleCacheEntry {
290 SmallString<128> EntryPath;
291
292public:
293 // Create a cache entry. This compute a unique hash for the Module considering
294 // the current list of export/import, and offer an interface to query to
295 // access the content in the cache.
296 ModuleCacheEntry(
297 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
298 const FunctionImporter::ImportMapTy &ImportList,
299 const FunctionImporter::ExportSetTy &ExportList,
300 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Eugene Leviantbf46e742018-11-16 07:08:00 +0000301 const GVSummaryMapTy &DefinedGVSummaries,
Mehdi Aminic92b6122017-01-10 00:55:47 +0000302 const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000303 bool Freestanding, const TargetMachineBuilder &TMBuilder) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000304 if (CachePath.empty())
305 return;
306
Mehdi Amini00fa1402016-10-08 04:44:18 +0000307 if (!Index.modulePaths().count(ModuleID))
308 // The module does not have an entry, it can't have a hash at all
309 return;
310
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000311 // Compute the unique hash for this entry
312 // This is based on the current compiler version, the module itself, the
313 // export list, the hash for every single module in the import list, the
314 // list of ResolvedODR for the module, and the list of preserved symbols.
315
Mehdi Aminif82bda02016-10-08 04:44:23 +0000316 // Include the hash for the current module
317 auto ModHash = Index.getModuleHash(ModuleID);
318
319 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
320 // No hash entry, no caching!
321 return;
322
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000323 SHA1 Hasher;
324
Mehdi Aminic92b6122017-01-10 00:55:47 +0000325 // Include the parts of the LTO configuration that affect code generation.
326 auto AddString = [&](StringRef Str) {
327 Hasher.update(Str);
328 Hasher.update(ArrayRef<uint8_t>{0});
329 };
330 auto AddUnsigned = [&](unsigned I) {
331 uint8_t Data[4];
332 Data[0] = I;
333 Data[1] = I >> 8;
334 Data[2] = I >> 16;
335 Data[3] = I >> 24;
336 Hasher.update(ArrayRef<uint8_t>{Data, 4});
337 };
338
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000339 // Start with the compiler revision
340 Hasher.update(LLVM_VERSION_STRING);
Peter Collingbourne942fa562017-04-13 01:26:12 +0000341#ifdef LLVM_REVISION
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000342 Hasher.update(LLVM_REVISION);
343#endif
344
Mehdi Aminic92b6122017-01-10 00:55:47 +0000345 // Hash the optimization level and the target machine settings.
346 AddString(TMBuilder.MCpu);
347 // FIXME: Hash more of Options. For now all clients initialize Options from
348 // command-line flags (which is unsupported in production), but may set
349 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
350 // DataSections and DebuggerTuning via command line flags.
351 AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
352 AddUnsigned(TMBuilder.Options.FunctionSections);
353 AddUnsigned(TMBuilder.Options.DataSections);
354 AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
355 AddString(TMBuilder.MAttr);
356 if (TMBuilder.RelocModel)
357 AddUnsigned(*TMBuilder.RelocModel);
358 AddUnsigned(TMBuilder.CGOptLevel);
359 AddUnsigned(OptLevel);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000360 AddUnsigned(Freestanding);
Mehdi Aminic92b6122017-01-10 00:55:47 +0000361
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000362 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
363 for (auto F : ExportList)
364 // The export list can impact the internalization, be conservative here
365 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
366
367 // Include the hash for every module we import functions from
368 for (auto &Entry : ImportList) {
369 auto ModHash = Index.getModuleHash(Entry.first());
370 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
Eugene Leviantbf46e742018-11-16 07:08:00 +0000371 for (auto Guid : Entry.second)
372 if (auto *GVS = dyn_cast<GlobalVarSummary>(
373 Index.getGlobalValueSummary(Guid, false)))
374 AddUnsigned(GVS->isReadOnly());
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000375 }
376
377 // Include the hash for the resolved ODR.
378 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000379 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000380 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000381 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000382 sizeof(GlobalValue::LinkageTypes)));
383 }
384
385 // Include the hash for the preserved symbols.
386 for (auto &Entry : PreservedSymbols) {
Eugene Leviantbf46e742018-11-16 07:08:00 +0000387 if (DefinedGVSummaries.count(Entry))
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000388 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000389 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000390 }
391
Eugene Leviantbf46e742018-11-16 07:08:00 +0000392 for (auto &Entry : DefinedGVSummaries)
393 if (auto *GVS = dyn_cast<GlobalVarSummary>(Entry.second))
394 AddUnsigned(GVS->isReadOnly());
395
Peter Collingbourne25a17ba2017-03-20 16:41:57 +0000396 // This choice of file name allows the cache to be pruned (see pruneCache()
397 // in include/llvm/Support/CachePruning.h).
398 sys::path::append(EntryPath, CachePath,
399 "llvmcache-" + toHex(Hasher.result()));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000400 }
401
Mehdi Amini059464f2016-04-24 03:18:01 +0000402 // Access the path to this entry in the cache.
403 StringRef getEntryPath() { return EntryPath; }
404
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000405 // Try loading the buffer for this cache entry.
406 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
407 if (EntryPath.empty())
408 return std::error_code();
Andrew Ng089303d2018-07-04 14:17:10 +0000409 int FD;
410 SmallString<64> ResultPath;
411 std::error_code EC = sys::fs::openFileForRead(
412 Twine(EntryPath), FD, sys::fs::OF_UpdateAtime, &ResultPath);
413 if (EC)
414 return EC;
415 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
416 MemoryBuffer::getOpenFile(FD, EntryPath,
417 /*FileSize*/ -1,
418 /*RequiresNullTerminator*/ false);
419 close(FD);
420 return MBOrErr;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000421 }
422
423 // Cache the Produced object file
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000424 void write(const MemoryBuffer &OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000425 if (EntryPath.empty())
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000426 return;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000427
428 // Write to a temporary to avoid race condition
429 SmallString<128> TempFilename;
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000430 SmallString<128> CachePath(EntryPath);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000431 int TempFD;
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000432 llvm::sys::path::remove_filename(CachePath);
433 sys::path::append(TempFilename, CachePath, "Thin-%%%%%%.tmp.o");
Fangrui Songf78650a2018-07-30 19:41:25 +0000434 std::error_code EC =
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000435 sys::fs::createUniqueFile(TempFilename, TempFD, TempFilename);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000436 if (EC) {
437 errs() << "Error: " << EC.message() << "\n";
438 report_fatal_error("ThinLTO: Can't get a temporary file");
439 }
440 {
441 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000442 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000443 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000444 // Rename temp file to final destination; rename is atomic
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000445 EC = sys::fs::rename(TempFilename, EntryPath);
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000446 if (EC)
Mehdi Aminib02139d2016-05-14 05:16:35 +0000447 sys::fs::remove(TempFilename);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000448 }
449};
450
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000451static std::unique_ptr<MemoryBuffer>
452ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
453 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
454 const FunctionImporter::ImportMapTy &ImportList,
455 const FunctionImporter::ExportSetTy &ExportList,
456 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
457 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000458 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000459 bool DisableCodeGen, StringRef SaveTempsDir,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000460 bool Freestanding, unsigned OptLevel, unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000461
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000462 // "Benchmark"-like optimization: single-source case
463 bool SingleModule = (ModuleMap.size() == 1);
464
465 if (!SingleModule) {
466 promoteModule(TheModule, Index);
467
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000468 // Apply summary-based prevailing-symbol resolution decisions.
469 thinLTOResolvePrevailingInModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000470
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000471 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000472 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000473 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000474
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000475 // Be friendly and don't nuke totally the module when the client didn't
476 // supply anything to preserve.
477 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
478 // Apply summary-based internalization decisions.
479 thinLTOInternalizeModule(TheModule, DefinedGlobals);
480 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000481
482 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000483 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000484
485 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000486 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000487
488 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000489 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000490 }
491
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000492 optimizeModule(TheModule, TM, OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000493
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000494 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000495
Mehdi Amini43b657b2016-04-01 06:47:02 +0000496 if (DisableCodeGen) {
497 // Configured to stop before CodeGen, serialize the bitcode and return.
498 SmallVector<char, 128> OutputBuffer;
499 {
500 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000501 ProfileSummaryInfo PSI(TheModule);
Teresa Johnson94624ac2017-05-10 18:52:16 +0000502 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000503 WriteBitcodeToFile(TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000504 }
Weiming Zhao79f2d092018-04-16 03:44:03 +0000505 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
Mehdi Amini43b657b2016-04-01 06:47:02 +0000506 }
507
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000508 return codegenModule(TheModule, TM);
509}
510
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000511/// Resolve prevailing symbols. Record resolutions in the \p ResolvedODR map
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000512/// for caching, and in the \p Index for application during the ThinLTO
513/// backends. This is needed for correctness for exported symbols (ensure
514/// at least one copy kept) and a compile-time optimization (to drop duplicate
515/// copies when possible).
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000516static void resolvePrevailingInIndex(
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000517 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000518 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
519 &ResolvedODR) {
520
521 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
522 computePrevailingCopies(Index, PrevailingCopy);
523
524 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
525 const auto &Prevailing = PrevailingCopy.find(GUID);
526 // Not in map means that there was only one copy, which must be prevailing.
527 if (Prevailing == PrevailingCopy.end())
528 return true;
529 return Prevailing->second == S;
530 };
531
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000532 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
533 GlobalValue::GUID GUID,
534 GlobalValue::LinkageTypes NewLinkage) {
535 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
536 };
537
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000538 thinLTOResolvePrevailingInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000539}
540
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000541// Initialize the TargetMachine builder for a given Triple
542static void initTMBuilder(TargetMachineBuilder &TMBuilder,
543 const Triple &TheTriple) {
544 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
545 // FIXME this looks pretty terrible...
546 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
547 if (TheTriple.getArch() == llvm::Triple::x86_64)
548 TMBuilder.MCpu = "core2";
549 else if (TheTriple.getArch() == llvm::Triple::x86)
550 TMBuilder.MCpu = "yonah";
551 else if (TheTriple.getArch() == llvm::Triple::aarch64)
552 TMBuilder.MCpu = "cyclone";
553 }
554 TMBuilder.TheTriple = std::move(TheTriple);
555}
556
557} // end anonymous namespace
558
559void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
Johan Engelendcebe4f2017-09-17 18:11:26 +0000560 ThinLTOBuffer Buffer(Data, Identifier);
Akira Hatanakab10bff12017-05-18 03:52:29 +0000561 LLVMContext Context;
562 StringRef TripleStr;
563 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
564 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
565
566 if (TripleOrErr)
567 TripleStr = *TripleOrErr;
568
569 Triple TheTriple(TripleStr);
570
571 if (Modules.empty())
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000572 initTMBuilder(TMBuilder, Triple(TheTriple));
Akira Hatanakab10bff12017-05-18 03:52:29 +0000573 else if (TMBuilder.TheTriple != TheTriple) {
574 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
575 report_fatal_error("ThinLTO modules with incompatible triples not "
576 "supported");
577 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000578 }
Akira Hatanakab10bff12017-05-18 03:52:29 +0000579
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000580 Modules.push_back(Buffer);
581}
582
583void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
584 PreservedSymbols.insert(Name);
585}
586
587void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000588 // FIXME: At the moment, we don't take advantage of this extra information,
589 // we're conservatively considering cross-references as preserved.
590 // CrossReferencedSymbols.insert(Name);
591 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000592}
593
594// TargetMachine factory
595std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
596 std::string ErrMsg;
597 const Target *TheTarget =
598 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
599 if (!TheTarget) {
600 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
601 }
602
603 // Use MAttr as the default set of features.
604 SubtargetFeatures Features(MAttr);
605 Features.getDefaultSubtargetFeatures(TheTriple);
606 std::string FeatureStr = Features.getString();
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000607
Rafael Espindola79e238a2017-08-03 02:16:21 +0000608 return std::unique_ptr<TargetMachine>(
609 TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options,
610 RelocModel, None, CGOptLevel));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000611}
612
613/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000614 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000615 * "thin-link".
616 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000617std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000618 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
Teresa Johnson4ffc3e72018-06-06 22:22:01 +0000619 llvm::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000620 uint64_t NextModuleId = 0;
621 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000622 if (Error Err = readModuleSummaryIndex(ModuleBuffer.getMemBuffer(),
623 *CombinedIndex, NextModuleId++)) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000624 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000625 logAllUnhandledErrors(
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000626 std::move(Err), errs(),
Peter Collingbournec15d60b2017-05-01 20:42:32 +0000627 "error: can't create module summary index for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000628 return nullptr;
629 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000630 }
631 return CombinedIndex;
632}
633
George Rimar2421b6f2018-01-17 10:33:05 +0000634static void internalizeAndPromoteInIndex(
635 const StringMap<FunctionImporter::ExportSetTy> &ExportLists,
636 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
637 ModuleSummaryIndex &Index) {
638 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
639 const auto &ExportList = ExportLists.find(ModuleIdentifier);
640 return (ExportList != ExportLists.end() &&
641 ExportList->second.count(GUID)) ||
642 GUIDPreservedSymbols.count(GUID);
643 };
644
645 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
646}
647
George Rimareaf51722018-01-29 08:03:30 +0000648static void computeDeadSymbolsInIndex(
649 ModuleSummaryIndex &Index,
650 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
651 // We have no symbols resolution available. And can't do any better now in the
652 // case where the prevailing symbol is in a native object. It can be refined
653 // with linker information in the future.
654 auto isPrevailing = [&](GlobalValue::GUID G) {
655 return PrevailingType::Unknown;
656 };
Eugene Leviantbf46e742018-11-16 07:08:00 +0000657 computeDeadSymbolsWithConstProp(Index, GUIDPreservedSymbols, isPrevailing,
658 /* ImportEnabled = */ true);
George Rimareaf51722018-01-29 08:03:30 +0000659}
660
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000661/**
662 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000663 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000664 */
665void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000666 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000667 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000668 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000669
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000670 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000671 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000672 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000673
Teresa Johnson6c475a72017-01-05 21:34:18 +0000674 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000675 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000676 PreservedSymbols, Triple(TheModule.getTargetTriple()));
677
678 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000679 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000680
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000681 // Generate import/export list
682 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
683 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
684 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000685 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000686
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000687 // Resolve prevailing symbols
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000688 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000689 resolvePrevailingInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000690
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000691 thinLTOResolvePrevailingInModule(
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000692 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000693
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000694 // Promote the exported values in the index, so that they are promoted
695 // in the module.
George Rimar2421b6f2018-01-17 10:33:05 +0000696 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000697
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000698 promoteModule(TheModule, Index);
699}
700
701/**
702 * Perform cross-module importing for the module identified by ModuleIdentifier.
703 */
704void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000705 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000706 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000707 auto ModuleCount = Index.modulePaths().size();
708
709 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000710 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000711 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000712
Teresa Johnson6c475a72017-01-05 21:34:18 +0000713 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000714 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000715 PreservedSymbols, Triple(TheModule.getTargetTriple()));
716
717 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000718 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000719
Mehdi Amini01e32132016-03-26 05:40:34 +0000720 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000721 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
722 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000723 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000724 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000725 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
726
727 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000728}
729
730/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000731 * Compute the list of summaries needed for importing into module.
732 */
733void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
734 StringRef ModulePath, ModuleSummaryIndex &Index,
735 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
736 auto ModuleCount = Index.modulePaths().size();
737
738 // Collect for each module the list of function it defines (GUID -> Summary).
739 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
740 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
741
742 // Generate import/export list
743 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
744 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
745 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
746 ExportLists);
747
748 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000749 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000750 ModuleToSummariesForIndex);
751}
752
753/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000754 * Emit the list of files needed for importing into module.
755 */
756void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
757 StringRef OutputName,
758 ModuleSummaryIndex &Index) {
759 auto ModuleCount = Index.modulePaths().size();
760
761 // Collect for each module the list of function it defines (GUID -> Summary).
762 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
763 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
764
765 // Generate import/export list
766 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
767 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
768 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
769 ExportLists);
770
Teresa Johnsonc0320ef2018-07-10 20:06:04 +0000771 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
772 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
773 ImportLists[ModulePath],
774 ModuleToSummariesForIndex);
775
Teresa Johnson8570fe42016-05-10 15:54:09 +0000776 std::error_code EC;
Teresa Johnsonc0320ef2018-07-10 20:06:04 +0000777 if ((EC =
778 EmitImportsFiles(ModulePath, OutputName, ModuleToSummariesForIndex)))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000779 report_fatal_error(Twine("Failed to open ") + OutputName +
780 " to save imports lists\n");
781}
782
783/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000784 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000785 */
786void ThinLTOCodeGenerator::internalize(Module &TheModule,
787 ModuleSummaryIndex &Index) {
788 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
789 auto ModuleCount = Index.modulePaths().size();
790 auto ModuleIdentifier = TheModule.getModuleIdentifier();
791
792 // Convert the preserved symbols set from string to GUID
793 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000794 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Amini059464f2016-04-24 03:18:01 +0000795
796 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000797 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000798 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
799
Teresa Johnson6c475a72017-01-05 21:34:18 +0000800 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000801 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000802
Mehdi Amini059464f2016-04-24 03:18:01 +0000803 // Generate import/export list
804 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
805 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
806 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000807 ExportLists);
Mehdi Amini059464f2016-04-24 03:18:01 +0000808 auto &ExportList = ExportLists[ModuleIdentifier];
809
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000810 // Be friendly and don't nuke totally the module when the client didn't
811 // supply anything to preserve.
812 if (ExportList.empty() && GUIDPreservedSymbols.empty())
813 return;
814
Mehdi Amini059464f2016-04-24 03:18:01 +0000815 // Internalization
George Rimar2421b6f2018-01-17 10:33:05 +0000816 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000817 thinLTOInternalizeModule(TheModule,
818 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000819}
820
821/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000822 * Perform post-importing ThinLTO optimizations.
823 */
824void ThinLTOCodeGenerator::optimize(Module &TheModule) {
825 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000826
827 // Optimize now
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000828 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000829}
830
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000831/// Write out the generated object file, either from CacheEntryPath or from
832/// OutputBuffer, preferring hard-link when possible.
833/// Returns the path to the generated file in SavedObjectsDirectoryPath.
834static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
835 StringRef SavedObjectsDirectoryPath,
836 const MemoryBuffer &OutputBuffer) {
837 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
838 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
839 OutputPath.c_str(); // Ensure the string is null terminated.
840 if (sys::fs::exists(OutputPath))
841 sys::fs::remove(OutputPath);
842
843 // We don't return a memory buffer to the linker, just a list of files.
844 if (!CacheEntryPath.empty()) {
845 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
846 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
847 if (!Err)
848 return OutputPath.str();
849 // Hard linking failed, try to copy.
850 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
851 if (!Err)
852 return OutputPath.str();
853 // Copy failed (could be because the CacheEntry was removed from the cache
854 // in the meantime by another process), fall back and try to write down the
855 // buffer to the output.
856 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
857 << "' to '" << OutputPath << "'\n";
858 }
859 // No cache entry, just write out the buffer.
860 std::error_code Err;
861 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
862 if (Err)
863 report_fatal_error("Can't open output '" + OutputPath + "'\n");
864 OS << OutputBuffer.getBuffer();
865 return OutputPath.str();
866}
867
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000868// Main entry point for the ThinLTO processing
869void ThinLTOCodeGenerator::run() {
Mehdi Aminib2990462017-01-20 22:45:34 +0000870 // Prepare the resulting object vector
871 assert(ProducedBinaries.empty() && "The generator should not be reused");
872 if (SavedObjectsDirectoryPath.empty())
873 ProducedBinaries.resize(Modules.size());
874 else {
875 sys::fs::create_directories(SavedObjectsDirectoryPath);
876 bool IsDir;
877 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
878 if (!IsDir)
879 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
880 ProducedBinaryFiles.resize(Modules.size());
881 }
882
Mehdi Amini43b657b2016-04-01 06:47:02 +0000883 if (CodeGenOnly) {
884 // Perform only parallel codegen and return.
885 ThreadPool Pool;
Mehdi Amini43b657b2016-04-01 06:47:02 +0000886 int count = 0;
887 for (auto &ModuleBuffer : Modules) {
888 Pool.async([&](int count) {
889 LLVMContext Context;
890 Context.setDiscardValueNames(LTODiscardValueNames);
891
892 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000893 auto TheModule =
894 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
895 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000896
897 // CodeGen
Steven Wucf902032018-09-04 22:54:17 +0000898 auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create());
Mehdi Aminib2990462017-01-20 22:45:34 +0000899 if (SavedObjectsDirectoryPath.empty())
900 ProducedBinaries[count] = std::move(OutputBuffer);
901 else
902 ProducedBinaryFiles[count] = writeGeneratedObject(
903 count, "", SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000904 }, count++);
905 }
906
907 return;
908 }
909
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000910 // Sequential linking phase
911 auto Index = linkCombinedIndex();
912
913 // Save temps: index.
914 if (!SaveTempsDir.empty()) {
915 auto SaveTempPath = SaveTempsDir + "index.bc";
916 std::error_code EC;
917 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
918 if (EC)
919 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
920 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000921 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000922 }
923
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000924
925 // Prepare the module map.
926 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000927 auto ModuleCount = Modules.size();
928
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000929 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000930 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000931 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
932
Teresa Johnson6c475a72017-01-05 21:34:18 +0000933 // Convert the preserved symbols set from string to GUID, this is needed for
934 // computing the caching hash and the internalization.
935 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000936 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000937
938 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000939 computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000940
Mehdi Amini01e32132016-03-26 05:40:34 +0000941 // Collect the import/export lists for all modules from the call-graph in the
942 // combined index.
943 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
944 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000945 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000946 ExportLists);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000947
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000948 // We use a std::map here to be able to have a defined ordering when
949 // producing a hash for the cache entry.
950 // FIXME: we should be able to compute the caching hash for the entry based
951 // on the index, and nuke this map.
952 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
953
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000954 // Resolve prevailing symbols, this has to be computed early because it
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000955 // impacts the caching.
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000956 resolvePrevailingInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000957
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000958 // Use global summary-based analysis to identify symbols that can be
959 // internalized (because they aren't exported or preserved as per callback).
960 // Changes are made in the index, consumed in the ThinLTO backends.
George Rimar2421b6f2018-01-17 10:33:05 +0000961 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, *Index);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000962
Steven Wuec53c892018-09-14 19:38:21 +0000963 // Make sure that every module has an entry in the ExportLists, ImportList,
964 // GVSummary and ResolvedODR maps to enable threaded access to these maps
965 // below.
966 for (auto &Module : Modules) {
967 auto ModuleIdentifier = Module.getBufferIdentifier();
968 ExportLists[ModuleIdentifier];
969 ImportLists[ModuleIdentifier];
970 ResolvedODR[ModuleIdentifier];
971 ModuleToDefinedGVSummaries[ModuleIdentifier];
Teresa Johnson141149f2016-05-24 18:44:01 +0000972 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000973
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000974 // Compute the ordering we will process the inputs: the rough heuristic here
975 // is to sort them per size so that the largest module get schedule as soon as
976 // possible. This is purely a compile-time optimization.
977 std::vector<int> ModulesOrdering;
978 ModulesOrdering.resize(Modules.size());
979 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
Fangrui Song0cac7262018-09-27 02:13:45 +0000980 llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) {
981 auto LSize = Modules[LeftIndex].getBuffer().size();
982 auto RSize = Modules[RightIndex].getBuffer().size();
983 return LSize > RSize;
984 });
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000985
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000986 // Parallel optimizer + codegen
987 {
988 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000989 for (auto IndexCount : ModulesOrdering) {
990 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000991 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000992 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000993 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000994
Eugene Leviantbf46e742018-11-16 07:08:00 +0000995 auto &DefinedGVSummaries = ModuleToDefinedGVSummaries[ModuleIdentifier];
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000996
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000997 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000998 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
999 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +00001000 ResolvedODR[ModuleIdentifier],
Eugene Leviantbf46e742018-11-16 07:08:00 +00001001 DefinedGVSummaries, GUIDPreservedSymbols,
Mehdi Aminib5a46c12017-03-28 18:55:44 +00001002 OptLevel, Freestanding, TMBuilder);
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001003 auto CacheEntryPath = CacheEntry.getEntryPath();
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001004
1005 {
1006 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001007 LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss")
1008 << " '" << CacheEntryPath << "' for buffer "
1009 << count << " " << ModuleIdentifier << "\n");
Mehdi Amini059464f2016-04-24 03:18:01 +00001010
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001011 if (ErrOrBuffer) {
1012 // Cache Hit!
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001013 if (SavedObjectsDirectoryPath.empty())
1014 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
1015 else
1016 ProducedBinaryFiles[count] = writeGeneratedObject(
1017 count, CacheEntryPath, SavedObjectsDirectoryPath,
1018 *ErrOrBuffer.get());
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001019 return;
1020 }
1021 }
1022
1023 LLVMContext Context;
1024 Context.setDiscardValueNames(LTODiscardValueNames);
1025 Context.enableDebugTypeODRUniquing();
Davide Italiano690ed9d2017-02-10 23:49:38 +00001026 auto DiagFileOrErr = lto::setupOptimizationRemarks(
Bob Haarmanfb2d3422018-03-08 01:13:10 +00001027 Context, LTORemarksFilename, LTOPassRemarksWithHotness, count);
Mehdi Amini19f176b2016-11-19 18:20:05 +00001028 if (!DiagFileOrErr) {
1029 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
1030 report_fatal_error("ThinLTO: Can't get an output file for the "
1031 "remarks");
1032 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001033
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001034 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +00001035 auto TheModule =
1036 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
1037 /*IsImporting*/ false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001038
1039 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +00001040 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001041
Mehdi Amini1aafabf2016-04-16 07:02:16 +00001042 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +00001043 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001044 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +00001045 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +00001046 ExportList, GUIDPreservedSymbols,
1047 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Aminib5a46c12017-03-28 18:55:44 +00001048 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001049
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001050 // Commit to the cache (if enabled)
1051 CacheEntry.write(*OutputBuffer);
1052
1053 if (SavedObjectsDirectoryPath.empty()) {
1054 // We need to generated a memory buffer for the linker.
1055 if (!CacheEntryPath.empty()) {
Fangrui Songf78650a2018-07-30 19:41:25 +00001056 // When cache is enabled, reload from the cache if possible.
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +00001057 // Releasing the buffer from the heap and reloading it from the
Fangrui Songf78650a2018-07-30 19:41:25 +00001058 // cache file with mmap helps us to lower memory pressure.
1059 // The freed memory can be used for the next input file.
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +00001060 // The final binary link will read from the VFS cache (hopefully!)
1061 // or from disk (if the memory pressure was too high).
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001062 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1063 if (auto EC = ReloadedBufferOrErr.getError()) {
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +00001064 // On error, keep the preexisting buffer and print a diagnostic.
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001065 errs() << "error: can't reload cached file '" << CacheEntryPath
1066 << "': " << EC.message() << "\n";
1067 } else {
1068 OutputBuffer = std::move(*ReloadedBufferOrErr);
1069 }
1070 }
1071 ProducedBinaries[count] = std::move(OutputBuffer);
1072 return;
1073 }
1074 ProducedBinaryFiles[count] = writeGeneratedObject(
1075 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001076 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001077 }
1078 }
1079
Peter Collingbournecead56f2017-03-15 22:54:18 +00001080 pruneCache(CacheOptions.Path, CacheOptions.Policy);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001081
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001082 // If statistics were requested, print them out now.
1083 if (llvm::AreStatisticsEnabled())
1084 llvm::PrintStatistics();
James Henderson852f6fd2017-05-16 09:43:21 +00001085 reportAndResetTimings();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001086}