blob: 970c75e4aceac3ef9e6072cf3ee02b363f09cd4f [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 Amini7c4a1a82016-03-09 01:37:22 +000076// Simple helper to save temporary files for debug.
77static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
78 unsigned count, StringRef Suffix) {
79 if (TempDir.empty())
80 return;
81 // User asked to save temps, let dump the bitcode file after import.
Teresa Johnsonc44a1222016-08-15 23:24:57 +000082 std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000083 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000084 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000085 if (EC)
86 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
87 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +000088 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000089}
90
Teresa Johnson4d2613f2016-05-24 17:24:25 +000091static const GlobalValueSummary *
92getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
93 // If there is any strong definition anywhere, get it.
94 auto StrongDefForLinker = llvm::find_if(
95 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
96 auto Linkage = Summary->linkage();
97 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
98 !GlobalValue::isWeakForLinker(Linkage);
99 });
100 if (StrongDefForLinker != GVSummaryList.end())
101 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000102 // Get the first *linker visible* definition for this global in the summary
103 // list.
104 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000105 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
106 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000107 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
108 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000109 // Extern templates can be emitted as available_externally.
110 if (FirstDefForLinker == GVSummaryList.end())
111 return nullptr;
112 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000113}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000114
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000115// Populate map of GUID to the prevailing copy for any multiply defined
116// symbols. Currently assume first copy is prevailing, or any strong
117// definition. Can be refined with Linker information in the future.
118static void computePrevailingCopies(
119 const ModuleSummaryIndex &Index,
120 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000121 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
122 return GVSummaryList.size() > 1;
123 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000124
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000125 for (auto &I : Index) {
126 if (HasMultipleCopies(I.second))
127 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000128 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000129}
130
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000131static StringMap<MemoryBufferRef>
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000132generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000133 StringMap<MemoryBufferRef> ModuleMap;
134 for (auto &ModuleBuffer : Modules) {
135 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
136 ModuleMap.end() &&
137 "Expect unique Buffer Identifier");
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000138 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000139 }
140 return ModuleMap;
141}
142
Teresa Johnson26ab5772016-03-15 00:04:37 +0000143static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000144 if (renameModuleForThinLTO(TheModule, Index))
145 report_fatal_error("renameModuleForThinLTO failed");
146}
147
Peter Collingbournedac43b42016-12-01 05:52:32 +0000148static std::unique_ptr<Module>
149loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000150 bool Lazy, bool IsImporting) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000151 SMDiagnostic Err;
152 Expected<std::unique_ptr<Module>> ModuleOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000153 Lazy
154 ? getLazyBitcodeModule(Buffer, Context,
155 /* ShouldLazyLoadMetadata */ true, IsImporting)
156 : parseBitcodeFile(Buffer, Context);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000157 if (!ModuleOrErr) {
158 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
159 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
160 SourceMgr::DK_Error, EIB.message());
161 Err.print("ThinLTO", errs());
162 });
163 report_fatal_error("Can't load module, abort.");
164 }
165 return std::move(ModuleOrErr.get());
166}
167
Mehdi Amini01e32132016-03-26 05:40:34 +0000168static void
169crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
170 StringMap<MemoryBufferRef> &ModuleMap,
171 const FunctionImporter::ImportMapTy &ImportList) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000172 auto Loader = [&](StringRef Identifier) {
173 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000174 /*Lazy=*/true, /*IsImporting*/ true);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000175 };
176
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000177 FunctionImporter Importer(Index, Loader);
Mehdi Amini83a807e2017-01-08 00:30:27 +0000178 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
179 if (!Result) {
180 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
181 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
182 SourceMgr::DK_Error, EIB.message());
183 Err.print("ThinLTO", errs());
184 });
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000185 report_fatal_error("importFunctions failed");
Mehdi Amini83a807e2017-01-08 00:30:27 +0000186 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000187}
188
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000189static void optimizeModule(Module &TheModule, TargetMachine &TM,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000190 unsigned OptLevel, bool Freestanding) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000191 // Populate the PassManager
192 PassManagerBuilder PMB;
193 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000194 if (Freestanding)
195 PMB.LibraryInfo->disableAllFunctions();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000196 PMB.Inliner = createFunctionInliningPass();
197 // FIXME: should get it from the bitcode?
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000198 PMB.OptLevel = OptLevel;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000199 PMB.LoopVectorize = true;
200 PMB.SLPVectorize = true;
201 PMB.VerifyInput = true;
202 PMB.VerifyOutput = false;
203
204 legacy::PassManager PM;
205
206 // Add the TTI (required to inform the vectorizer about register size for
207 // instance)
208 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
209
210 // Add optimizations
211 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000212
213 PM.run(TheModule);
214}
215
Mehdi Amini059464f2016-04-24 03:18:01 +0000216// Convert the PreservedSymbols map from "Name" based to "GUID" based.
217static DenseSet<GlobalValue::GUID>
Mehdi Amini1380edf2017-02-03 07:41:43 +0000218computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
219 const Triple &TheTriple) {
220 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
221 for (auto &Entry : PreservedSymbols) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000222 StringRef Name = Entry.first();
223 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
224 Name = Name.drop_front();
Mehdi Amini1380edf2017-02-03 07:41:43 +0000225 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
Mehdi Amini059464f2016-04-24 03:18:01 +0000226 }
Mehdi Amini1380edf2017-02-03 07:41:43 +0000227 return GUIDPreservedSymbols;
Mehdi Amini059464f2016-04-24 03:18:01 +0000228}
229
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000230std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
231 TargetMachine &TM) {
232 SmallVector<char, 128> OutputBuffer;
233
234 // CodeGen
235 {
236 raw_svector_ostream OS(OutputBuffer);
237 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000238
239 // If the bitcode files contain ARC code and were compiled with optimization,
240 // the ObjCARCContractPass must be run, so do it unconditionally here.
241 PM.add(createObjCARCContractPass());
242
243 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000244 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
245 /* DisableVerify */ true))
246 report_fatal_error("Failed to setup codegen");
247
248 // Run codegen now. resulting binary is in OutputBuffer.
249 PM.run(TheModule);
250 }
251 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
252}
253
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000254/// Manage caching for a single Module.
255class ModuleCacheEntry {
256 SmallString<128> EntryPath;
257
258public:
259 // Create a cache entry. This compute a unique hash for the Module considering
260 // the current list of export/import, and offer an interface to query to
261 // access the content in the cache.
262 ModuleCacheEntry(
263 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
264 const FunctionImporter::ImportMapTy &ImportList,
265 const FunctionImporter::ExportSetTy &ExportList,
266 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000267 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminic92b6122017-01-10 00:55:47 +0000268 const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000269 bool Freestanding, const TargetMachineBuilder &TMBuilder) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000270 if (CachePath.empty())
271 return;
272
Mehdi Amini00fa1402016-10-08 04:44:18 +0000273 if (!Index.modulePaths().count(ModuleID))
274 // The module does not have an entry, it can't have a hash at all
275 return;
276
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000277 // Compute the unique hash for this entry
278 // This is based on the current compiler version, the module itself, the
279 // export list, the hash for every single module in the import list, the
280 // list of ResolvedODR for the module, and the list of preserved symbols.
281
Mehdi Aminif82bda02016-10-08 04:44:23 +0000282 // Include the hash for the current module
283 auto ModHash = Index.getModuleHash(ModuleID);
284
285 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
286 // No hash entry, no caching!
287 return;
288
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000289 SHA1 Hasher;
290
Mehdi Aminic92b6122017-01-10 00:55:47 +0000291 // Include the parts of the LTO configuration that affect code generation.
292 auto AddString = [&](StringRef Str) {
293 Hasher.update(Str);
294 Hasher.update(ArrayRef<uint8_t>{0});
295 };
296 auto AddUnsigned = [&](unsigned I) {
297 uint8_t Data[4];
298 Data[0] = I;
299 Data[1] = I >> 8;
300 Data[2] = I >> 16;
301 Data[3] = I >> 24;
302 Hasher.update(ArrayRef<uint8_t>{Data, 4});
303 };
304
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000305 // Start with the compiler revision
306 Hasher.update(LLVM_VERSION_STRING);
307#ifdef HAVE_LLVM_REVISION
308 Hasher.update(LLVM_REVISION);
309#endif
310
Mehdi Aminic92b6122017-01-10 00:55:47 +0000311 // Hash the optimization level and the target machine settings.
312 AddString(TMBuilder.MCpu);
313 // FIXME: Hash more of Options. For now all clients initialize Options from
314 // command-line flags (which is unsupported in production), but may set
315 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
316 // DataSections and DebuggerTuning via command line flags.
317 AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
318 AddUnsigned(TMBuilder.Options.FunctionSections);
319 AddUnsigned(TMBuilder.Options.DataSections);
320 AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
321 AddString(TMBuilder.MAttr);
322 if (TMBuilder.RelocModel)
323 AddUnsigned(*TMBuilder.RelocModel);
324 AddUnsigned(TMBuilder.CGOptLevel);
325 AddUnsigned(OptLevel);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000326 AddUnsigned(Freestanding);
Mehdi Aminic92b6122017-01-10 00:55:47 +0000327
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000328 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
329 for (auto F : ExportList)
330 // The export list can impact the internalization, be conservative here
331 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
332
333 // Include the hash for every module we import functions from
334 for (auto &Entry : ImportList) {
335 auto ModHash = Index.getModuleHash(Entry.first());
336 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
337 }
338
339 // Include the hash for the resolved ODR.
340 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000341 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000342 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000343 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000344 sizeof(GlobalValue::LinkageTypes)));
345 }
346
347 // Include the hash for the preserved symbols.
348 for (auto &Entry : PreservedSymbols) {
349 if (DefinedFunctions.count(Entry))
350 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000351 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000352 }
353
Peter Collingbourne25a17ba2017-03-20 16:41:57 +0000354 // This choice of file name allows the cache to be pruned (see pruneCache()
355 // in include/llvm/Support/CachePruning.h).
356 sys::path::append(EntryPath, CachePath,
357 "llvmcache-" + toHex(Hasher.result()));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000358 }
359
Mehdi Amini059464f2016-04-24 03:18:01 +0000360 // Access the path to this entry in the cache.
361 StringRef getEntryPath() { return EntryPath; }
362
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000363 // Try loading the buffer for this cache entry.
364 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
365 if (EntryPath.empty())
366 return std::error_code();
367 return MemoryBuffer::getFile(EntryPath);
368 }
369
370 // Cache the Produced object file
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000371 void write(const MemoryBuffer &OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000372 if (EntryPath.empty())
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000373 return;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000374
375 // Write to a temporary to avoid race condition
376 SmallString<128> TempFilename;
377 int TempFD;
378 std::error_code EC =
379 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
380 if (EC) {
381 errs() << "Error: " << EC.message() << "\n";
382 report_fatal_error("ThinLTO: Can't get a temporary file");
383 }
384 {
385 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000386 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000387 }
388 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000389 EC = sys::fs::rename(TempFilename, EntryPath);
390 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000391 sys::fs::remove(TempFilename);
392 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
393 if (EC)
394 report_fatal_error(Twine("Failed to open ") + EntryPath +
395 " to save cached entry\n");
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000396 OS << OutputBuffer.getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000397 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000398 }
399};
400
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000401static std::unique_ptr<MemoryBuffer>
402ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
403 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
404 const FunctionImporter::ImportMapTy &ImportList,
405 const FunctionImporter::ExportSetTy &ExportList,
406 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
407 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000408 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000409 bool DisableCodeGen, StringRef SaveTempsDir,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000410 bool Freestanding, unsigned OptLevel, unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000411
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000412 // "Benchmark"-like optimization: single-source case
413 bool SingleModule = (ModuleMap.size() == 1);
414
415 if (!SingleModule) {
416 promoteModule(TheModule, Index);
417
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000418 // Apply summary-based LinkOnce/Weak resolution decisions.
419 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000420
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000421 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000422 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000423 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000424
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000425 // Be friendly and don't nuke totally the module when the client didn't
426 // supply anything to preserve.
427 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
428 // Apply summary-based internalization decisions.
429 thinLTOInternalizeModule(TheModule, DefinedGlobals);
430 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000431
432 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000433 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000434
435 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000436 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000437
438 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000439 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000440 }
441
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000442 optimizeModule(TheModule, TM, OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000443
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000444 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000445
Mehdi Amini43b657b2016-04-01 06:47:02 +0000446 if (DisableCodeGen) {
447 // Configured to stop before CodeGen, serialize the bitcode and return.
448 SmallVector<char, 128> OutputBuffer;
449 {
450 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000451 ProfileSummaryInfo PSI(TheModule);
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000452 auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000453 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000454 }
455 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
456 }
457
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000458 return codegenModule(TheModule, TM);
459}
460
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000461/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
462/// for caching, and in the \p Index for application during the ThinLTO
463/// backends. This is needed for correctness for exported symbols (ensure
464/// at least one copy kept) and a compile-time optimization (to drop duplicate
465/// copies when possible).
466static void resolveWeakForLinkerInIndex(
467 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000468 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
469 &ResolvedODR) {
470
471 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
472 computePrevailingCopies(Index, PrevailingCopy);
473
474 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
475 const auto &Prevailing = PrevailingCopy.find(GUID);
476 // Not in map means that there was only one copy, which must be prevailing.
477 if (Prevailing == PrevailingCopy.end())
478 return true;
479 return Prevailing->second == S;
480 };
481
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000482 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
483 GlobalValue::GUID GUID,
484 GlobalValue::LinkageTypes NewLinkage) {
485 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
486 };
487
Peter Collingbourne73589f32016-07-07 18:31:51 +0000488 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000489}
490
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000491// Initialize the TargetMachine builder for a given Triple
492static void initTMBuilder(TargetMachineBuilder &TMBuilder,
493 const Triple &TheTriple) {
494 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
495 // FIXME this looks pretty terrible...
496 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
497 if (TheTriple.getArch() == llvm::Triple::x86_64)
498 TMBuilder.MCpu = "core2";
499 else if (TheTriple.getArch() == llvm::Triple::x86)
500 TMBuilder.MCpu = "yonah";
501 else if (TheTriple.getArch() == llvm::Triple::aarch64)
502 TMBuilder.MCpu = "cyclone";
503 }
504 TMBuilder.TheTriple = std::move(TheTriple);
505}
506
507} // end anonymous namespace
508
509void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000510 ThinLTOBuffer Buffer(Data, Identifier);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000511 if (Modules.empty()) {
512 // First module added, so initialize the triple and some options
513 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000514 StringRef TripleStr;
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000515 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
516 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
Peter Collingbournecd513a42016-11-11 19:50:24 +0000517 if (TripleOrErr)
518 TripleStr = *TripleOrErr;
519 Triple TheTriple(TripleStr);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000520 initTMBuilder(TMBuilder, Triple(TheTriple));
521 }
522#ifndef NDEBUG
523 else {
524 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000525 StringRef TripleStr;
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000526 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
527 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
Peter Collingbournecd513a42016-11-11 19:50:24 +0000528 if (TripleOrErr)
529 TripleStr = *TripleOrErr;
530 assert(TMBuilder.TheTriple.str() == TripleStr &&
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000531 "ThinLTO modules with different triple not supported");
532 }
533#endif
534 Modules.push_back(Buffer);
535}
536
537void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
538 PreservedSymbols.insert(Name);
539}
540
541void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000542 // FIXME: At the moment, we don't take advantage of this extra information,
543 // we're conservatively considering cross-references as preserved.
544 // CrossReferencedSymbols.insert(Name);
545 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000546}
547
548// TargetMachine factory
549std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
550 std::string ErrMsg;
551 const Target *TheTarget =
552 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
553 if (!TheTarget) {
554 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
555 }
556
557 // Use MAttr as the default set of features.
558 SubtargetFeatures Features(MAttr);
559 Features.getDefaultSubtargetFeatures(TheTriple);
560 std::string FeatureStr = Features.getString();
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000561
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000562 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
563 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
564 CodeModel::Default, CGOptLevel));
565}
566
567/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000568 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000569 * "thin-link".
570 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000571std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
572 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000573 uint64_t NextModuleId = 0;
574 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000575 Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000576 object::ModuleSummaryIndexObjectFile::create(
577 ModuleBuffer.getMemBuffer());
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000578 if (!ObjOrErr) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000579 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000580 logAllUnhandledErrors(
581 ObjOrErr.takeError(), errs(),
582 "error: can't create ModuleSummaryIndexObjectFile for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000583 return nullptr;
584 }
585 auto Index = (*ObjOrErr)->takeIndex();
586 if (CombinedIndex) {
587 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
588 } else {
589 CombinedIndex = std::move(Index);
590 }
591 }
592 return CombinedIndex;
593}
594
595/**
596 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000597 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000598 */
599void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000600 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000601 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000602 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000603
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000604 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000605 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000606 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000607
Teresa Johnson6c475a72017-01-05 21:34:18 +0000608 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000609 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000610 PreservedSymbols, Triple(TheModule.getTargetTriple()));
611
612 // Compute "dead" symbols, we don't want to import/export these!
613 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
614
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000615 // Generate import/export list
616 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
617 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
618 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000619 ExportLists, &DeadSymbols);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000620
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000621 // Resolve LinkOnce/Weak symbols.
622 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000623 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000624
625 thinLTOResolveWeakForLinkerModule(
626 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000627
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000628 // Promote the exported values in the index, so that they are promoted
629 // in the module.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000630 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000631 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000632 return (ExportList != ExportLists.end() &&
633 ExportList->second.count(GUID)) ||
634 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000635 };
636 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
637
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000638 promoteModule(TheModule, Index);
639}
640
641/**
642 * Perform cross-module importing for the module identified by ModuleIdentifier.
643 */
644void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000645 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000646 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000647 auto ModuleCount = Index.modulePaths().size();
648
649 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000650 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000651 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000652
Teresa Johnson6c475a72017-01-05 21:34:18 +0000653 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000654 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000655 PreservedSymbols, Triple(TheModule.getTargetTriple()));
656
657 // Compute "dead" symbols, we don't want to import/export these!
658 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
659
Mehdi Amini01e32132016-03-26 05:40:34 +0000660 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000661 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
662 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000663 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000664 ExportLists, &DeadSymbols);
Mehdi Amini01e32132016-03-26 05:40:34 +0000665 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
666
667 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000668}
669
670/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000671 * Compute the list of summaries needed for importing into module.
672 */
673void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
674 StringRef ModulePath, ModuleSummaryIndex &Index,
675 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
676 auto ModuleCount = Index.modulePaths().size();
677
678 // Collect for each module the list of function it defines (GUID -> Summary).
679 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
680 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
681
682 // Generate import/export list
683 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
684 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
685 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
686 ExportLists);
687
688 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000689 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000690 ModuleToSummariesForIndex);
691}
692
693/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000694 * Emit the list of files needed for importing into module.
695 */
696void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
697 StringRef OutputName,
698 ModuleSummaryIndex &Index) {
699 auto ModuleCount = Index.modulePaths().size();
700
701 // Collect for each module the list of function it defines (GUID -> Summary).
702 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
703 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
704
705 // Generate import/export list
706 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
707 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
708 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
709 ExportLists);
710
711 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000712 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000713 report_fatal_error(Twine("Failed to open ") + OutputName +
714 " to save imports lists\n");
715}
716
717/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000718 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000719 */
720void ThinLTOCodeGenerator::internalize(Module &TheModule,
721 ModuleSummaryIndex &Index) {
722 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
723 auto ModuleCount = Index.modulePaths().size();
724 auto ModuleIdentifier = TheModule.getModuleIdentifier();
725
726 // Convert the preserved symbols set from string to GUID
727 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000728 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Amini059464f2016-04-24 03:18:01 +0000729
730 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000731 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000732 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
733
Teresa Johnson6c475a72017-01-05 21:34:18 +0000734 // Compute "dead" symbols, we don't want to import/export these!
735 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
736
Mehdi Amini059464f2016-04-24 03:18:01 +0000737 // Generate import/export list
738 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
739 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
740 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000741 ExportLists, &DeadSymbols);
Mehdi Amini059464f2016-04-24 03:18:01 +0000742 auto &ExportList = ExportLists[ModuleIdentifier];
743
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000744 // Be friendly and don't nuke totally the module when the client didn't
745 // supply anything to preserve.
746 if (ExportList.empty() && GUIDPreservedSymbols.empty())
747 return;
748
Mehdi Amini059464f2016-04-24 03:18:01 +0000749 // Internalization
Mehdi Amini1380edf2017-02-03 07:41:43 +0000750 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000751 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000752 return (ExportList != ExportLists.end() &&
753 ExportList->second.count(GUID)) ||
754 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000755 };
756 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
757 thinLTOInternalizeModule(TheModule,
758 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000759}
760
761/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000762 * Perform post-importing ThinLTO optimizations.
763 */
764void ThinLTOCodeGenerator::optimize(Module &TheModule) {
765 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000766
767 // Optimize now
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000768 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000769}
770
771/**
772 * Perform ThinLTO CodeGen.
773 */
774std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
775 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
776 return codegenModule(TheModule, *TMBuilder.create());
777}
778
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000779/// Write out the generated object file, either from CacheEntryPath or from
780/// OutputBuffer, preferring hard-link when possible.
781/// Returns the path to the generated file in SavedObjectsDirectoryPath.
782static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
783 StringRef SavedObjectsDirectoryPath,
784 const MemoryBuffer &OutputBuffer) {
785 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
786 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
787 OutputPath.c_str(); // Ensure the string is null terminated.
788 if (sys::fs::exists(OutputPath))
789 sys::fs::remove(OutputPath);
790
791 // We don't return a memory buffer to the linker, just a list of files.
792 if (!CacheEntryPath.empty()) {
793 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
794 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
795 if (!Err)
796 return OutputPath.str();
797 // Hard linking failed, try to copy.
798 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
799 if (!Err)
800 return OutputPath.str();
801 // Copy failed (could be because the CacheEntry was removed from the cache
802 // in the meantime by another process), fall back and try to write down the
803 // buffer to the output.
804 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
805 << "' to '" << OutputPath << "'\n";
806 }
807 // No cache entry, just write out the buffer.
808 std::error_code Err;
809 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
810 if (Err)
811 report_fatal_error("Can't open output '" + OutputPath + "'\n");
812 OS << OutputBuffer.getBuffer();
813 return OutputPath.str();
814}
815
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000816// Main entry point for the ThinLTO processing
817void ThinLTOCodeGenerator::run() {
Mehdi Aminib2990462017-01-20 22:45:34 +0000818 // Prepare the resulting object vector
819 assert(ProducedBinaries.empty() && "The generator should not be reused");
820 if (SavedObjectsDirectoryPath.empty())
821 ProducedBinaries.resize(Modules.size());
822 else {
823 sys::fs::create_directories(SavedObjectsDirectoryPath);
824 bool IsDir;
825 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
826 if (!IsDir)
827 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
828 ProducedBinaryFiles.resize(Modules.size());
829 }
830
Mehdi Amini43b657b2016-04-01 06:47:02 +0000831 if (CodeGenOnly) {
832 // Perform only parallel codegen and return.
833 ThreadPool Pool;
Mehdi Amini43b657b2016-04-01 06:47:02 +0000834 int count = 0;
835 for (auto &ModuleBuffer : Modules) {
836 Pool.async([&](int count) {
837 LLVMContext Context;
838 Context.setDiscardValueNames(LTODiscardValueNames);
839
840 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000841 auto TheModule =
842 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
843 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000844
845 // CodeGen
Mehdi Aminib2990462017-01-20 22:45:34 +0000846 auto OutputBuffer = codegen(*TheModule);
847 if (SavedObjectsDirectoryPath.empty())
848 ProducedBinaries[count] = std::move(OutputBuffer);
849 else
850 ProducedBinaryFiles[count] = writeGeneratedObject(
851 count, "", SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000852 }, count++);
853 }
854
855 return;
856 }
857
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000858 // Sequential linking phase
859 auto Index = linkCombinedIndex();
860
861 // Save temps: index.
862 if (!SaveTempsDir.empty()) {
863 auto SaveTempPath = SaveTempsDir + "index.bc";
864 std::error_code EC;
865 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
866 if (EC)
867 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
868 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000869 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000870 }
871
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000872
873 // Prepare the module map.
874 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000875 auto ModuleCount = Modules.size();
876
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000877 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000878 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000879 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
880
Teresa Johnson6c475a72017-01-05 21:34:18 +0000881 // Convert the preserved symbols set from string to GUID, this is needed for
882 // computing the caching hash and the internalization.
883 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000884 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000885
886 // Compute "dead" symbols, we don't want to import/export these!
887 auto DeadSymbols = computeDeadSymbols(*Index, GUIDPreservedSymbols);
888
Mehdi Amini01e32132016-03-26 05:40:34 +0000889 // Collect the import/export lists for all modules from the call-graph in the
890 // combined index.
891 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
892 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000893 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000894 ExportLists, &DeadSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000895
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000896 // We use a std::map here to be able to have a defined ordering when
897 // producing a hash for the cache entry.
898 // FIXME: we should be able to compute the caching hash for the entry based
899 // on the index, and nuke this map.
900 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
901
902 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
903 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000904 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000905
Mehdi Amini1380edf2017-02-03 07:41:43 +0000906 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000907 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000908 return (ExportList != ExportLists.end() &&
909 ExportList->second.count(GUID)) ||
910 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000911 };
912
913 // Use global summary-based analysis to identify symbols that can be
914 // internalized (because they aren't exported or preserved as per callback).
915 // Changes are made in the index, consumed in the ThinLTO backends.
916 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
917
Teresa Johnson141149f2016-05-24 18:44:01 +0000918 // Make sure that every module has an entry in the ExportLists and
919 // ResolvedODR maps to enable threaded access to these maps below.
920 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000921 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000922 ResolvedODR[DefinedGVSummaries.first()];
923 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000924
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000925 // Compute the ordering we will process the inputs: the rough heuristic here
926 // is to sort them per size so that the largest module get schedule as soon as
927 // possible. This is purely a compile-time optimization.
928 std::vector<int> ModulesOrdering;
929 ModulesOrdering.resize(Modules.size());
930 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
931 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
932 [&](int LeftIndex, int RightIndex) {
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000933 auto LSize = Modules[LeftIndex].getBuffer().size();
934 auto RSize = Modules[RightIndex].getBuffer().size();
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000935 return LSize > RSize;
936 });
937
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000938 // Parallel optimizer + codegen
939 {
940 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000941 for (auto IndexCount : ModulesOrdering) {
942 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000943 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000944 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000945 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000946
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000947 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
948
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000949 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000950 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
951 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000952 ResolvedODR[ModuleIdentifier],
Mehdi Aminic92b6122017-01-10 00:55:47 +0000953 DefinedFunctions, GUIDPreservedSymbols,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000954 OptLevel, Freestanding, TMBuilder);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000955 auto CacheEntryPath = CacheEntry.getEntryPath();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000956
957 {
958 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000959 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000960 << CacheEntryPath << "' for buffer " << count << " "
961 << ModuleIdentifier << "\n");
Mehdi Amini059464f2016-04-24 03:18:01 +0000962
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000963 if (ErrOrBuffer) {
964 // Cache Hit!
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000965 if (SavedObjectsDirectoryPath.empty())
966 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
967 else
968 ProducedBinaryFiles[count] = writeGeneratedObject(
969 count, CacheEntryPath, SavedObjectsDirectoryPath,
970 *ErrOrBuffer.get());
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000971 return;
972 }
973 }
974
975 LLVMContext Context;
976 Context.setDiscardValueNames(LTODiscardValueNames);
977 Context.enableDebugTypeODRUniquing();
Davide Italiano690ed9d2017-02-10 23:49:38 +0000978 auto DiagFileOrErr = lto::setupOptimizationRemarks(
979 Context, LTORemarksFilename, LTOPassRemarksWithHotness, count);
Mehdi Amini19f176b2016-11-19 18:20:05 +0000980 if (!DiagFileOrErr) {
981 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
982 report_fatal_error("ThinLTO: Can't get an output file for the "
983 "remarks");
984 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000985
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000986 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000987 auto TheModule =
988 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
989 /*IsImporting*/ false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000990
991 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000992 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000993
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000994 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000995 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000996 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000997 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000998 ExportList, GUIDPreservedSymbols,
999 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Aminib5a46c12017-03-28 18:55:44 +00001000 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001001
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001002 // Commit to the cache (if enabled)
1003 CacheEntry.write(*OutputBuffer);
1004
1005 if (SavedObjectsDirectoryPath.empty()) {
1006 // We need to generated a memory buffer for the linker.
1007 if (!CacheEntryPath.empty()) {
1008 // Cache is enabled, reload from the cache
1009 // We do this to lower memory pressuree: the buffer is on the heap
1010 // and releasing it frees memory that can be used for the next input
1011 // file. The final binary link will read from the VFS cache
1012 // (hopefully!) or from disk if the memory pressure wasn't too high.
1013 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1014 if (auto EC = ReloadedBufferOrErr.getError()) {
1015 // On error, keeping the preexisting buffer and printing a
1016 // diagnostic is more friendly than just crashing.
1017 errs() << "error: can't reload cached file '" << CacheEntryPath
1018 << "': " << EC.message() << "\n";
1019 } else {
1020 OutputBuffer = std::move(*ReloadedBufferOrErr);
1021 }
1022 }
1023 ProducedBinaries[count] = std::move(OutputBuffer);
1024 return;
1025 }
1026 ProducedBinaryFiles[count] = writeGeneratedObject(
1027 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001028 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001029 }
1030 }
1031
Peter Collingbournecead56f2017-03-15 22:54:18 +00001032 pruneCache(CacheOptions.Path, CacheOptions.Policy);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001033
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001034 // If statistics were requested, print them out now.
1035 if (llvm::AreStatisticsEnabled())
1036 llvm::PrintStatistics();
1037}