blob: a14b86179d6e369fd67dcc54b0eda57daa3bb152 [file] [log] [blame]
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001//===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Thin Link Time Optimization library. This library is
11// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Peter Collingbourne5c732202016-07-14 21:21:16 +000015#include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000016
Mehdi Aminif95f77a2016-04-21 05:54:23 +000017#ifdef HAVE_LLVM_REVISION
18#include "LLVMLTORevision.h"
19#endif
Mehdi Amini059464f2016-04-24 03:18:01 +000020
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000021#include "llvm/ADT/Statistic.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000022#include "llvm/ADT/StringExtras.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000023#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000024#include "llvm/Analysis/ProfileSummaryInfo.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000025#include "llvm/Analysis/TargetLibraryInfo.h"
26#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000027#include "llvm/Bitcode/BitcodeReader.h"
28#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000029#include "llvm/Bitcode/BitcodeWriterPass.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000030#include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000031#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000032#include "llvm/IR/LLVMContext.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000033#include "llvm/IR/LegacyPassManager.h"
34#include "llvm/IR/Mangler.h"
35#include "llvm/IRReader/IRReader.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000036#include "llvm/LTO/LTO.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000037#include "llvm/Linker/Linker.h"
38#include "llvm/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000039#include "llvm/Object/IRObjectFile.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000040#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000041#include "llvm/Support/CachePruning.h"
42#include "llvm/Support/Debug.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000043#include "llvm/Support/Error.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000044#include "llvm/Support/Path.h"
45#include "llvm/Support/SHA1.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000046#include "llvm/Support/TargetRegistry.h"
47#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000048#include "llvm/Support/Threading.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000049#include "llvm/Support/ToolOutputFile.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000050#include "llvm/Target/TargetMachine.h"
51#include "llvm/Transforms/IPO.h"
52#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000053#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000054#include "llvm/Transforms/IPO/PassManagerBuilder.h"
55#include "llvm/Transforms/ObjCARC.h"
56#include "llvm/Transforms/Utils/FunctionImportUtils.h"
57
Mehdi Amini819e9cd2016-05-16 19:33:07 +000058#include <numeric>
59
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000060using namespace llvm;
61
Mehdi Amini1aafabf2016-04-16 07:02:16 +000062#define DEBUG_TYPE "thinlto"
63
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000064namespace llvm {
65// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
66extern cl::opt<bool> LTODiscardValueNames;
Mehdi Amini19f176b2016-11-19 18:20:05 +000067extern cl::opt<std::string> LTORemarksFilename;
Adam Nemet4c207a62016-12-02 17:53:56 +000068extern cl::opt<bool> LTOPassRemarksWithHotness;
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000069}
70
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000071namespace {
72
Teresa Johnsonec544c52016-10-19 17:35:01 +000073static cl::opt<int>
74 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000075
Mehdi Amini19f176b2016-11-19 18:20:05 +000076Expected<std::unique_ptr<tool_output_file>>
77setupOptimizationRemarks(LLVMContext &Ctx, int Count) {
Adam Nemet4c207a62016-12-02 17:53:56 +000078 if (LTOPassRemarksWithHotness)
79 Ctx.setDiagnosticHotnessRequested(true);
80
Mehdi Amini19f176b2016-11-19 18:20:05 +000081 if (LTORemarksFilename.empty())
82 return nullptr;
83
84 std::string FileName =
85 LTORemarksFilename + ".thin." + llvm::utostr(Count) + ".yaml";
86 std::error_code EC;
87 auto DiagnosticOutputFile =
88 llvm::make_unique<tool_output_file>(FileName, EC, sys::fs::F_None);
89 if (EC)
90 return errorCodeToError(EC);
91 Ctx.setDiagnosticsOutputFile(
92 llvm::make_unique<yaml::Output>(DiagnosticOutputFile->os()));
93 DiagnosticOutputFile->keep();
94 return std::move(DiagnosticOutputFile);
95}
96
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000097// Simple helper to save temporary files for debug.
98static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
99 unsigned count, StringRef Suffix) {
100 if (TempDir.empty())
101 return;
102 // User asked to save temps, let dump the bitcode file after import.
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000103 std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000104 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000105 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000106 if (EC)
107 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
108 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +0000109 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000110}
111
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000112static const GlobalValueSummary *
113getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
114 // If there is any strong definition anywhere, get it.
115 auto StrongDefForLinker = llvm::find_if(
116 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
117 auto Linkage = Summary->linkage();
118 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
119 !GlobalValue::isWeakForLinker(Linkage);
120 });
121 if (StrongDefForLinker != GVSummaryList.end())
122 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000123 // Get the first *linker visible* definition for this global in the summary
124 // list.
125 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000126 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
127 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000128 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
129 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000130 // Extern templates can be emitted as available_externally.
131 if (FirstDefForLinker == GVSummaryList.end())
132 return nullptr;
133 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000134}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000135
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000136// Populate map of GUID to the prevailing copy for any multiply defined
137// symbols. Currently assume first copy is prevailing, or any strong
138// definition. Can be refined with Linker information in the future.
139static void computePrevailingCopies(
140 const ModuleSummaryIndex &Index,
141 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000142 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
143 return GVSummaryList.size() > 1;
144 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000145
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000146 for (auto &I : Index) {
147 if (HasMultipleCopies(I.second))
148 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000149 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000150}
151
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000152static StringMap<MemoryBufferRef>
153generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
154 StringMap<MemoryBufferRef> ModuleMap;
155 for (auto &ModuleBuffer : Modules) {
156 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
157 ModuleMap.end() &&
158 "Expect unique Buffer Identifier");
159 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
160 }
161 return ModuleMap;
162}
163
Teresa Johnson26ab5772016-03-15 00:04:37 +0000164static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000165 if (renameModuleForThinLTO(TheModule, Index))
166 report_fatal_error("renameModuleForThinLTO failed");
167}
168
Peter Collingbournedac43b42016-12-01 05:52:32 +0000169static std::unique_ptr<Module>
170loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000171 bool Lazy, bool IsImporting) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000172 SMDiagnostic Err;
173 Expected<std::unique_ptr<Module>> ModuleOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000174 Lazy
175 ? getLazyBitcodeModule(Buffer, Context,
176 /* ShouldLazyLoadMetadata */ true, IsImporting)
177 : parseBitcodeFile(Buffer, Context);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000178 if (!ModuleOrErr) {
179 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
180 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
181 SourceMgr::DK_Error, EIB.message());
182 Err.print("ThinLTO", errs());
183 });
184 report_fatal_error("Can't load module, abort.");
185 }
186 return std::move(ModuleOrErr.get());
187}
188
Mehdi Amini01e32132016-03-26 05:40:34 +0000189static void
190crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
191 StringMap<MemoryBufferRef> &ModuleMap,
192 const FunctionImporter::ImportMapTy &ImportList) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000193 auto Loader = [&](StringRef Identifier) {
194 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000195 /*Lazy=*/true, /*IsImporting*/ true);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000196 };
197
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000198 FunctionImporter Importer(Index, Loader);
Mehdi Amini83a807e2017-01-08 00:30:27 +0000199 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
200 if (!Result) {
201 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
202 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
203 SourceMgr::DK_Error, EIB.message());
204 Err.print("ThinLTO", errs());
205 });
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000206 report_fatal_error("importFunctions failed");
Mehdi Amini83a807e2017-01-08 00:30:27 +0000207 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000208}
209
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000210static void optimizeModule(Module &TheModule, TargetMachine &TM,
211 unsigned OptLevel) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000212 // Populate the PassManager
213 PassManagerBuilder PMB;
214 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
215 PMB.Inliner = createFunctionInliningPass();
216 // FIXME: should get it from the bitcode?
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000217 PMB.OptLevel = OptLevel;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000218 PMB.LoopVectorize = true;
219 PMB.SLPVectorize = true;
220 PMB.VerifyInput = true;
221 PMB.VerifyOutput = false;
222
223 legacy::PassManager PM;
224
225 // Add the TTI (required to inform the vectorizer about register size for
226 // instance)
227 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
228
229 // Add optimizations
230 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000231
232 PM.run(TheModule);
233}
234
Mehdi Amini059464f2016-04-24 03:18:01 +0000235// Convert the PreservedSymbols map from "Name" based to "GUID" based.
236static DenseSet<GlobalValue::GUID>
237computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
238 const Triple &TheTriple) {
239 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
240 for (auto &Entry : PreservedSymbols) {
241 StringRef Name = Entry.first();
242 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
243 Name = Name.drop_front();
244 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
245 }
246 return GUIDPreservedSymbols;
247}
248
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000249std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
250 TargetMachine &TM) {
251 SmallVector<char, 128> OutputBuffer;
252
253 // CodeGen
254 {
255 raw_svector_ostream OS(OutputBuffer);
256 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000257
258 // If the bitcode files contain ARC code and were compiled with optimization,
259 // the ObjCARCContractPass must be run, so do it unconditionally here.
260 PM.add(createObjCARCContractPass());
261
262 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000263 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
264 /* DisableVerify */ true))
265 report_fatal_error("Failed to setup codegen");
266
267 // Run codegen now. resulting binary is in OutputBuffer.
268 PM.run(TheModule);
269 }
270 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
271}
272
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000273/// Manage caching for a single Module.
274class ModuleCacheEntry {
275 SmallString<128> EntryPath;
276
277public:
278 // Create a cache entry. This compute a unique hash for the Module considering
279 // the current list of export/import, and offer an interface to query to
280 // access the content in the cache.
281 ModuleCacheEntry(
282 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
283 const FunctionImporter::ImportMapTy &ImportList,
284 const FunctionImporter::ExportSetTy &ExportList,
285 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000286 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminic92b6122017-01-10 00:55:47 +0000287 const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
288 const TargetMachineBuilder &TMBuilder) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000289 if (CachePath.empty())
290 return;
291
Mehdi Amini00fa1402016-10-08 04:44:18 +0000292 if (!Index.modulePaths().count(ModuleID))
293 // The module does not have an entry, it can't have a hash at all
294 return;
295
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000296 // Compute the unique hash for this entry
297 // This is based on the current compiler version, the module itself, the
298 // export list, the hash for every single module in the import list, the
299 // list of ResolvedODR for the module, and the list of preserved symbols.
300
Mehdi Aminif82bda02016-10-08 04:44:23 +0000301 // Include the hash for the current module
302 auto ModHash = Index.getModuleHash(ModuleID);
303
304 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
305 // No hash entry, no caching!
306 return;
307
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000308 SHA1 Hasher;
309
Mehdi Aminic92b6122017-01-10 00:55:47 +0000310 // Include the parts of the LTO configuration that affect code generation.
311 auto AddString = [&](StringRef Str) {
312 Hasher.update(Str);
313 Hasher.update(ArrayRef<uint8_t>{0});
314 };
315 auto AddUnsigned = [&](unsigned I) {
316 uint8_t Data[4];
317 Data[0] = I;
318 Data[1] = I >> 8;
319 Data[2] = I >> 16;
320 Data[3] = I >> 24;
321 Hasher.update(ArrayRef<uint8_t>{Data, 4});
322 };
323
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000324 // Start with the compiler revision
325 Hasher.update(LLVM_VERSION_STRING);
326#ifdef HAVE_LLVM_REVISION
327 Hasher.update(LLVM_REVISION);
328#endif
329
Mehdi Aminic92b6122017-01-10 00:55:47 +0000330 // Hash the optimization level and the target machine settings.
331 AddString(TMBuilder.MCpu);
332 // FIXME: Hash more of Options. For now all clients initialize Options from
333 // command-line flags (which is unsupported in production), but may set
334 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
335 // DataSections and DebuggerTuning via command line flags.
336 AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
337 AddUnsigned(TMBuilder.Options.FunctionSections);
338 AddUnsigned(TMBuilder.Options.DataSections);
339 AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
340 AddString(TMBuilder.MAttr);
341 if (TMBuilder.RelocModel)
342 AddUnsigned(*TMBuilder.RelocModel);
343 AddUnsigned(TMBuilder.CGOptLevel);
344 AddUnsigned(OptLevel);
345
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000346 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
347 for (auto F : ExportList)
348 // The export list can impact the internalization, be conservative here
349 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
350
351 // Include the hash for every module we import functions from
352 for (auto &Entry : ImportList) {
353 auto ModHash = Index.getModuleHash(Entry.first());
354 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
355 }
356
357 // Include the hash for the resolved ODR.
358 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000359 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000360 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000361 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000362 sizeof(GlobalValue::LinkageTypes)));
363 }
364
365 // Include the hash for the preserved symbols.
366 for (auto &Entry : PreservedSymbols) {
367 if (DefinedFunctions.count(Entry))
368 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000369 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000370 }
371
372 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
373 }
374
Mehdi Amini059464f2016-04-24 03:18:01 +0000375 // Access the path to this entry in the cache.
376 StringRef getEntryPath() { return EntryPath; }
377
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000378 // Try loading the buffer for this cache entry.
379 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
380 if (EntryPath.empty())
381 return std::error_code();
382 return MemoryBuffer::getFile(EntryPath);
383 }
384
385 // Cache the Produced object file
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000386 void write(const MemoryBuffer &OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000387 if (EntryPath.empty())
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000388 return;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000389
390 // Write to a temporary to avoid race condition
391 SmallString<128> TempFilename;
392 int TempFD;
393 std::error_code EC =
394 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
395 if (EC) {
396 errs() << "Error: " << EC.message() << "\n";
397 report_fatal_error("ThinLTO: Can't get a temporary file");
398 }
399 {
400 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000401 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000402 }
403 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000404 EC = sys::fs::rename(TempFilename, EntryPath);
405 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000406 sys::fs::remove(TempFilename);
407 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
408 if (EC)
409 report_fatal_error(Twine("Failed to open ") + EntryPath +
410 " to save cached entry\n");
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000411 OS << OutputBuffer.getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000412 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000413 }
414};
415
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000416static std::unique_ptr<MemoryBuffer>
417ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
418 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
419 const FunctionImporter::ImportMapTy &ImportList,
420 const FunctionImporter::ExportSetTy &ExportList,
421 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
422 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000423 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000424 bool DisableCodeGen, StringRef SaveTempsDir,
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000425 unsigned OptLevel, unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000426
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000427 // "Benchmark"-like optimization: single-source case
428 bool SingleModule = (ModuleMap.size() == 1);
429
430 if (!SingleModule) {
431 promoteModule(TheModule, Index);
432
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000433 // Apply summary-based LinkOnce/Weak resolution decisions.
434 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000435
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000436 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000437 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000438 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000439
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000440 // Be friendly and don't nuke totally the module when the client didn't
441 // supply anything to preserve.
442 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
443 // Apply summary-based internalization decisions.
444 thinLTOInternalizeModule(TheModule, DefinedGlobals);
445 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000446
447 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000448 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000449
450 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000451 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000452
453 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000454 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000455 }
456
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000457 optimizeModule(TheModule, TM, OptLevel);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000458
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000459 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000460
Mehdi Amini43b657b2016-04-01 06:47:02 +0000461 if (DisableCodeGen) {
462 // Configured to stop before CodeGen, serialize the bitcode and return.
463 SmallVector<char, 128> OutputBuffer;
464 {
465 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000466 ProfileSummaryInfo PSI(TheModule);
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000467 auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000468 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000469 }
470 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
471 }
472
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000473 return codegenModule(TheModule, TM);
474}
475
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000476/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
477/// for caching, and in the \p Index for application during the ThinLTO
478/// backends. This is needed for correctness for exported symbols (ensure
479/// at least one copy kept) and a compile-time optimization (to drop duplicate
480/// copies when possible).
481static void resolveWeakForLinkerInIndex(
482 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000483 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
484 &ResolvedODR) {
485
486 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
487 computePrevailingCopies(Index, PrevailingCopy);
488
489 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
490 const auto &Prevailing = PrevailingCopy.find(GUID);
491 // Not in map means that there was only one copy, which must be prevailing.
492 if (Prevailing == PrevailingCopy.end())
493 return true;
494 return Prevailing->second == S;
495 };
496
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000497 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
498 GlobalValue::GUID GUID,
499 GlobalValue::LinkageTypes NewLinkage) {
500 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
501 };
502
Peter Collingbourne73589f32016-07-07 18:31:51 +0000503 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000504}
505
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000506// Initialize the TargetMachine builder for a given Triple
507static void initTMBuilder(TargetMachineBuilder &TMBuilder,
508 const Triple &TheTriple) {
509 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
510 // FIXME this looks pretty terrible...
511 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
512 if (TheTriple.getArch() == llvm::Triple::x86_64)
513 TMBuilder.MCpu = "core2";
514 else if (TheTriple.getArch() == llvm::Triple::x86)
515 TMBuilder.MCpu = "yonah";
516 else if (TheTriple.getArch() == llvm::Triple::aarch64)
517 TMBuilder.MCpu = "cyclone";
518 }
519 TMBuilder.TheTriple = std::move(TheTriple);
520}
521
522} // end anonymous namespace
523
524void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
525 MemoryBufferRef Buffer(Data, Identifier);
526 if (Modules.empty()) {
527 // First module added, so initialize the triple and some options
528 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000529 StringRef TripleStr;
530 ErrorOr<std::string> TripleOrErr =
531 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
532 if (TripleOrErr)
533 TripleStr = *TripleOrErr;
534 Triple TheTriple(TripleStr);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000535 initTMBuilder(TMBuilder, Triple(TheTriple));
536 }
537#ifndef NDEBUG
538 else {
539 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000540 StringRef TripleStr;
541 ErrorOr<std::string> TripleOrErr =
542 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
543 if (TripleOrErr)
544 TripleStr = *TripleOrErr;
545 assert(TMBuilder.TheTriple.str() == TripleStr &&
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000546 "ThinLTO modules with different triple not supported");
547 }
548#endif
549 Modules.push_back(Buffer);
550}
551
552void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
553 PreservedSymbols.insert(Name);
554}
555
556void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000557 // FIXME: At the moment, we don't take advantage of this extra information,
558 // we're conservatively considering cross-references as preserved.
559 // CrossReferencedSymbols.insert(Name);
560 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000561}
562
563// TargetMachine factory
564std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
565 std::string ErrMsg;
566 const Target *TheTarget =
567 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
568 if (!TheTarget) {
569 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
570 }
571
572 // Use MAttr as the default set of features.
573 SubtargetFeatures Features(MAttr);
574 Features.getDefaultSubtargetFeatures(TheTriple);
575 std::string FeatureStr = Features.getString();
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000576
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000577 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
578 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
579 CodeModel::Default, CGOptLevel));
580}
581
582/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000583 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000584 * "thin-link".
585 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000586std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
587 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000588 uint64_t NextModuleId = 0;
589 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000590 Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
591 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer);
592 if (!ObjOrErr) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000593 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000594 logAllUnhandledErrors(
595 ObjOrErr.takeError(), errs(),
596 "error: can't create ModuleSummaryIndexObjectFile for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000597 return nullptr;
598 }
599 auto Index = (*ObjOrErr)->takeIndex();
600 if (CombinedIndex) {
601 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
602 } else {
603 CombinedIndex = std::move(Index);
604 }
605 }
606 return CombinedIndex;
607}
608
609/**
610 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000611 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000612 */
613void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000614 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000615 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000616 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000617
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000618 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000619 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000620 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000621
Teresa Johnson6c475a72017-01-05 21:34:18 +0000622 // Convert the preserved symbols set from string to GUID
623 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
624 PreservedSymbols, Triple(TheModule.getTargetTriple()));
625
626 // Compute "dead" symbols, we don't want to import/export these!
627 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
628
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000629 // Generate import/export list
630 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
631 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
632 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000633 ExportLists, &DeadSymbols);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000634
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000635 // Resolve LinkOnce/Weak symbols.
636 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000637 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000638
639 thinLTOResolveWeakForLinkerModule(
640 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000641
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000642 // Promote the exported values in the index, so that they are promoted
643 // in the module.
644 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
645 const auto &ExportList = ExportLists.find(ModuleIdentifier);
646 return (ExportList != ExportLists.end() &&
647 ExportList->second.count(GUID)) ||
648 GUIDPreservedSymbols.count(GUID);
649 };
650 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
651
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000652 promoteModule(TheModule, Index);
653}
654
655/**
656 * Perform cross-module importing for the module identified by ModuleIdentifier.
657 */
658void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000659 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000660 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000661 auto ModuleCount = Index.modulePaths().size();
662
663 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000664 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000665 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000666
Teresa Johnson6c475a72017-01-05 21:34:18 +0000667 // Convert the preserved symbols set from string to GUID
668 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
669 PreservedSymbols, Triple(TheModule.getTargetTriple()));
670
671 // Compute "dead" symbols, we don't want to import/export these!
672 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
673
Mehdi Amini01e32132016-03-26 05:40:34 +0000674 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000675 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
676 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000677 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000678 ExportLists, &DeadSymbols);
Mehdi Amini01e32132016-03-26 05:40:34 +0000679 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
680
681 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000682}
683
684/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000685 * Compute the list of summaries needed for importing into module.
686 */
687void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
688 StringRef ModulePath, ModuleSummaryIndex &Index,
689 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
690 auto ModuleCount = Index.modulePaths().size();
691
692 // Collect for each module the list of function it defines (GUID -> Summary).
693 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
694 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
695
696 // Generate import/export list
697 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
698 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
699 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
700 ExportLists);
701
702 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000703 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000704 ModuleToSummariesForIndex);
705}
706
707/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000708 * Emit the list of files needed for importing into module.
709 */
710void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
711 StringRef OutputName,
712 ModuleSummaryIndex &Index) {
713 auto ModuleCount = Index.modulePaths().size();
714
715 // Collect for each module the list of function it defines (GUID -> Summary).
716 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
717 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
718
719 // Generate import/export list
720 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
721 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
722 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
723 ExportLists);
724
725 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000726 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000727 report_fatal_error(Twine("Failed to open ") + OutputName +
728 " to save imports lists\n");
729}
730
731/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000732 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000733 */
734void ThinLTOCodeGenerator::internalize(Module &TheModule,
735 ModuleSummaryIndex &Index) {
736 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
737 auto ModuleCount = Index.modulePaths().size();
738 auto ModuleIdentifier = TheModule.getModuleIdentifier();
739
740 // Convert the preserved symbols set from string to GUID
741 auto GUIDPreservedSymbols =
742 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
743
744 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000745 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000746 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
747
Teresa Johnson6c475a72017-01-05 21:34:18 +0000748 // Compute "dead" symbols, we don't want to import/export these!
749 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
750
Mehdi Amini059464f2016-04-24 03:18:01 +0000751 // Generate import/export list
752 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
753 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
754 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000755 ExportLists, &DeadSymbols);
Mehdi Amini059464f2016-04-24 03:18:01 +0000756 auto &ExportList = ExportLists[ModuleIdentifier];
757
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000758 // Be friendly and don't nuke totally the module when the client didn't
759 // supply anything to preserve.
760 if (ExportList.empty() && GUIDPreservedSymbols.empty())
761 return;
762
Mehdi Amini059464f2016-04-24 03:18:01 +0000763 // Internalization
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000764 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
765 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000766 return (ExportList != ExportLists.end() &&
767 ExportList->second.count(GUID)) ||
768 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000769 };
770 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
771 thinLTOInternalizeModule(TheModule,
772 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000773}
774
775/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000776 * Perform post-importing ThinLTO optimizations.
777 */
778void ThinLTOCodeGenerator::optimize(Module &TheModule) {
779 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000780
781 // Optimize now
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000782 optimizeModule(TheModule, *TMBuilder.create(), OptLevel);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000783}
784
785/**
786 * Perform ThinLTO CodeGen.
787 */
788std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
789 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
790 return codegenModule(TheModule, *TMBuilder.create());
791}
792
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000793/// Write out the generated object file, either from CacheEntryPath or from
794/// OutputBuffer, preferring hard-link when possible.
795/// Returns the path to the generated file in SavedObjectsDirectoryPath.
796static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
797 StringRef SavedObjectsDirectoryPath,
798 const MemoryBuffer &OutputBuffer) {
799 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
800 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
801 OutputPath.c_str(); // Ensure the string is null terminated.
802 if (sys::fs::exists(OutputPath))
803 sys::fs::remove(OutputPath);
804
805 // We don't return a memory buffer to the linker, just a list of files.
806 if (!CacheEntryPath.empty()) {
807 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
808 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
809 if (!Err)
810 return OutputPath.str();
811 // Hard linking failed, try to copy.
812 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
813 if (!Err)
814 return OutputPath.str();
815 // Copy failed (could be because the CacheEntry was removed from the cache
816 // in the meantime by another process), fall back and try to write down the
817 // buffer to the output.
818 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
819 << "' to '" << OutputPath << "'\n";
820 }
821 // No cache entry, just write out the buffer.
822 std::error_code Err;
823 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
824 if (Err)
825 report_fatal_error("Can't open output '" + OutputPath + "'\n");
826 OS << OutputBuffer.getBuffer();
827 return OutputPath.str();
828}
829
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000830// Main entry point for the ThinLTO processing
831void ThinLTOCodeGenerator::run() {
Mehdi Amini43b657b2016-04-01 06:47:02 +0000832 if (CodeGenOnly) {
833 // Perform only parallel codegen and return.
834 ThreadPool Pool;
835 assert(ProducedBinaries.empty() && "The generator should not be reused");
836 ProducedBinaries.resize(Modules.size());
837 int count = 0;
838 for (auto &ModuleBuffer : Modules) {
839 Pool.async([&](int count) {
840 LLVMContext Context;
841 Context.setDiscardValueNames(LTODiscardValueNames);
842
843 // Parse module now
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000844 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false,
845 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000846
847 // CodeGen
848 ProducedBinaries[count] = codegen(*TheModule);
849 }, count++);
850 }
851
852 return;
853 }
854
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000855 // Sequential linking phase
856 auto Index = linkCombinedIndex();
857
858 // Save temps: index.
859 if (!SaveTempsDir.empty()) {
860 auto SaveTempPath = SaveTempsDir + "index.bc";
861 std::error_code EC;
862 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
863 if (EC)
864 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
865 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000866 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000867 }
868
869 // Prepare the resulting object vector
870 assert(ProducedBinaries.empty() && "The generator should not be reused");
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000871 if (SavedObjectsDirectoryPath.empty())
872 ProducedBinaries.resize(Modules.size());
873 else {
874 sys::fs::create_directories(SavedObjectsDirectoryPath);
875 bool IsDir;
876 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
877 if (!IsDir)
878 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
879 ProducedBinaryFiles.resize(Modules.size());
880 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000881
882 // Prepare the module map.
883 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000884 auto ModuleCount = Modules.size();
885
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000886 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000887 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000888 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
889
Teresa Johnson6c475a72017-01-05 21:34:18 +0000890 // Convert the preserved symbols set from string to GUID, this is needed for
891 // computing the caching hash and the internalization.
892 auto GUIDPreservedSymbols =
893 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
894
895 // Compute "dead" symbols, we don't want to import/export these!
896 auto DeadSymbols = computeDeadSymbols(*Index, GUIDPreservedSymbols);
897
Mehdi Amini01e32132016-03-26 05:40:34 +0000898 // Collect the import/export lists for all modules from the call-graph in the
899 // combined index.
900 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
901 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000902 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000903 ExportLists, &DeadSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000904
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000905 // We use a std::map here to be able to have a defined ordering when
906 // producing a hash for the cache entry.
907 // FIXME: we should be able to compute the caching hash for the entry based
908 // on the index, and nuke this map.
909 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
910
911 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
912 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000913 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000914
915 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
916 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Teresa Johnson4ae5ce72016-05-24 19:12:48 +0000917 return (ExportList != ExportLists.end() &&
918 ExportList->second.count(GUID)) ||
919 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000920 };
921
922 // Use global summary-based analysis to identify symbols that can be
923 // internalized (because they aren't exported or preserved as per callback).
924 // Changes are made in the index, consumed in the ThinLTO backends.
925 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
926
Teresa Johnson141149f2016-05-24 18:44:01 +0000927 // Make sure that every module has an entry in the ExportLists and
928 // ResolvedODR maps to enable threaded access to these maps below.
929 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000930 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000931 ResolvedODR[DefinedGVSummaries.first()];
932 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000933
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000934 // Compute the ordering we will process the inputs: the rough heuristic here
935 // is to sort them per size so that the largest module get schedule as soon as
936 // possible. This is purely a compile-time optimization.
937 std::vector<int> ModulesOrdering;
938 ModulesOrdering.resize(Modules.size());
939 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
940 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
941 [&](int LeftIndex, int RightIndex) {
942 auto LSize = Modules[LeftIndex].getBufferSize();
943 auto RSize = Modules[RightIndex].getBufferSize();
944 return LSize > RSize;
945 });
946
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000947 // Parallel optimizer + codegen
948 {
949 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000950 for (auto IndexCount : ModulesOrdering) {
951 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000952 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000953 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000954 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000955
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000956 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
957
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000958 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000959 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
960 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000961 ResolvedODR[ModuleIdentifier],
Mehdi Aminic92b6122017-01-10 00:55:47 +0000962 DefinedFunctions, GUIDPreservedSymbols,
963 OptLevel, TMBuilder);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000964 auto CacheEntryPath = CacheEntry.getEntryPath();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000965
966 {
967 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000968 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000969 << CacheEntryPath << "' for buffer " << count << " "
970 << ModuleIdentifier << "\n");
Mehdi Amini059464f2016-04-24 03:18:01 +0000971
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000972 if (ErrOrBuffer) {
973 // Cache Hit!
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000974 if (SavedObjectsDirectoryPath.empty())
975 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
976 else
977 ProducedBinaryFiles[count] = writeGeneratedObject(
978 count, CacheEntryPath, SavedObjectsDirectoryPath,
979 *ErrOrBuffer.get());
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000980 return;
981 }
982 }
983
984 LLVMContext Context;
985 Context.setDiscardValueNames(LTODiscardValueNames);
986 Context.enableDebugTypeODRUniquing();
Mehdi Amini19f176b2016-11-19 18:20:05 +0000987 auto DiagFileOrErr = setupOptimizationRemarks(Context, count);
988 if (!DiagFileOrErr) {
989 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
990 report_fatal_error("ThinLTO: Can't get an output file for the "
991 "remarks");
992 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000993
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000994 // Parse module now
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000995 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false,
996 /*IsImporting*/ false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000997
998 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000999 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001000
Mehdi Amini1aafabf2016-04-16 07:02:16 +00001001 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +00001002 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001003 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +00001004 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +00001005 ExportList, GUIDPreservedSymbols,
1006 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Aminicc7fbf72016-12-28 19:37:16 +00001007 DisableCodeGen, SaveTempsDir, OptLevel, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001008
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001009 // Commit to the cache (if enabled)
1010 CacheEntry.write(*OutputBuffer);
1011
1012 if (SavedObjectsDirectoryPath.empty()) {
1013 // We need to generated a memory buffer for the linker.
1014 if (!CacheEntryPath.empty()) {
1015 // Cache is enabled, reload from the cache
1016 // We do this to lower memory pressuree: the buffer is on the heap
1017 // and releasing it frees memory that can be used for the next input
1018 // file. The final binary link will read from the VFS cache
1019 // (hopefully!) or from disk if the memory pressure wasn't too high.
1020 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1021 if (auto EC = ReloadedBufferOrErr.getError()) {
1022 // On error, keeping the preexisting buffer and printing a
1023 // diagnostic is more friendly than just crashing.
1024 errs() << "error: can't reload cached file '" << CacheEntryPath
1025 << "': " << EC.message() << "\n";
1026 } else {
1027 OutputBuffer = std::move(*ReloadedBufferOrErr);
1028 }
1029 }
1030 ProducedBinaries[count] = std::move(OutputBuffer);
1031 return;
1032 }
1033 ProducedBinaryFiles[count] = writeGeneratedObject(
1034 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001035 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001036 }
1037 }
1038
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001039 CachePruning(CacheOptions.Path)
Pavel Labath757ca882016-10-24 10:59:17 +00001040 .setPruningInterval(std::chrono::seconds(CacheOptions.PruningInterval))
1041 .setEntryExpiration(std::chrono::seconds(CacheOptions.Expiration))
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001042 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
1043 .prune();
1044
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001045 // If statistics were requested, print them out now.
1046 if (llvm::AreStatisticsEnabled())
1047 llvm::PrintStatistics();
1048}