blob: abcd8905ad35677dacef57c12d44873ac6a1ddda [file] [log] [blame]
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001//===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Thin Link Time Optimization library. This library is
11// intended to be used by linker to optimize code at link time.
12//
13//===----------------------------------------------------------------------===//
14
Peter Collingbourne5c732202016-07-14 21:21:16 +000015#include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000016
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000017#include "llvm/ADT/Statistic.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000018#include "llvm/ADT/StringExtras.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000019#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Piotr Padlewskid9830eb2016-09-26 20:37:32 +000020#include "llvm/Analysis/ProfileSummaryInfo.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000023#include "llvm/Bitcode/BitcodeReader.h"
24#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000025#include "llvm/Bitcode/BitcodeWriterPass.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000026#include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
Adrian Prantl981a7992017-05-20 00:00:08 +000027#include "llvm/IR/DebugInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000028#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000029#include "llvm/IR/LLVMContext.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000030#include "llvm/IR/LegacyPassManager.h"
31#include "llvm/IR/Mangler.h"
Adrian Prantl981a7992017-05-20 00:00:08 +000032#include "llvm/IR/Verifier.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000033#include "llvm/IRReader/IRReader.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000034#include "llvm/LTO/LTO.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000035#include "llvm/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000036#include "llvm/Object/IRObjectFile.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000037#include "llvm/Support/CachePruning.h"
38#include "llvm/Support/Debug.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000039#include "llvm/Support/Error.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000040#include "llvm/Support/Path.h"
41#include "llvm/Support/SHA1.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000042#include "llvm/Support/TargetRegistry.h"
43#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000044#include "llvm/Support/Threading.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000045#include "llvm/Support/ToolOutputFile.h"
Peter Collingbourne942fa562017-04-13 01:26:12 +000046#include "llvm/Support/VCSRevision.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000047#include "llvm/Target/TargetMachine.h"
48#include "llvm/Transforms/IPO.h"
49#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000050#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000051#include "llvm/Transforms/IPO/PassManagerBuilder.h"
52#include "llvm/Transforms/ObjCARC.h"
53#include "llvm/Transforms/Utils/FunctionImportUtils.h"
54
Mehdi Amini819e9cd2016-05-16 19:33:07 +000055#include <numeric>
56
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000057using namespace llvm;
58
Mehdi Amini1aafabf2016-04-16 07:02:16 +000059#define DEBUG_TYPE "thinlto"
60
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000061namespace llvm {
62// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
63extern cl::opt<bool> LTODiscardValueNames;
Mehdi Amini19f176b2016-11-19 18:20:05 +000064extern cl::opt<std::string> LTORemarksFilename;
Adam Nemet4c207a62016-12-02 17:53:56 +000065extern cl::opt<bool> LTOPassRemarksWithHotness;
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000066}
67
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000068namespace {
69
Teresa Johnsonec544c52016-10-19 17:35:01 +000070static cl::opt<int>
71 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000072
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000073// Simple helper to save temporary files for debug.
74static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
75 unsigned count, StringRef Suffix) {
76 if (TempDir.empty())
77 return;
78 // User asked to save temps, let dump the bitcode file after import.
Benjamin Kramer3a13ed62017-12-28 16:58:54 +000079 std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000080 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000081 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000082 if (EC)
83 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
84 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +000085 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000086}
87
Teresa Johnson4d2613f2016-05-24 17:24:25 +000088static const GlobalValueSummary *
89getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
90 // If there is any strong definition anywhere, get it.
91 auto StrongDefForLinker = llvm::find_if(
92 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
93 auto Linkage = Summary->linkage();
94 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
95 !GlobalValue::isWeakForLinker(Linkage);
96 });
97 if (StrongDefForLinker != GVSummaryList.end())
98 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +000099 // Get the first *linker visible* definition for this global in the summary
100 // list.
101 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000102 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
103 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000104 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
105 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000106 // Extern templates can be emitted as available_externally.
107 if (FirstDefForLinker == GVSummaryList.end())
108 return nullptr;
109 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000110}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000111
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000112// Populate map of GUID to the prevailing copy for any multiply defined
113// symbols. Currently assume first copy is prevailing, or any strong
114// definition. Can be refined with Linker information in the future.
115static void computePrevailingCopies(
116 const ModuleSummaryIndex &Index,
117 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000118 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
119 return GVSummaryList.size() > 1;
120 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000121
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000122 for (auto &I : Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000123 if (HasMultipleCopies(I.second.SummaryList))
124 PrevailingCopy[I.first] =
125 getFirstDefinitionForLinker(I.second.SummaryList);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000126 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000127}
128
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000129static StringMap<MemoryBufferRef>
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000130generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000131 StringMap<MemoryBufferRef> ModuleMap;
132 for (auto &ModuleBuffer : Modules) {
133 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
134 ModuleMap.end() &&
135 "Expect unique Buffer Identifier");
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000136 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000137 }
138 return ModuleMap;
139}
140
Teresa Johnson26ab5772016-03-15 00:04:37 +0000141static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000142 if (renameModuleForThinLTO(TheModule, Index))
143 report_fatal_error("renameModuleForThinLTO failed");
144}
145
Adrian Prantl981a7992017-05-20 00:00:08 +0000146namespace {
147class ThinLTODiagnosticInfo : public DiagnosticInfo {
148 const Twine &Msg;
149public:
150 ThinLTODiagnosticInfo(const Twine &DiagMsg,
151 DiagnosticSeverity Severity = DS_Error)
152 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
153 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
154};
155}
156
157/// Verify the module and strip broken debug info.
158static void verifyLoadedModule(Module &TheModule) {
159 bool BrokenDebugInfo = false;
Adrian Prantla8b2ddb2017-10-02 18:31:29 +0000160 if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
Adrian Prantl981a7992017-05-20 00:00:08 +0000161 report_fatal_error("Broken module found, compilation aborted!");
162 if (BrokenDebugInfo) {
163 TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
164 "Invalid debug info found, debug info will be stripped", DS_Warning));
165 StripDebugInfo(TheModule);
166 }
167}
168
Peter Collingbournedac43b42016-12-01 05:52:32 +0000169static std::unique_ptr<Module>
170loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000171 bool Lazy, bool IsImporting) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000172 SMDiagnostic Err;
173 Expected<std::unique_ptr<Module>> ModuleOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000174 Lazy
175 ? getLazyBitcodeModule(Buffer, Context,
176 /* ShouldLazyLoadMetadata */ true, IsImporting)
177 : parseBitcodeFile(Buffer, Context);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000178 if (!ModuleOrErr) {
179 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
180 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
181 SourceMgr::DK_Error, EIB.message());
182 Err.print("ThinLTO", errs());
183 });
184 report_fatal_error("Can't load module, abort.");
185 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000186 if (!Lazy)
187 verifyLoadedModule(*ModuleOrErr.get());
Peter Collingbournedac43b42016-12-01 05:52:32 +0000188 return std::move(ModuleOrErr.get());
189}
190
Mehdi Amini01e32132016-03-26 05:40:34 +0000191static void
192crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
193 StringMap<MemoryBufferRef> &ModuleMap,
194 const FunctionImporter::ImportMapTy &ImportList) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000195 auto Loader = [&](StringRef Identifier) {
196 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000197 /*Lazy=*/true, /*IsImporting*/ true);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000198 };
199
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000200 FunctionImporter Importer(Index, Loader);
Adrian Prantl66043792017-05-19 23:32:21 +0000201 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
Mehdi Amini83a807e2017-01-08 00:30:27 +0000202 if (!Result) {
203 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
204 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
205 SourceMgr::DK_Error, EIB.message());
206 Err.print("ThinLTO", errs());
207 });
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000208 report_fatal_error("importFunctions failed");
Mehdi Amini83a807e2017-01-08 00:30:27 +0000209 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000210 // Verify again after cross-importing.
211 verifyLoadedModule(TheModule);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000212}
213
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000214static void optimizeModule(Module &TheModule, TargetMachine &TM,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000215 unsigned OptLevel, bool Freestanding) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000216 // Populate the PassManager
217 PassManagerBuilder PMB;
218 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000219 if (Freestanding)
220 PMB.LibraryInfo->disableAllFunctions();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000221 PMB.Inliner = createFunctionInliningPass();
222 // FIXME: should get it from the bitcode?
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000223 PMB.OptLevel = OptLevel;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000224 PMB.LoopVectorize = true;
225 PMB.SLPVectorize = true;
Adrian Prantl981a7992017-05-20 00:00:08 +0000226 // Already did this in verifyLoadedModule().
227 PMB.VerifyInput = false;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000228 PMB.VerifyOutput = false;
229
230 legacy::PassManager PM;
231
232 // Add the TTI (required to inform the vectorizer about register size for
233 // instance)
234 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
235
236 // Add optimizations
237 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000238
239 PM.run(TheModule);
240}
241
Mehdi Amini059464f2016-04-24 03:18:01 +0000242// Convert the PreservedSymbols map from "Name" based to "GUID" based.
243static DenseSet<GlobalValue::GUID>
Mehdi Amini1380edf2017-02-03 07:41:43 +0000244computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
245 const Triple &TheTriple) {
246 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
247 for (auto &Entry : PreservedSymbols) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000248 StringRef Name = Entry.first();
249 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
250 Name = Name.drop_front();
Mehdi Amini1380edf2017-02-03 07:41:43 +0000251 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
Mehdi Amini059464f2016-04-24 03:18:01 +0000252 }
Mehdi Amini1380edf2017-02-03 07:41:43 +0000253 return GUIDPreservedSymbols;
Mehdi Amini059464f2016-04-24 03:18:01 +0000254}
255
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000256std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
257 TargetMachine &TM) {
258 SmallVector<char, 128> OutputBuffer;
259
260 // CodeGen
261 {
262 raw_svector_ostream OS(OutputBuffer);
263 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000264
265 // If the bitcode files contain ARC code and were compiled with optimization,
266 // the ObjCARCContractPass must be run, so do it unconditionally here.
267 PM.add(createObjCARCContractPass());
268
269 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000270 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
271 /* DisableVerify */ true))
272 report_fatal_error("Failed to setup codegen");
273
274 // Run codegen now. resulting binary is in OutputBuffer.
275 PM.run(TheModule);
276 }
277 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
278}
279
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000280/// Manage caching for a single Module.
281class ModuleCacheEntry {
282 SmallString<128> EntryPath;
283
284public:
285 // Create a cache entry. This compute a unique hash for the Module considering
286 // the current list of export/import, and offer an interface to query to
287 // access the content in the cache.
288 ModuleCacheEntry(
289 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
290 const FunctionImporter::ImportMapTy &ImportList,
291 const FunctionImporter::ExportSetTy &ExportList,
292 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000293 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminic92b6122017-01-10 00:55:47 +0000294 const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000295 bool Freestanding, const TargetMachineBuilder &TMBuilder) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000296 if (CachePath.empty())
297 return;
298
Mehdi Amini00fa1402016-10-08 04:44:18 +0000299 if (!Index.modulePaths().count(ModuleID))
300 // The module does not have an entry, it can't have a hash at all
301 return;
302
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000303 // Compute the unique hash for this entry
304 // This is based on the current compiler version, the module itself, the
305 // export list, the hash for every single module in the import list, the
306 // list of ResolvedODR for the module, and the list of preserved symbols.
307
Mehdi Aminif82bda02016-10-08 04:44:23 +0000308 // Include the hash for the current module
309 auto ModHash = Index.getModuleHash(ModuleID);
310
311 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
312 // No hash entry, no caching!
313 return;
314
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000315 SHA1 Hasher;
316
Mehdi Aminic92b6122017-01-10 00:55:47 +0000317 // Include the parts of the LTO configuration that affect code generation.
318 auto AddString = [&](StringRef Str) {
319 Hasher.update(Str);
320 Hasher.update(ArrayRef<uint8_t>{0});
321 };
322 auto AddUnsigned = [&](unsigned I) {
323 uint8_t Data[4];
324 Data[0] = I;
325 Data[1] = I >> 8;
326 Data[2] = I >> 16;
327 Data[3] = I >> 24;
328 Hasher.update(ArrayRef<uint8_t>{Data, 4});
329 };
330
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000331 // Start with the compiler revision
332 Hasher.update(LLVM_VERSION_STRING);
Peter Collingbourne942fa562017-04-13 01:26:12 +0000333#ifdef LLVM_REVISION
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000334 Hasher.update(LLVM_REVISION);
335#endif
336
Mehdi Aminic92b6122017-01-10 00:55:47 +0000337 // Hash the optimization level and the target machine settings.
338 AddString(TMBuilder.MCpu);
339 // FIXME: Hash more of Options. For now all clients initialize Options from
340 // command-line flags (which is unsupported in production), but may set
341 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
342 // DataSections and DebuggerTuning via command line flags.
343 AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
344 AddUnsigned(TMBuilder.Options.FunctionSections);
345 AddUnsigned(TMBuilder.Options.DataSections);
346 AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
347 AddString(TMBuilder.MAttr);
348 if (TMBuilder.RelocModel)
349 AddUnsigned(*TMBuilder.RelocModel);
350 AddUnsigned(TMBuilder.CGOptLevel);
351 AddUnsigned(OptLevel);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000352 AddUnsigned(Freestanding);
Mehdi Aminic92b6122017-01-10 00:55:47 +0000353
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000354 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
355 for (auto F : ExportList)
356 // The export list can impact the internalization, be conservative here
357 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
358
359 // Include the hash for every module we import functions from
360 for (auto &Entry : ImportList) {
361 auto ModHash = Index.getModuleHash(Entry.first());
362 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
363 }
364
365 // Include the hash for the resolved ODR.
366 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000367 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000368 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000369 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000370 sizeof(GlobalValue::LinkageTypes)));
371 }
372
373 // Include the hash for the preserved symbols.
374 for (auto &Entry : PreservedSymbols) {
375 if (DefinedFunctions.count(Entry))
376 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000377 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000378 }
379
Peter Collingbourne25a17ba2017-03-20 16:41:57 +0000380 // This choice of file name allows the cache to be pruned (see pruneCache()
381 // in include/llvm/Support/CachePruning.h).
382 sys::path::append(EntryPath, CachePath,
383 "llvmcache-" + toHex(Hasher.result()));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000384 }
385
Mehdi Amini059464f2016-04-24 03:18:01 +0000386 // Access the path to this entry in the cache.
387 StringRef getEntryPath() { return EntryPath; }
388
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000389 // Try loading the buffer for this cache entry.
390 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
391 if (EntryPath.empty())
392 return std::error_code();
393 return MemoryBuffer::getFile(EntryPath);
394 }
395
396 // Cache the Produced object file
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000397 void write(const MemoryBuffer &OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000398 if (EntryPath.empty())
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000399 return;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000400
401 // Write to a temporary to avoid race condition
402 SmallString<128> TempFilename;
403 int TempFD;
404 std::error_code EC =
405 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
406 if (EC) {
407 errs() << "Error: " << EC.message() << "\n";
408 report_fatal_error("ThinLTO: Can't get a temporary file");
409 }
410 {
411 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000412 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000413 }
414 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000415 EC = sys::fs::rename(TempFilename, EntryPath);
416 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000417 sys::fs::remove(TempFilename);
418 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
419 if (EC)
420 report_fatal_error(Twine("Failed to open ") + EntryPath +
421 " to save cached entry\n");
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000422 OS << OutputBuffer.getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000423 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000424 }
425};
426
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000427static std::unique_ptr<MemoryBuffer>
428ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
429 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
430 const FunctionImporter::ImportMapTy &ImportList,
431 const FunctionImporter::ExportSetTy &ExportList,
432 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
433 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000434 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000435 bool DisableCodeGen, StringRef SaveTempsDir,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000436 bool Freestanding, unsigned OptLevel, unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000437
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000438 // "Benchmark"-like optimization: single-source case
439 bool SingleModule = (ModuleMap.size() == 1);
440
441 if (!SingleModule) {
442 promoteModule(TheModule, Index);
443
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000444 // Apply summary-based LinkOnce/Weak resolution decisions.
445 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000446
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000447 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000448 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000449 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000450
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000451 // Be friendly and don't nuke totally the module when the client didn't
452 // supply anything to preserve.
453 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
454 // Apply summary-based internalization decisions.
455 thinLTOInternalizeModule(TheModule, DefinedGlobals);
456 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000457
458 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000459 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000460
461 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000462 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000463
464 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000465 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000466 }
467
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000468 optimizeModule(TheModule, TM, OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000469
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000470 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000471
Mehdi Amini43b657b2016-04-01 06:47:02 +0000472 if (DisableCodeGen) {
473 // Configured to stop before CodeGen, serialize the bitcode and return.
474 SmallVector<char, 128> OutputBuffer;
475 {
476 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000477 ProfileSummaryInfo PSI(TheModule);
Teresa Johnson94624ac2017-05-10 18:52:16 +0000478 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000479 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000480 }
481 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
482 }
483
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000484 return codegenModule(TheModule, TM);
485}
486
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000487/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
488/// for caching, and in the \p Index for application during the ThinLTO
489/// backends. This is needed for correctness for exported symbols (ensure
490/// at least one copy kept) and a compile-time optimization (to drop duplicate
491/// copies when possible).
492static void resolveWeakForLinkerInIndex(
493 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000494 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
495 &ResolvedODR) {
496
497 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
498 computePrevailingCopies(Index, PrevailingCopy);
499
500 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
501 const auto &Prevailing = PrevailingCopy.find(GUID);
502 // Not in map means that there was only one copy, which must be prevailing.
503 if (Prevailing == PrevailingCopy.end())
504 return true;
505 return Prevailing->second == S;
506 };
507
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000508 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
509 GlobalValue::GUID GUID,
510 GlobalValue::LinkageTypes NewLinkage) {
511 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
512 };
513
Peter Collingbourne73589f32016-07-07 18:31:51 +0000514 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000515}
516
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000517// Initialize the TargetMachine builder for a given Triple
518static void initTMBuilder(TargetMachineBuilder &TMBuilder,
519 const Triple &TheTriple) {
520 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
521 // FIXME this looks pretty terrible...
522 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
523 if (TheTriple.getArch() == llvm::Triple::x86_64)
524 TMBuilder.MCpu = "core2";
525 else if (TheTriple.getArch() == llvm::Triple::x86)
526 TMBuilder.MCpu = "yonah";
527 else if (TheTriple.getArch() == llvm::Triple::aarch64)
528 TMBuilder.MCpu = "cyclone";
529 }
530 TMBuilder.TheTriple = std::move(TheTriple);
531}
532
533} // end anonymous namespace
534
535void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
Johan Engelendcebe4f2017-09-17 18:11:26 +0000536 ThinLTOBuffer Buffer(Data, Identifier);
Akira Hatanakab10bff12017-05-18 03:52:29 +0000537 LLVMContext Context;
538 StringRef TripleStr;
539 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
540 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
541
542 if (TripleOrErr)
543 TripleStr = *TripleOrErr;
544
545 Triple TheTriple(TripleStr);
546
547 if (Modules.empty())
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000548 initTMBuilder(TMBuilder, Triple(TheTriple));
Akira Hatanakab10bff12017-05-18 03:52:29 +0000549 else if (TMBuilder.TheTriple != TheTriple) {
550 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
551 report_fatal_error("ThinLTO modules with incompatible triples not "
552 "supported");
553 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000554 }
Akira Hatanakab10bff12017-05-18 03:52:29 +0000555
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000556 Modules.push_back(Buffer);
557}
558
559void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
560 PreservedSymbols.insert(Name);
561}
562
563void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000564 // FIXME: At the moment, we don't take advantage of this extra information,
565 // we're conservatively considering cross-references as preserved.
566 // CrossReferencedSymbols.insert(Name);
567 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000568}
569
570// TargetMachine factory
571std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
572 std::string ErrMsg;
573 const Target *TheTarget =
574 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
575 if (!TheTarget) {
576 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
577 }
578
579 // Use MAttr as the default set of features.
580 SubtargetFeatures Features(MAttr);
581 Features.getDefaultSubtargetFeatures(TheTriple);
582 std::string FeatureStr = Features.getString();
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000583
Rafael Espindola79e238a2017-08-03 02:16:21 +0000584 return std::unique_ptr<TargetMachine>(
585 TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options,
586 RelocModel, None, CGOptLevel));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000587}
588
589/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000590 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000591 * "thin-link".
592 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000593std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000594 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
595 llvm::make_unique<ModuleSummaryIndex>();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000596 uint64_t NextModuleId = 0;
597 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000598 if (Error Err = readModuleSummaryIndex(ModuleBuffer.getMemBuffer(),
599 *CombinedIndex, NextModuleId++)) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000600 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000601 logAllUnhandledErrors(
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000602 std::move(Err), errs(),
Peter Collingbournec15d60b2017-05-01 20:42:32 +0000603 "error: can't create module summary index for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000604 return nullptr;
605 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000606 }
607 return CombinedIndex;
608}
609
610/**
611 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000612 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000613 */
614void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000615 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000616 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000617 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000618
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000619 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000620 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000621 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000622
Teresa Johnson6c475a72017-01-05 21:34:18 +0000623 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000624 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000625 PreservedSymbols, Triple(TheModule.getTargetTriple()));
626
627 // Compute "dead" symbols, we don't want to import/export these!
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000628 computeDeadSymbols(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000629
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000630 // Generate import/export list
631 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
632 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
633 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000634 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000635
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000636 // Resolve LinkOnce/Weak symbols.
637 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000638 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000639
640 thinLTOResolveWeakForLinkerModule(
641 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000642
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000643 // Promote the exported values in the index, so that they are promoted
644 // in the module.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000645 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000646 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000647 return (ExportList != ExportLists.end() &&
648 ExportList->second.count(GUID)) ||
649 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000650 };
651 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
652
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000653 promoteModule(TheModule, Index);
654}
655
656/**
657 * Perform cross-module importing for the module identified by ModuleIdentifier.
658 */
659void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000660 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000661 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000662 auto ModuleCount = Index.modulePaths().size();
663
664 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000665 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000666 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000667
Teresa Johnson6c475a72017-01-05 21:34:18 +0000668 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000669 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000670 PreservedSymbols, Triple(TheModule.getTargetTriple()));
671
672 // Compute "dead" symbols, we don't want to import/export these!
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000673 computeDeadSymbols(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000674
Mehdi Amini01e32132016-03-26 05:40:34 +0000675 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000676 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
677 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000678 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000679 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000680 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
681
682 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000683}
684
685/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000686 * Compute the list of summaries needed for importing into module.
687 */
688void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
689 StringRef ModulePath, ModuleSummaryIndex &Index,
690 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
691 auto ModuleCount = Index.modulePaths().size();
692
693 // Collect for each module the list of function it defines (GUID -> Summary).
694 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
695 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
696
697 // Generate import/export list
698 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
699 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
700 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
701 ExportLists);
702
703 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000704 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000705 ModuleToSummariesForIndex);
706}
707
708/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000709 * Emit the list of files needed for importing into module.
710 */
711void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
712 StringRef OutputName,
713 ModuleSummaryIndex &Index) {
714 auto ModuleCount = Index.modulePaths().size();
715
716 // Collect for each module the list of function it defines (GUID -> Summary).
717 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
718 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
719
720 // Generate import/export list
721 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
722 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
723 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
724 ExportLists);
725
726 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000727 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000728 report_fatal_error(Twine("Failed to open ") + OutputName +
729 " to save imports lists\n");
730}
731
732/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000733 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000734 */
735void ThinLTOCodeGenerator::internalize(Module &TheModule,
736 ModuleSummaryIndex &Index) {
737 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
738 auto ModuleCount = Index.modulePaths().size();
739 auto ModuleIdentifier = TheModule.getModuleIdentifier();
740
741 // Convert the preserved symbols set from string to GUID
742 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000743 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Amini059464f2016-04-24 03:18:01 +0000744
745 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000746 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000747 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
748
Teresa Johnson6c475a72017-01-05 21:34:18 +0000749 // Compute "dead" symbols, we don't want to import/export these!
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000750 computeDeadSymbols(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000751
Mehdi Amini059464f2016-04-24 03:18:01 +0000752 // Generate import/export list
753 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
754 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
755 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000756 ExportLists);
Mehdi Amini059464f2016-04-24 03:18:01 +0000757 auto &ExportList = ExportLists[ModuleIdentifier];
758
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000759 // Be friendly and don't nuke totally the module when the client didn't
760 // supply anything to preserve.
761 if (ExportList.empty() && GUIDPreservedSymbols.empty())
762 return;
763
Mehdi Amini059464f2016-04-24 03:18:01 +0000764 // Internalization
Mehdi Amini1380edf2017-02-03 07:41:43 +0000765 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000766 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000767 return (ExportList != ExportLists.end() &&
768 ExportList->second.count(GUID)) ||
769 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000770 };
771 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
772 thinLTOInternalizeModule(TheModule,
773 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000774}
775
776/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000777 * Perform post-importing ThinLTO optimizations.
778 */
779void ThinLTOCodeGenerator::optimize(Module &TheModule) {
780 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000781
782 // Optimize now
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000783 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000784}
785
786/**
787 * Perform ThinLTO CodeGen.
788 */
789std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
790 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
791 return codegenModule(TheModule, *TMBuilder.create());
792}
793
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000794/// Write out the generated object file, either from CacheEntryPath or from
795/// OutputBuffer, preferring hard-link when possible.
796/// Returns the path to the generated file in SavedObjectsDirectoryPath.
797static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
798 StringRef SavedObjectsDirectoryPath,
799 const MemoryBuffer &OutputBuffer) {
800 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
801 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
802 OutputPath.c_str(); // Ensure the string is null terminated.
803 if (sys::fs::exists(OutputPath))
804 sys::fs::remove(OutputPath);
805
806 // We don't return a memory buffer to the linker, just a list of files.
807 if (!CacheEntryPath.empty()) {
808 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
809 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
810 if (!Err)
811 return OutputPath.str();
812 // Hard linking failed, try to copy.
813 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
814 if (!Err)
815 return OutputPath.str();
816 // Copy failed (could be because the CacheEntry was removed from the cache
817 // in the meantime by another process), fall back and try to write down the
818 // buffer to the output.
819 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
820 << "' to '" << OutputPath << "'\n";
821 }
822 // No cache entry, just write out the buffer.
823 std::error_code Err;
824 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
825 if (Err)
826 report_fatal_error("Can't open output '" + OutputPath + "'\n");
827 OS << OutputBuffer.getBuffer();
828 return OutputPath.str();
829}
830
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000831// Main entry point for the ThinLTO processing
832void ThinLTOCodeGenerator::run() {
Mehdi Aminib2990462017-01-20 22:45:34 +0000833 // Prepare the resulting object vector
834 assert(ProducedBinaries.empty() && "The generator should not be reused");
835 if (SavedObjectsDirectoryPath.empty())
836 ProducedBinaries.resize(Modules.size());
837 else {
838 sys::fs::create_directories(SavedObjectsDirectoryPath);
839 bool IsDir;
840 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
841 if (!IsDir)
842 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
843 ProducedBinaryFiles.resize(Modules.size());
844 }
845
Mehdi Amini43b657b2016-04-01 06:47:02 +0000846 if (CodeGenOnly) {
847 // Perform only parallel codegen and return.
848 ThreadPool Pool;
Mehdi Amini43b657b2016-04-01 06:47:02 +0000849 int count = 0;
850 for (auto &ModuleBuffer : Modules) {
851 Pool.async([&](int count) {
852 LLVMContext Context;
853 Context.setDiscardValueNames(LTODiscardValueNames);
854
855 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000856 auto TheModule =
857 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
858 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000859
860 // CodeGen
Mehdi Aminib2990462017-01-20 22:45:34 +0000861 auto OutputBuffer = codegen(*TheModule);
862 if (SavedObjectsDirectoryPath.empty())
863 ProducedBinaries[count] = std::move(OutputBuffer);
864 else
865 ProducedBinaryFiles[count] = writeGeneratedObject(
866 count, "", SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000867 }, count++);
868 }
869
870 return;
871 }
872
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000873 // Sequential linking phase
874 auto Index = linkCombinedIndex();
875
876 // Save temps: index.
877 if (!SaveTempsDir.empty()) {
878 auto SaveTempPath = SaveTempsDir + "index.bc";
879 std::error_code EC;
880 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
881 if (EC)
882 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
883 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000884 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000885 }
886
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000887
888 // Prepare the module map.
889 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000890 auto ModuleCount = Modules.size();
891
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000892 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000893 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000894 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
895
Teresa Johnson6c475a72017-01-05 21:34:18 +0000896 // Convert the preserved symbols set from string to GUID, this is needed for
897 // computing the caching hash and the internalization.
898 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000899 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000900
901 // Compute "dead" symbols, we don't want to import/export these!
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000902 computeDeadSymbols(*Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000903
Mehdi Amini01e32132016-03-26 05:40:34 +0000904 // Collect the import/export lists for all modules from the call-graph in the
905 // combined index.
906 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
907 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000908 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000909 ExportLists);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000910
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000911 // We use a std::map here to be able to have a defined ordering when
912 // producing a hash for the cache entry.
913 // FIXME: we should be able to compute the caching hash for the entry based
914 // on the index, and nuke this map.
915 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
916
917 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
918 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000919 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000920
Mehdi Amini1380edf2017-02-03 07:41:43 +0000921 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000922 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000923 return (ExportList != ExportLists.end() &&
924 ExportList->second.count(GUID)) ||
925 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000926 };
927
928 // Use global summary-based analysis to identify symbols that can be
929 // internalized (because they aren't exported or preserved as per callback).
930 // Changes are made in the index, consumed in the ThinLTO backends.
931 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
932
Teresa Johnson141149f2016-05-24 18:44:01 +0000933 // Make sure that every module has an entry in the ExportLists and
934 // ResolvedODR maps to enable threaded access to these maps below.
935 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000936 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000937 ResolvedODR[DefinedGVSummaries.first()];
938 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000939
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000940 // Compute the ordering we will process the inputs: the rough heuristic here
941 // is to sort them per size so that the largest module get schedule as soon as
942 // possible. This is purely a compile-time optimization.
943 std::vector<int> ModulesOrdering;
944 ModulesOrdering.resize(Modules.size());
945 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
946 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
947 [&](int LeftIndex, int RightIndex) {
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000948 auto LSize = Modules[LeftIndex].getBuffer().size();
949 auto RSize = Modules[RightIndex].getBuffer().size();
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000950 return LSize > RSize;
951 });
952
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000953 // Parallel optimizer + codegen
954 {
955 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000956 for (auto IndexCount : ModulesOrdering) {
957 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000958 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000959 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000960 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000961
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000962 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
963
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000964 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000965 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
966 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000967 ResolvedODR[ModuleIdentifier],
Mehdi Aminic92b6122017-01-10 00:55:47 +0000968 DefinedFunctions, GUIDPreservedSymbols,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000969 OptLevel, Freestanding, TMBuilder);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000970 auto CacheEntryPath = CacheEntry.getEntryPath();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000971
972 {
973 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000974 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000975 << CacheEntryPath << "' for buffer " << count << " "
976 << ModuleIdentifier << "\n");
Mehdi Amini059464f2016-04-24 03:18:01 +0000977
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000978 if (ErrOrBuffer) {
979 // Cache Hit!
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000980 if (SavedObjectsDirectoryPath.empty())
981 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
982 else
983 ProducedBinaryFiles[count] = writeGeneratedObject(
984 count, CacheEntryPath, SavedObjectsDirectoryPath,
985 *ErrOrBuffer.get());
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000986 return;
987 }
988 }
989
990 LLVMContext Context;
991 Context.setDiscardValueNames(LTODiscardValueNames);
992 Context.enableDebugTypeODRUniquing();
Davide Italiano690ed9d2017-02-10 23:49:38 +0000993 auto DiagFileOrErr = lto::setupOptimizationRemarks(
994 Context, LTORemarksFilename, LTOPassRemarksWithHotness, count);
Mehdi Amini19f176b2016-11-19 18:20:05 +0000995 if (!DiagFileOrErr) {
996 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
997 report_fatal_error("ThinLTO: Can't get an output file for the "
998 "remarks");
999 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001000
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001001 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +00001002 auto TheModule =
1003 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
1004 /*IsImporting*/ false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001005
1006 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +00001007 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001008
Mehdi Amini1aafabf2016-04-16 07:02:16 +00001009 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +00001010 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001011 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +00001012 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +00001013 ExportList, GUIDPreservedSymbols,
1014 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Aminib5a46c12017-03-28 18:55:44 +00001015 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001016
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001017 // Commit to the cache (if enabled)
1018 CacheEntry.write(*OutputBuffer);
1019
1020 if (SavedObjectsDirectoryPath.empty()) {
1021 // We need to generated a memory buffer for the linker.
1022 if (!CacheEntryPath.empty()) {
1023 // Cache is enabled, reload from the cache
1024 // We do this to lower memory pressuree: the buffer is on the heap
1025 // and releasing it frees memory that can be used for the next input
1026 // file. The final binary link will read from the VFS cache
1027 // (hopefully!) or from disk if the memory pressure wasn't too high.
1028 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1029 if (auto EC = ReloadedBufferOrErr.getError()) {
1030 // On error, keeping the preexisting buffer and printing a
1031 // diagnostic is more friendly than just crashing.
1032 errs() << "error: can't reload cached file '" << CacheEntryPath
1033 << "': " << EC.message() << "\n";
1034 } else {
1035 OutputBuffer = std::move(*ReloadedBufferOrErr);
1036 }
1037 }
1038 ProducedBinaries[count] = std::move(OutputBuffer);
1039 return;
1040 }
1041 ProducedBinaryFiles[count] = writeGeneratedObject(
1042 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001043 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001044 }
1045 }
1046
Peter Collingbournecead56f2017-03-15 22:54:18 +00001047 pruneCache(CacheOptions.Path, CacheOptions.Policy);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001048
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001049 // If statistics were requested, print them out now.
1050 if (llvm::AreStatisticsEnabled())
1051 llvm::PrintStatistics();
James Henderson852f6fd2017-05-16 09:43:21 +00001052 reportAndResetTimings();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001053}