blob: aa4d32a9c57463809e56ee1276a9c56eac174ac2 [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,
190 unsigned OptLevel) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000191 // Populate the PassManager
192 PassManagerBuilder PMB;
193 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
194 PMB.Inliner = createFunctionInliningPass();
195 // FIXME: should get it from the bitcode?
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000196 PMB.OptLevel = OptLevel;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000197 PMB.LoopVectorize = true;
198 PMB.SLPVectorize = true;
199 PMB.VerifyInput = true;
200 PMB.VerifyOutput = false;
201
202 legacy::PassManager PM;
203
204 // Add the TTI (required to inform the vectorizer about register size for
205 // instance)
206 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
207
208 // Add optimizations
209 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000210
211 PM.run(TheModule);
212}
213
Mehdi Amini059464f2016-04-24 03:18:01 +0000214// Convert the PreservedSymbols map from "Name" based to "GUID" based.
215static DenseSet<GlobalValue::GUID>
Mehdi Amini1380edf2017-02-03 07:41:43 +0000216computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
217 const Triple &TheTriple) {
218 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
219 for (auto &Entry : PreservedSymbols) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000220 StringRef Name = Entry.first();
221 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
222 Name = Name.drop_front();
Mehdi Amini1380edf2017-02-03 07:41:43 +0000223 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
Mehdi Amini059464f2016-04-24 03:18:01 +0000224 }
Mehdi Amini1380edf2017-02-03 07:41:43 +0000225 return GUIDPreservedSymbols;
Mehdi Amini059464f2016-04-24 03:18:01 +0000226}
227
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000228std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
229 TargetMachine &TM) {
230 SmallVector<char, 128> OutputBuffer;
231
232 // CodeGen
233 {
234 raw_svector_ostream OS(OutputBuffer);
235 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000236
237 // If the bitcode files contain ARC code and were compiled with optimization,
238 // the ObjCARCContractPass must be run, so do it unconditionally here.
239 PM.add(createObjCARCContractPass());
240
241 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000242 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
243 /* DisableVerify */ true))
244 report_fatal_error("Failed to setup codegen");
245
246 // Run codegen now. resulting binary is in OutputBuffer.
247 PM.run(TheModule);
248 }
249 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
250}
251
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000252/// Manage caching for a single Module.
253class ModuleCacheEntry {
254 SmallString<128> EntryPath;
255
256public:
257 // Create a cache entry. This compute a unique hash for the Module considering
258 // the current list of export/import, and offer an interface to query to
259 // access the content in the cache.
260 ModuleCacheEntry(
261 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
262 const FunctionImporter::ImportMapTy &ImportList,
263 const FunctionImporter::ExportSetTy &ExportList,
264 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000265 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminic92b6122017-01-10 00:55:47 +0000266 const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
267 const TargetMachineBuilder &TMBuilder) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000268 if (CachePath.empty())
269 return;
270
Mehdi Amini00fa1402016-10-08 04:44:18 +0000271 if (!Index.modulePaths().count(ModuleID))
272 // The module does not have an entry, it can't have a hash at all
273 return;
274
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000275 // Compute the unique hash for this entry
276 // This is based on the current compiler version, the module itself, the
277 // export list, the hash for every single module in the import list, the
278 // list of ResolvedODR for the module, and the list of preserved symbols.
279
Mehdi Aminif82bda02016-10-08 04:44:23 +0000280 // Include the hash for the current module
281 auto ModHash = Index.getModuleHash(ModuleID);
282
283 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
284 // No hash entry, no caching!
285 return;
286
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000287 SHA1 Hasher;
288
Mehdi Aminic92b6122017-01-10 00:55:47 +0000289 // Include the parts of the LTO configuration that affect code generation.
290 auto AddString = [&](StringRef Str) {
291 Hasher.update(Str);
292 Hasher.update(ArrayRef<uint8_t>{0});
293 };
294 auto AddUnsigned = [&](unsigned I) {
295 uint8_t Data[4];
296 Data[0] = I;
297 Data[1] = I >> 8;
298 Data[2] = I >> 16;
299 Data[3] = I >> 24;
300 Hasher.update(ArrayRef<uint8_t>{Data, 4});
301 };
302
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000303 // Start with the compiler revision
304 Hasher.update(LLVM_VERSION_STRING);
305#ifdef HAVE_LLVM_REVISION
306 Hasher.update(LLVM_REVISION);
307#endif
308
Mehdi Aminic92b6122017-01-10 00:55:47 +0000309 // Hash the optimization level and the target machine settings.
310 AddString(TMBuilder.MCpu);
311 // FIXME: Hash more of Options. For now all clients initialize Options from
312 // command-line flags (which is unsupported in production), but may set
313 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
314 // DataSections and DebuggerTuning via command line flags.
315 AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
316 AddUnsigned(TMBuilder.Options.FunctionSections);
317 AddUnsigned(TMBuilder.Options.DataSections);
318 AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
319 AddString(TMBuilder.MAttr);
320 if (TMBuilder.RelocModel)
321 AddUnsigned(*TMBuilder.RelocModel);
322 AddUnsigned(TMBuilder.CGOptLevel);
323 AddUnsigned(OptLevel);
324
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000325 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
326 for (auto F : ExportList)
327 // The export list can impact the internalization, be conservative here
328 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
329
330 // Include the hash for every module we import functions from
331 for (auto &Entry : ImportList) {
332 auto ModHash = Index.getModuleHash(Entry.first());
333 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
334 }
335
336 // Include the hash for the resolved ODR.
337 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000338 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000339 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000340 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000341 sizeof(GlobalValue::LinkageTypes)));
342 }
343
344 // Include the hash for the preserved symbols.
345 for (auto &Entry : PreservedSymbols) {
346 if (DefinedFunctions.count(Entry))
347 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000348 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000349 }
350
Peter Collingbourne25a17ba2017-03-20 16:41:57 +0000351 // This choice of file name allows the cache to be pruned (see pruneCache()
352 // in include/llvm/Support/CachePruning.h).
353 sys::path::append(EntryPath, CachePath,
354 "llvmcache-" + toHex(Hasher.result()));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000355 }
356
Mehdi Amini059464f2016-04-24 03:18:01 +0000357 // Access the path to this entry in the cache.
358 StringRef getEntryPath() { return EntryPath; }
359
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000360 // Try loading the buffer for this cache entry.
361 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
362 if (EntryPath.empty())
363 return std::error_code();
364 return MemoryBuffer::getFile(EntryPath);
365 }
366
367 // Cache the Produced object file
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000368 void write(const MemoryBuffer &OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000369 if (EntryPath.empty())
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000370 return;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000371
372 // Write to a temporary to avoid race condition
373 SmallString<128> TempFilename;
374 int TempFD;
375 std::error_code EC =
376 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
377 if (EC) {
378 errs() << "Error: " << EC.message() << "\n";
379 report_fatal_error("ThinLTO: Can't get a temporary file");
380 }
381 {
382 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000383 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000384 }
385 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000386 EC = sys::fs::rename(TempFilename, EntryPath);
387 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000388 sys::fs::remove(TempFilename);
389 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
390 if (EC)
391 report_fatal_error(Twine("Failed to open ") + EntryPath +
392 " to save cached entry\n");
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000393 OS << OutputBuffer.getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000394 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000395 }
396};
397
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000398static std::unique_ptr<MemoryBuffer>
399ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
400 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
401 const FunctionImporter::ImportMapTy &ImportList,
402 const FunctionImporter::ExportSetTy &ExportList,
403 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
404 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000405 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000406 bool DisableCodeGen, StringRef SaveTempsDir,
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000407 unsigned OptLevel, unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000408
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000409 // "Benchmark"-like optimization: single-source case
410 bool SingleModule = (ModuleMap.size() == 1);
411
412 if (!SingleModule) {
413 promoteModule(TheModule, Index);
414
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000415 // Apply summary-based LinkOnce/Weak resolution decisions.
416 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000417
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000418 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000419 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000420 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000421
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000422 // Be friendly and don't nuke totally the module when the client didn't
423 // supply anything to preserve.
424 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
425 // Apply summary-based internalization decisions.
426 thinLTOInternalizeModule(TheModule, DefinedGlobals);
427 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000428
429 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000430 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000431
432 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000433 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000434
435 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000436 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000437 }
438
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000439 optimizeModule(TheModule, TM, OptLevel);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000440
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000441 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000442
Mehdi Amini43b657b2016-04-01 06:47:02 +0000443 if (DisableCodeGen) {
444 // Configured to stop before CodeGen, serialize the bitcode and return.
445 SmallVector<char, 128> OutputBuffer;
446 {
447 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000448 ProfileSummaryInfo PSI(TheModule);
Piotr Padlewskid9830eb2016-09-26 20:37:32 +0000449 auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000450 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000451 }
452 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
453 }
454
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000455 return codegenModule(TheModule, TM);
456}
457
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000458/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
459/// for caching, and in the \p Index for application during the ThinLTO
460/// backends. This is needed for correctness for exported symbols (ensure
461/// at least one copy kept) and a compile-time optimization (to drop duplicate
462/// copies when possible).
463static void resolveWeakForLinkerInIndex(
464 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000465 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
466 &ResolvedODR) {
467
468 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
469 computePrevailingCopies(Index, PrevailingCopy);
470
471 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
472 const auto &Prevailing = PrevailingCopy.find(GUID);
473 // Not in map means that there was only one copy, which must be prevailing.
474 if (Prevailing == PrevailingCopy.end())
475 return true;
476 return Prevailing->second == S;
477 };
478
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000479 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
480 GlobalValue::GUID GUID,
481 GlobalValue::LinkageTypes NewLinkage) {
482 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
483 };
484
Peter Collingbourne73589f32016-07-07 18:31:51 +0000485 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000486}
487
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000488// Initialize the TargetMachine builder for a given Triple
489static void initTMBuilder(TargetMachineBuilder &TMBuilder,
490 const Triple &TheTriple) {
491 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
492 // FIXME this looks pretty terrible...
493 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
494 if (TheTriple.getArch() == llvm::Triple::x86_64)
495 TMBuilder.MCpu = "core2";
496 else if (TheTriple.getArch() == llvm::Triple::x86)
497 TMBuilder.MCpu = "yonah";
498 else if (TheTriple.getArch() == llvm::Triple::aarch64)
499 TMBuilder.MCpu = "cyclone";
500 }
501 TMBuilder.TheTriple = std::move(TheTriple);
502}
503
504} // end anonymous namespace
505
506void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000507 ThinLTOBuffer Buffer(Data, Identifier);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000508 if (Modules.empty()) {
509 // First module added, so initialize the triple and some options
510 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000511 StringRef TripleStr;
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000512 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
513 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
Peter Collingbournecd513a42016-11-11 19:50:24 +0000514 if (TripleOrErr)
515 TripleStr = *TripleOrErr;
516 Triple TheTriple(TripleStr);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000517 initTMBuilder(TMBuilder, Triple(TheTriple));
518 }
519#ifndef NDEBUG
520 else {
521 LLVMContext Context;
Peter Collingbournecd513a42016-11-11 19:50:24 +0000522 StringRef TripleStr;
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000523 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
524 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
Peter Collingbournecd513a42016-11-11 19:50:24 +0000525 if (TripleOrErr)
526 TripleStr = *TripleOrErr;
527 assert(TMBuilder.TheTriple.str() == TripleStr &&
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000528 "ThinLTO modules with different triple not supported");
529 }
530#endif
531 Modules.push_back(Buffer);
532}
533
534void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
535 PreservedSymbols.insert(Name);
536}
537
538void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000539 // FIXME: At the moment, we don't take advantage of this extra information,
540 // we're conservatively considering cross-references as preserved.
541 // CrossReferencedSymbols.insert(Name);
542 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000543}
544
545// TargetMachine factory
546std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
547 std::string ErrMsg;
548 const Target *TheTarget =
549 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
550 if (!TheTarget) {
551 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
552 }
553
554 // Use MAttr as the default set of features.
555 SubtargetFeatures Features(MAttr);
556 Features.getDefaultSubtargetFeatures(TheTriple);
557 std::string FeatureStr = Features.getString();
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000558
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000559 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
560 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
561 CodeModel::Default, CGOptLevel));
562}
563
564/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000565 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000566 * "thin-link".
567 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000568std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
569 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000570 uint64_t NextModuleId = 0;
571 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000572 Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000573 object::ModuleSummaryIndexObjectFile::create(
574 ModuleBuffer.getMemBuffer());
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000575 if (!ObjOrErr) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000576 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000577 logAllUnhandledErrors(
578 ObjOrErr.takeError(), errs(),
579 "error: can't create ModuleSummaryIndexObjectFile for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000580 return nullptr;
581 }
582 auto Index = (*ObjOrErr)->takeIndex();
583 if (CombinedIndex) {
584 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
585 } else {
586 CombinedIndex = std::move(Index);
587 }
588 }
589 return CombinedIndex;
590}
591
592/**
593 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000594 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000595 */
596void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000597 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000598 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000599 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000600
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000601 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000602 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000603 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000604
Teresa Johnson6c475a72017-01-05 21:34:18 +0000605 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000606 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000607 PreservedSymbols, Triple(TheModule.getTargetTriple()));
608
609 // Compute "dead" symbols, we don't want to import/export these!
610 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
611
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000612 // Generate import/export list
613 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
614 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
615 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000616 ExportLists, &DeadSymbols);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000617
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000618 // Resolve LinkOnce/Weak symbols.
619 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000620 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000621
622 thinLTOResolveWeakForLinkerModule(
623 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000624
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000625 // Promote the exported values in the index, so that they are promoted
626 // in the module.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000627 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000628 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000629 return (ExportList != ExportLists.end() &&
630 ExportList->second.count(GUID)) ||
631 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000632 };
633 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
634
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000635 promoteModule(TheModule, Index);
636}
637
638/**
639 * Perform cross-module importing for the module identified by ModuleIdentifier.
640 */
641void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000642 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000643 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000644 auto ModuleCount = Index.modulePaths().size();
645
646 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000647 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000648 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000649
Teresa Johnson6c475a72017-01-05 21:34:18 +0000650 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000651 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000652 PreservedSymbols, Triple(TheModule.getTargetTriple()));
653
654 // Compute "dead" symbols, we don't want to import/export these!
655 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
656
Mehdi Amini01e32132016-03-26 05:40:34 +0000657 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000658 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
659 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000660 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000661 ExportLists, &DeadSymbols);
Mehdi Amini01e32132016-03-26 05:40:34 +0000662 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
663
664 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000665}
666
667/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000668 * Compute the list of summaries needed for importing into module.
669 */
670void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
671 StringRef ModulePath, ModuleSummaryIndex &Index,
672 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
673 auto ModuleCount = Index.modulePaths().size();
674
675 // Collect for each module the list of function it defines (GUID -> Summary).
676 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
677 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
678
679 // Generate import/export list
680 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
681 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
682 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
683 ExportLists);
684
685 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000686 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000687 ModuleToSummariesForIndex);
688}
689
690/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000691 * Emit the list of files needed for importing into module.
692 */
693void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
694 StringRef OutputName,
695 ModuleSummaryIndex &Index) {
696 auto ModuleCount = Index.modulePaths().size();
697
698 // Collect for each module the list of function it defines (GUID -> Summary).
699 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
700 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
701
702 // Generate import/export list
703 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
704 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
705 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
706 ExportLists);
707
708 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000709 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000710 report_fatal_error(Twine("Failed to open ") + OutputName +
711 " to save imports lists\n");
712}
713
714/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000715 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000716 */
717void ThinLTOCodeGenerator::internalize(Module &TheModule,
718 ModuleSummaryIndex &Index) {
719 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
720 auto ModuleCount = Index.modulePaths().size();
721 auto ModuleIdentifier = TheModule.getModuleIdentifier();
722
723 // Convert the preserved symbols set from string to GUID
724 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000725 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Amini059464f2016-04-24 03:18:01 +0000726
727 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000728 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000729 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
730
Teresa Johnson6c475a72017-01-05 21:34:18 +0000731 // Compute "dead" symbols, we don't want to import/export these!
732 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
733
Mehdi Amini059464f2016-04-24 03:18:01 +0000734 // Generate import/export list
735 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
736 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
737 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000738 ExportLists, &DeadSymbols);
Mehdi Amini059464f2016-04-24 03:18:01 +0000739 auto &ExportList = ExportLists[ModuleIdentifier];
740
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000741 // Be friendly and don't nuke totally the module when the client didn't
742 // supply anything to preserve.
743 if (ExportList.empty() && GUIDPreservedSymbols.empty())
744 return;
745
Mehdi Amini059464f2016-04-24 03:18:01 +0000746 // Internalization
Mehdi Amini1380edf2017-02-03 07:41:43 +0000747 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000748 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000749 return (ExportList != ExportLists.end() &&
750 ExportList->second.count(GUID)) ||
751 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000752 };
753 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
754 thinLTOInternalizeModule(TheModule,
755 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000756}
757
758/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000759 * Perform post-importing ThinLTO optimizations.
760 */
761void ThinLTOCodeGenerator::optimize(Module &TheModule) {
762 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000763
764 // Optimize now
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000765 optimizeModule(TheModule, *TMBuilder.create(), OptLevel);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000766}
767
768/**
769 * Perform ThinLTO CodeGen.
770 */
771std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
772 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
773 return codegenModule(TheModule, *TMBuilder.create());
774}
775
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000776/// Write out the generated object file, either from CacheEntryPath or from
777/// OutputBuffer, preferring hard-link when possible.
778/// Returns the path to the generated file in SavedObjectsDirectoryPath.
779static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
780 StringRef SavedObjectsDirectoryPath,
781 const MemoryBuffer &OutputBuffer) {
782 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
783 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
784 OutputPath.c_str(); // Ensure the string is null terminated.
785 if (sys::fs::exists(OutputPath))
786 sys::fs::remove(OutputPath);
787
788 // We don't return a memory buffer to the linker, just a list of files.
789 if (!CacheEntryPath.empty()) {
790 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
791 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
792 if (!Err)
793 return OutputPath.str();
794 // Hard linking failed, try to copy.
795 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
796 if (!Err)
797 return OutputPath.str();
798 // Copy failed (could be because the CacheEntry was removed from the cache
799 // in the meantime by another process), fall back and try to write down the
800 // buffer to the output.
801 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
802 << "' to '" << OutputPath << "'\n";
803 }
804 // No cache entry, just write out the buffer.
805 std::error_code Err;
806 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
807 if (Err)
808 report_fatal_error("Can't open output '" + OutputPath + "'\n");
809 OS << OutputBuffer.getBuffer();
810 return OutputPath.str();
811}
812
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000813// Main entry point for the ThinLTO processing
814void ThinLTOCodeGenerator::run() {
Mehdi Aminib2990462017-01-20 22:45:34 +0000815 // Prepare the resulting object vector
816 assert(ProducedBinaries.empty() && "The generator should not be reused");
817 if (SavedObjectsDirectoryPath.empty())
818 ProducedBinaries.resize(Modules.size());
819 else {
820 sys::fs::create_directories(SavedObjectsDirectoryPath);
821 bool IsDir;
822 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
823 if (!IsDir)
824 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
825 ProducedBinaryFiles.resize(Modules.size());
826 }
827
Mehdi Amini43b657b2016-04-01 06:47:02 +0000828 if (CodeGenOnly) {
829 // Perform only parallel codegen and return.
830 ThreadPool Pool;
Mehdi Amini43b657b2016-04-01 06:47:02 +0000831 int count = 0;
832 for (auto &ModuleBuffer : Modules) {
833 Pool.async([&](int count) {
834 LLVMContext Context;
835 Context.setDiscardValueNames(LTODiscardValueNames);
836
837 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000838 auto TheModule =
839 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
840 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000841
842 // CodeGen
Mehdi Aminib2990462017-01-20 22:45:34 +0000843 auto OutputBuffer = codegen(*TheModule);
844 if (SavedObjectsDirectoryPath.empty())
845 ProducedBinaries[count] = std::move(OutputBuffer);
846 else
847 ProducedBinaryFiles[count] = writeGeneratedObject(
848 count, "", SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000849 }, 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
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000869
870 // Prepare the module map.
871 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000872 auto ModuleCount = Modules.size();
873
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000874 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000875 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000876 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
877
Teresa Johnson6c475a72017-01-05 21:34:18 +0000878 // Convert the preserved symbols set from string to GUID, this is needed for
879 // computing the caching hash and the internalization.
880 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000881 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000882
883 // Compute "dead" symbols, we don't want to import/export these!
884 auto DeadSymbols = computeDeadSymbols(*Index, GUIDPreservedSymbols);
885
Mehdi Amini01e32132016-03-26 05:40:34 +0000886 // Collect the import/export lists for all modules from the call-graph in the
887 // combined index.
888 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
889 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000890 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000891 ExportLists, &DeadSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000892
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000893 // We use a std::map here to be able to have a defined ordering when
894 // producing a hash for the cache entry.
895 // FIXME: we should be able to compute the caching hash for the entry based
896 // on the index, and nuke this map.
897 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
898
899 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
900 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000901 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000902
Mehdi Amini1380edf2017-02-03 07:41:43 +0000903 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000904 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000905 return (ExportList != ExportLists.end() &&
906 ExportList->second.count(GUID)) ||
907 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000908 };
909
910 // Use global summary-based analysis to identify symbols that can be
911 // internalized (because they aren't exported or preserved as per callback).
912 // Changes are made in the index, consumed in the ThinLTO backends.
913 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
914
Teresa Johnson141149f2016-05-24 18:44:01 +0000915 // Make sure that every module has an entry in the ExportLists and
916 // ResolvedODR maps to enable threaded access to these maps below.
917 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000918 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000919 ResolvedODR[DefinedGVSummaries.first()];
920 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000921
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000922 // Compute the ordering we will process the inputs: the rough heuristic here
923 // is to sort them per size so that the largest module get schedule as soon as
924 // possible. This is purely a compile-time optimization.
925 std::vector<int> ModulesOrdering;
926 ModulesOrdering.resize(Modules.size());
927 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
928 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
929 [&](int LeftIndex, int RightIndex) {
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000930 auto LSize = Modules[LeftIndex].getBuffer().size();
931 auto RSize = Modules[RightIndex].getBuffer().size();
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000932 return LSize > RSize;
933 });
934
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000935 // Parallel optimizer + codegen
936 {
937 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000938 for (auto IndexCount : ModulesOrdering) {
939 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000940 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000941 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000942 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000943
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000944 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
945
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000946 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000947 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
948 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000949 ResolvedODR[ModuleIdentifier],
Mehdi Aminic92b6122017-01-10 00:55:47 +0000950 DefinedFunctions, GUIDPreservedSymbols,
951 OptLevel, TMBuilder);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000952 auto CacheEntryPath = CacheEntry.getEntryPath();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000953
954 {
955 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000956 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000957 << CacheEntryPath << "' for buffer " << count << " "
958 << ModuleIdentifier << "\n");
Mehdi Amini059464f2016-04-24 03:18:01 +0000959
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000960 if (ErrOrBuffer) {
961 // Cache Hit!
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000962 if (SavedObjectsDirectoryPath.empty())
963 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
964 else
965 ProducedBinaryFiles[count] = writeGeneratedObject(
966 count, CacheEntryPath, SavedObjectsDirectoryPath,
967 *ErrOrBuffer.get());
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000968 return;
969 }
970 }
971
972 LLVMContext Context;
973 Context.setDiscardValueNames(LTODiscardValueNames);
974 Context.enableDebugTypeODRUniquing();
Davide Italiano690ed9d2017-02-10 23:49:38 +0000975 auto DiagFileOrErr = lto::setupOptimizationRemarks(
976 Context, LTORemarksFilename, LTOPassRemarksWithHotness, count);
Mehdi Amini19f176b2016-11-19 18:20:05 +0000977 if (!DiagFileOrErr) {
978 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
979 report_fatal_error("ThinLTO: Can't get an output file for the "
980 "remarks");
981 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000982
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000983 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000984 auto TheModule =
985 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
986 /*IsImporting*/ false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000987
988 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000989 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000990
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000991 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000992 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000993 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000994 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000995 ExportList, GUIDPreservedSymbols,
996 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000997 DisableCodeGen, SaveTempsDir, OptLevel, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000998
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000999 // Commit to the cache (if enabled)
1000 CacheEntry.write(*OutputBuffer);
1001
1002 if (SavedObjectsDirectoryPath.empty()) {
1003 // We need to generated a memory buffer for the linker.
1004 if (!CacheEntryPath.empty()) {
1005 // Cache is enabled, reload from the cache
1006 // We do this to lower memory pressuree: the buffer is on the heap
1007 // and releasing it frees memory that can be used for the next input
1008 // file. The final binary link will read from the VFS cache
1009 // (hopefully!) or from disk if the memory pressure wasn't too high.
1010 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1011 if (auto EC = ReloadedBufferOrErr.getError()) {
1012 // On error, keeping the preexisting buffer and printing a
1013 // diagnostic is more friendly than just crashing.
1014 errs() << "error: can't reload cached file '" << CacheEntryPath
1015 << "': " << EC.message() << "\n";
1016 } else {
1017 OutputBuffer = std::move(*ReloadedBufferOrErr);
1018 }
1019 }
1020 ProducedBinaries[count] = std::move(OutputBuffer);
1021 return;
1022 }
1023 ProducedBinaryFiles[count] = writeGeneratedObject(
1024 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001025 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001026 }
1027 }
1028
Peter Collingbournecead56f2017-03-15 22:54:18 +00001029 pruneCache(CacheOptions.Path, CacheOptions.Policy);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001030
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001031 // If statistics were requested, print them out now.
1032 if (llvm::AreStatisticsEnabled())
1033 llvm::PrintStatistics();
1034}