blob: e4094d44867b2d5ef057ce6cd5408d6c991e4ac9 [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/Linker/Linker.h"
36#include "llvm/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000037#include "llvm/Object/IRObjectFile.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000038#include "llvm/Support/CachePruning.h"
39#include "llvm/Support/Debug.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000040#include "llvm/Support/Error.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000041#include "llvm/Support/Path.h"
42#include "llvm/Support/SHA1.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000043#include "llvm/Support/TargetRegistry.h"
44#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000045#include "llvm/Support/Threading.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000046#include "llvm/Support/ToolOutputFile.h"
Peter Collingbourne942fa562017-04-13 01:26:12 +000047#include "llvm/Support/VCSRevision.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000048#include "llvm/Target/TargetMachine.h"
49#include "llvm/Transforms/IPO.h"
50#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000051#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000052#include "llvm/Transforms/IPO/PassManagerBuilder.h"
53#include "llvm/Transforms/ObjCARC.h"
54#include "llvm/Transforms/Utils/FunctionImportUtils.h"
55
Mehdi Amini819e9cd2016-05-16 19:33:07 +000056#include <numeric>
57
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000058using namespace llvm;
59
Mehdi Amini1aafabf2016-04-16 07:02:16 +000060#define DEBUG_TYPE "thinlto"
61
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000062namespace llvm {
63// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
64extern cl::opt<bool> LTODiscardValueNames;
Mehdi Amini19f176b2016-11-19 18:20:05 +000065extern cl::opt<std::string> LTORemarksFilename;
Adam Nemet4c207a62016-12-02 17:53:56 +000066extern cl::opt<bool> LTOPassRemarksWithHotness;
Adrian Prantl981a7992017-05-20 00:00:08 +000067extern cl::opt<bool> LTOStripInvalidDebugInfo;
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000068}
69
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000070namespace {
71
Teresa Johnsonec544c52016-10-19 17:35:01 +000072static cl::opt<int>
73 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000074
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000075// Simple helper to save temporary files for debug.
76static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
77 unsigned count, StringRef Suffix) {
78 if (TempDir.empty())
79 return;
80 // User asked to save temps, let dump the bitcode file after import.
Teresa Johnsonc44a1222016-08-15 23:24:57 +000081 std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000082 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000083 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000084 if (EC)
85 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
86 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +000087 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000088}
89
Teresa Johnson4d2613f2016-05-24 17:24:25 +000090static const GlobalValueSummary *
91getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
92 // If there is any strong definition anywhere, get it.
93 auto StrongDefForLinker = llvm::find_if(
94 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
95 auto Linkage = Summary->linkage();
96 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
97 !GlobalValue::isWeakForLinker(Linkage);
98 });
99 if (StrongDefForLinker != GVSummaryList.end())
100 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000101 // Get the first *linker visible* definition for this global in the summary
102 // list.
103 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000104 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
105 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000106 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
107 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000108 // Extern templates can be emitted as available_externally.
109 if (FirstDefForLinker == GVSummaryList.end())
110 return nullptr;
111 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000112}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000113
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000114// Populate map of GUID to the prevailing copy for any multiply defined
115// symbols. Currently assume first copy is prevailing, or any strong
116// definition. Can be refined with Linker information in the future.
117static void computePrevailingCopies(
118 const ModuleSummaryIndex &Index,
119 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000120 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
121 return GVSummaryList.size() > 1;
122 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000123
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000124 for (auto &I : Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000125 if (HasMultipleCopies(I.second.SummaryList))
126 PrevailingCopy[I.first] =
127 getFirstDefinitionForLinker(I.second.SummaryList);
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
Adrian Prantl981a7992017-05-20 00:00:08 +0000148namespace {
149class ThinLTODiagnosticInfo : public DiagnosticInfo {
150 const Twine &Msg;
151public:
152 ThinLTODiagnosticInfo(const Twine &DiagMsg,
153 DiagnosticSeverity Severity = DS_Error)
154 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
155 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
156};
157}
158
159/// Verify the module and strip broken debug info.
160static void verifyLoadedModule(Module &TheModule) {
161 bool BrokenDebugInfo = false;
162 if (verifyModule(TheModule, &dbgs(),
163 LTOStripInvalidDebugInfo ? &BrokenDebugInfo : nullptr))
164 report_fatal_error("Broken module found, compilation aborted!");
165 if (BrokenDebugInfo) {
166 TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
167 "Invalid debug info found, debug info will be stripped", DS_Warning));
168 StripDebugInfo(TheModule);
169 }
170}
171
Peter Collingbournedac43b42016-12-01 05:52:32 +0000172static std::unique_ptr<Module>
173loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000174 bool Lazy, bool IsImporting) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000175 SMDiagnostic Err;
176 Expected<std::unique_ptr<Module>> ModuleOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000177 Lazy
178 ? getLazyBitcodeModule(Buffer, Context,
179 /* ShouldLazyLoadMetadata */ true, IsImporting)
180 : parseBitcodeFile(Buffer, Context);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000181 if (!ModuleOrErr) {
182 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
183 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
184 SourceMgr::DK_Error, EIB.message());
185 Err.print("ThinLTO", errs());
186 });
187 report_fatal_error("Can't load module, abort.");
188 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000189 if (!Lazy)
190 verifyLoadedModule(*ModuleOrErr.get());
Peter Collingbournedac43b42016-12-01 05:52:32 +0000191 return std::move(ModuleOrErr.get());
192}
193
Mehdi Amini01e32132016-03-26 05:40:34 +0000194static void
195crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
196 StringMap<MemoryBufferRef> &ModuleMap,
197 const FunctionImporter::ImportMapTy &ImportList) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000198 auto Loader = [&](StringRef Identifier) {
199 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000200 /*Lazy=*/true, /*IsImporting*/ true);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000201 };
202
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000203 FunctionImporter Importer(Index, Loader);
Adrian Prantl66043792017-05-19 23:32:21 +0000204 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
Mehdi Amini83a807e2017-01-08 00:30:27 +0000205 if (!Result) {
206 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
207 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
208 SourceMgr::DK_Error, EIB.message());
209 Err.print("ThinLTO", errs());
210 });
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000211 report_fatal_error("importFunctions failed");
Mehdi Amini83a807e2017-01-08 00:30:27 +0000212 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000213 // Verify again after cross-importing.
214 verifyLoadedModule(TheModule);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000215}
216
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000217static void optimizeModule(Module &TheModule, TargetMachine &TM,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000218 unsigned OptLevel, bool Freestanding) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000219 // Populate the PassManager
220 PassManagerBuilder PMB;
221 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000222 if (Freestanding)
223 PMB.LibraryInfo->disableAllFunctions();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000224 PMB.Inliner = createFunctionInliningPass();
225 // FIXME: should get it from the bitcode?
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000226 PMB.OptLevel = OptLevel;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000227 PMB.LoopVectorize = true;
228 PMB.SLPVectorize = true;
Adrian Prantl981a7992017-05-20 00:00:08 +0000229 // Already did this in verifyLoadedModule().
230 PMB.VerifyInput = false;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000231 PMB.VerifyOutput = false;
232
233 legacy::PassManager PM;
234
235 // Add the TTI (required to inform the vectorizer about register size for
236 // instance)
237 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
238
239 // Add optimizations
240 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000241
242 PM.run(TheModule);
243}
244
Mehdi Amini059464f2016-04-24 03:18:01 +0000245// Convert the PreservedSymbols map from "Name" based to "GUID" based.
246static DenseSet<GlobalValue::GUID>
Mehdi Amini1380edf2017-02-03 07:41:43 +0000247computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
248 const Triple &TheTriple) {
249 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
250 for (auto &Entry : PreservedSymbols) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000251 StringRef Name = Entry.first();
252 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
253 Name = Name.drop_front();
Mehdi Amini1380edf2017-02-03 07:41:43 +0000254 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
Mehdi Amini059464f2016-04-24 03:18:01 +0000255 }
Mehdi Amini1380edf2017-02-03 07:41:43 +0000256 return GUIDPreservedSymbols;
Mehdi Amini059464f2016-04-24 03:18:01 +0000257}
258
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000259std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
260 TargetMachine &TM) {
261 SmallVector<char, 128> OutputBuffer;
262
263 // CodeGen
264 {
265 raw_svector_ostream OS(OutputBuffer);
266 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000267
268 // If the bitcode files contain ARC code and were compiled with optimization,
269 // the ObjCARCContractPass must be run, so do it unconditionally here.
270 PM.add(createObjCARCContractPass());
271
272 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000273 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
274 /* DisableVerify */ true))
275 report_fatal_error("Failed to setup codegen");
276
277 // Run codegen now. resulting binary is in OutputBuffer.
278 PM.run(TheModule);
279 }
280 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
281}
282
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000283/// Manage caching for a single Module.
284class ModuleCacheEntry {
285 SmallString<128> EntryPath;
286
287public:
288 // Create a cache entry. This compute a unique hash for the Module considering
289 // the current list of export/import, and offer an interface to query to
290 // access the content in the cache.
291 ModuleCacheEntry(
292 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
293 const FunctionImporter::ImportMapTy &ImportList,
294 const FunctionImporter::ExportSetTy &ExportList,
295 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000296 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminic92b6122017-01-10 00:55:47 +0000297 const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000298 bool Freestanding, const TargetMachineBuilder &TMBuilder) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000299 if (CachePath.empty())
300 return;
301
Mehdi Amini00fa1402016-10-08 04:44:18 +0000302 if (!Index.modulePaths().count(ModuleID))
303 // The module does not have an entry, it can't have a hash at all
304 return;
305
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000306 // Compute the unique hash for this entry
307 // This is based on the current compiler version, the module itself, the
308 // export list, the hash for every single module in the import list, the
309 // list of ResolvedODR for the module, and the list of preserved symbols.
310
Mehdi Aminif82bda02016-10-08 04:44:23 +0000311 // Include the hash for the current module
312 auto ModHash = Index.getModuleHash(ModuleID);
313
314 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
315 // No hash entry, no caching!
316 return;
317
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000318 SHA1 Hasher;
319
Mehdi Aminic92b6122017-01-10 00:55:47 +0000320 // Include the parts of the LTO configuration that affect code generation.
321 auto AddString = [&](StringRef Str) {
322 Hasher.update(Str);
323 Hasher.update(ArrayRef<uint8_t>{0});
324 };
325 auto AddUnsigned = [&](unsigned I) {
326 uint8_t Data[4];
327 Data[0] = I;
328 Data[1] = I >> 8;
329 Data[2] = I >> 16;
330 Data[3] = I >> 24;
331 Hasher.update(ArrayRef<uint8_t>{Data, 4});
332 };
333
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000334 // Start with the compiler revision
335 Hasher.update(LLVM_VERSION_STRING);
Peter Collingbourne942fa562017-04-13 01:26:12 +0000336#ifdef LLVM_REVISION
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000337 Hasher.update(LLVM_REVISION);
338#endif
339
Mehdi Aminic92b6122017-01-10 00:55:47 +0000340 // Hash the optimization level and the target machine settings.
341 AddString(TMBuilder.MCpu);
342 // FIXME: Hash more of Options. For now all clients initialize Options from
343 // command-line flags (which is unsupported in production), but may set
344 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
345 // DataSections and DebuggerTuning via command line flags.
346 AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
347 AddUnsigned(TMBuilder.Options.FunctionSections);
348 AddUnsigned(TMBuilder.Options.DataSections);
349 AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
350 AddString(TMBuilder.MAttr);
351 if (TMBuilder.RelocModel)
352 AddUnsigned(*TMBuilder.RelocModel);
353 AddUnsigned(TMBuilder.CGOptLevel);
354 AddUnsigned(OptLevel);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000355 AddUnsigned(Freestanding);
Mehdi Aminic92b6122017-01-10 00:55:47 +0000356
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000357 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
358 for (auto F : ExportList)
359 // The export list can impact the internalization, be conservative here
360 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
361
362 // Include the hash for every module we import functions from
363 for (auto &Entry : ImportList) {
364 auto ModHash = Index.getModuleHash(Entry.first());
365 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
366 }
367
368 // Include the hash for the resolved ODR.
369 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000370 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000371 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000372 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000373 sizeof(GlobalValue::LinkageTypes)));
374 }
375
376 // Include the hash for the preserved symbols.
377 for (auto &Entry : PreservedSymbols) {
378 if (DefinedFunctions.count(Entry))
379 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000380 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000381 }
382
Peter Collingbourne25a17ba2017-03-20 16:41:57 +0000383 // This choice of file name allows the cache to be pruned (see pruneCache()
384 // in include/llvm/Support/CachePruning.h).
385 sys::path::append(EntryPath, CachePath,
386 "llvmcache-" + toHex(Hasher.result()));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000387 }
388
Mehdi Amini059464f2016-04-24 03:18:01 +0000389 // Access the path to this entry in the cache.
390 StringRef getEntryPath() { return EntryPath; }
391
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000392 // Try loading the buffer for this cache entry.
393 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
394 if (EntryPath.empty())
395 return std::error_code();
396 return MemoryBuffer::getFile(EntryPath);
397 }
398
399 // Cache the Produced object file
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000400 void write(const MemoryBuffer &OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000401 if (EntryPath.empty())
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000402 return;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000403
404 // Write to a temporary to avoid race condition
405 SmallString<128> TempFilename;
406 int TempFD;
407 std::error_code EC =
408 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
409 if (EC) {
410 errs() << "Error: " << EC.message() << "\n";
411 report_fatal_error("ThinLTO: Can't get a temporary file");
412 }
413 {
414 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000415 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000416 }
417 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000418 EC = sys::fs::rename(TempFilename, EntryPath);
419 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000420 sys::fs::remove(TempFilename);
421 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
422 if (EC)
423 report_fatal_error(Twine("Failed to open ") + EntryPath +
424 " to save cached entry\n");
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000425 OS << OutputBuffer.getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000426 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000427 }
428};
429
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000430static std::unique_ptr<MemoryBuffer>
431ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
432 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
433 const FunctionImporter::ImportMapTy &ImportList,
434 const FunctionImporter::ExportSetTy &ExportList,
435 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
436 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000437 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000438 bool DisableCodeGen, StringRef SaveTempsDir,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000439 bool Freestanding, unsigned OptLevel, unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000440
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000441 // "Benchmark"-like optimization: single-source case
442 bool SingleModule = (ModuleMap.size() == 1);
443
444 if (!SingleModule) {
445 promoteModule(TheModule, Index);
446
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000447 // Apply summary-based LinkOnce/Weak resolution decisions.
448 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000449
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000450 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000451 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000452 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000453
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000454 // Be friendly and don't nuke totally the module when the client didn't
455 // supply anything to preserve.
456 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
457 // Apply summary-based internalization decisions.
458 thinLTOInternalizeModule(TheModule, DefinedGlobals);
459 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000460
461 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000462 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000463
464 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000465 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000466
467 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000468 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000469 }
470
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000471 optimizeModule(TheModule, TM, OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000472
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000473 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000474
Mehdi Amini43b657b2016-04-01 06:47:02 +0000475 if (DisableCodeGen) {
476 // Configured to stop before CodeGen, serialize the bitcode and return.
477 SmallVector<char, 128> OutputBuffer;
478 {
479 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000480 ProfileSummaryInfo PSI(TheModule);
Teresa Johnson94624ac2017-05-10 18:52:16 +0000481 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
Chandler Carruthb7be5b62016-08-19 07:49:19 +0000482 WriteBitcodeToFile(&TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000483 }
484 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
485 }
486
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000487 return codegenModule(TheModule, TM);
488}
489
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000490/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
491/// for caching, and in the \p Index for application during the ThinLTO
492/// backends. This is needed for correctness for exported symbols (ensure
493/// at least one copy kept) and a compile-time optimization (to drop duplicate
494/// copies when possible).
495static void resolveWeakForLinkerInIndex(
496 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000497 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
498 &ResolvedODR) {
499
500 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
501 computePrevailingCopies(Index, PrevailingCopy);
502
503 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
504 const auto &Prevailing = PrevailingCopy.find(GUID);
505 // Not in map means that there was only one copy, which must be prevailing.
506 if (Prevailing == PrevailingCopy.end())
507 return true;
508 return Prevailing->second == S;
509 };
510
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000511 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
512 GlobalValue::GUID GUID,
513 GlobalValue::LinkageTypes NewLinkage) {
514 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
515 };
516
Peter Collingbourne73589f32016-07-07 18:31:51 +0000517 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000518}
519
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000520// Initialize the TargetMachine builder for a given Triple
521static void initTMBuilder(TargetMachineBuilder &TMBuilder,
522 const Triple &TheTriple) {
523 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
524 // FIXME this looks pretty terrible...
525 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
526 if (TheTriple.getArch() == llvm::Triple::x86_64)
527 TMBuilder.MCpu = "core2";
528 else if (TheTriple.getArch() == llvm::Triple::x86)
529 TMBuilder.MCpu = "yonah";
530 else if (TheTriple.getArch() == llvm::Triple::aarch64)
531 TMBuilder.MCpu = "cyclone";
532 }
533 TMBuilder.TheTriple = std::move(TheTriple);
534}
535
536} // end anonymous namespace
537
538void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000539 ThinLTOBuffer Buffer(Data, Identifier);
Akira Hatanakab10bff12017-05-18 03:52:29 +0000540 LLVMContext Context;
541 StringRef TripleStr;
542 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
543 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
544
545 if (TripleOrErr)
546 TripleStr = *TripleOrErr;
547
548 Triple TheTriple(TripleStr);
549
550 if (Modules.empty())
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000551 initTMBuilder(TMBuilder, Triple(TheTriple));
Akira Hatanakab10bff12017-05-18 03:52:29 +0000552 else if (TMBuilder.TheTriple != TheTriple) {
553 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
554 report_fatal_error("ThinLTO modules with incompatible triples not "
555 "supported");
556 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000557 }
Akira Hatanakab10bff12017-05-18 03:52:29 +0000558
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000559 Modules.push_back(Buffer);
560}
561
562void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
563 PreservedSymbols.insert(Name);
564}
565
566void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000567 // FIXME: At the moment, we don't take advantage of this extra information,
568 // we're conservatively considering cross-references as preserved.
569 // CrossReferencedSymbols.insert(Name);
570 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000571}
572
573// TargetMachine factory
574std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
575 std::string ErrMsg;
576 const Target *TheTarget =
577 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
578 if (!TheTarget) {
579 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
580 }
581
582 // Use MAttr as the default set of features.
583 SubtargetFeatures Features(MAttr);
584 Features.getDefaultSubtargetFeatures(TheTriple);
585 std::string FeatureStr = Features.getString();
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000586
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000587 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
588 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
589 CodeModel::Default, CGOptLevel));
590}
591
592/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000593 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000594 * "thin-link".
595 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000596std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000597 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
598 llvm::make_unique<ModuleSummaryIndex>();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000599 uint64_t NextModuleId = 0;
600 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000601 if (Error Err = readModuleSummaryIndex(ModuleBuffer.getMemBuffer(),
602 *CombinedIndex, NextModuleId++)) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000603 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000604 logAllUnhandledErrors(
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000605 std::move(Err), errs(),
Peter Collingbournec15d60b2017-05-01 20:42:32 +0000606 "error: can't create module summary index for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000607 return nullptr;
608 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000609 }
610 return CombinedIndex;
611}
612
613/**
614 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000615 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000616 */
617void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000618 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000619 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000620 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000621
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000622 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000623 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000624 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000625
Teresa Johnson6c475a72017-01-05 21:34:18 +0000626 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000627 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000628 PreservedSymbols, Triple(TheModule.getTargetTriple()));
629
630 // Compute "dead" symbols, we don't want to import/export these!
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000631 computeDeadSymbols(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000632
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000633 // Generate import/export list
634 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
635 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
636 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000637 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000638
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000639 // Resolve LinkOnce/Weak symbols.
640 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000641 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000642
643 thinLTOResolveWeakForLinkerModule(
644 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000645
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000646 // Promote the exported values in the index, so that they are promoted
647 // in the module.
Mehdi Amini1380edf2017-02-03 07:41:43 +0000648 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000649 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000650 return (ExportList != ExportLists.end() &&
651 ExportList->second.count(GUID)) ||
652 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000653 };
654 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
655
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000656 promoteModule(TheModule, Index);
657}
658
659/**
660 * Perform cross-module importing for the module identified by ModuleIdentifier.
661 */
662void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000663 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000664 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000665 auto ModuleCount = Index.modulePaths().size();
666
667 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000668 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000669 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000670
Teresa Johnson6c475a72017-01-05 21:34:18 +0000671 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000672 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000673 PreservedSymbols, Triple(TheModule.getTargetTriple()));
674
675 // Compute "dead" symbols, we don't want to import/export these!
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000676 computeDeadSymbols(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000677
Mehdi Amini01e32132016-03-26 05:40:34 +0000678 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000679 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
680 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000681 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000682 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000683 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
684
685 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000686}
687
688/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000689 * Compute the list of summaries needed for importing into module.
690 */
691void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
692 StringRef ModulePath, ModuleSummaryIndex &Index,
693 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
694 auto ModuleCount = Index.modulePaths().size();
695
696 // Collect for each module the list of function it defines (GUID -> Summary).
697 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
698 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
699
700 // Generate import/export list
701 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
702 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
703 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
704 ExportLists);
705
706 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000707 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000708 ModuleToSummariesForIndex);
709}
710
711/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000712 * Emit the list of files needed for importing into module.
713 */
714void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
715 StringRef OutputName,
716 ModuleSummaryIndex &Index) {
717 auto ModuleCount = Index.modulePaths().size();
718
719 // Collect for each module the list of function it defines (GUID -> Summary).
720 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
721 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
722
723 // Generate import/export list
724 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
725 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
726 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
727 ExportLists);
728
729 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000730 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000731 report_fatal_error(Twine("Failed to open ") + OutputName +
732 " to save imports lists\n");
733}
734
735/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000736 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000737 */
738void ThinLTOCodeGenerator::internalize(Module &TheModule,
739 ModuleSummaryIndex &Index) {
740 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
741 auto ModuleCount = Index.modulePaths().size();
742 auto ModuleIdentifier = TheModule.getModuleIdentifier();
743
744 // Convert the preserved symbols set from string to GUID
745 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000746 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Amini059464f2016-04-24 03:18:01 +0000747
748 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000749 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000750 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
751
Teresa Johnson6c475a72017-01-05 21:34:18 +0000752 // Compute "dead" symbols, we don't want to import/export these!
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000753 computeDeadSymbols(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000754
Mehdi Amini059464f2016-04-24 03:18:01 +0000755 // Generate import/export list
756 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
757 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
758 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000759 ExportLists);
Mehdi Amini059464f2016-04-24 03:18:01 +0000760 auto &ExportList = ExportLists[ModuleIdentifier];
761
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000762 // Be friendly and don't nuke totally the module when the client didn't
763 // supply anything to preserve.
764 if (ExportList.empty() && GUIDPreservedSymbols.empty())
765 return;
766
Mehdi Amini059464f2016-04-24 03:18:01 +0000767 // Internalization
Mehdi Amini1380edf2017-02-03 07:41:43 +0000768 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000769 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000770 return (ExportList != ExportLists.end() &&
771 ExportList->second.count(GUID)) ||
772 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000773 };
774 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
775 thinLTOInternalizeModule(TheModule,
776 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000777}
778
779/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000780 * Perform post-importing ThinLTO optimizations.
781 */
782void ThinLTOCodeGenerator::optimize(Module &TheModule) {
783 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000784
785 // Optimize now
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000786 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000787}
788
789/**
790 * Perform ThinLTO CodeGen.
791 */
792std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
793 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
794 return codegenModule(TheModule, *TMBuilder.create());
795}
796
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000797/// Write out the generated object file, either from CacheEntryPath or from
798/// OutputBuffer, preferring hard-link when possible.
799/// Returns the path to the generated file in SavedObjectsDirectoryPath.
800static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
801 StringRef SavedObjectsDirectoryPath,
802 const MemoryBuffer &OutputBuffer) {
803 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
804 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
805 OutputPath.c_str(); // Ensure the string is null terminated.
806 if (sys::fs::exists(OutputPath))
807 sys::fs::remove(OutputPath);
808
809 // We don't return a memory buffer to the linker, just a list of files.
810 if (!CacheEntryPath.empty()) {
811 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
812 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
813 if (!Err)
814 return OutputPath.str();
815 // Hard linking failed, try to copy.
816 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
817 if (!Err)
818 return OutputPath.str();
819 // Copy failed (could be because the CacheEntry was removed from the cache
820 // in the meantime by another process), fall back and try to write down the
821 // buffer to the output.
822 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
823 << "' to '" << OutputPath << "'\n";
824 }
825 // No cache entry, just write out the buffer.
826 std::error_code Err;
827 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
828 if (Err)
829 report_fatal_error("Can't open output '" + OutputPath + "'\n");
830 OS << OutputBuffer.getBuffer();
831 return OutputPath.str();
832}
833
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000834// Main entry point for the ThinLTO processing
835void ThinLTOCodeGenerator::run() {
Mehdi Aminib2990462017-01-20 22:45:34 +0000836 // Prepare the resulting object vector
837 assert(ProducedBinaries.empty() && "The generator should not be reused");
838 if (SavedObjectsDirectoryPath.empty())
839 ProducedBinaries.resize(Modules.size());
840 else {
841 sys::fs::create_directories(SavedObjectsDirectoryPath);
842 bool IsDir;
843 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
844 if (!IsDir)
845 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
846 ProducedBinaryFiles.resize(Modules.size());
847 }
848
Mehdi Amini43b657b2016-04-01 06:47:02 +0000849 if (CodeGenOnly) {
850 // Perform only parallel codegen and return.
851 ThreadPool Pool;
Mehdi Amini43b657b2016-04-01 06:47:02 +0000852 int count = 0;
853 for (auto &ModuleBuffer : Modules) {
854 Pool.async([&](int count) {
855 LLVMContext Context;
856 Context.setDiscardValueNames(LTODiscardValueNames);
857
858 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000859 auto TheModule =
860 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
861 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000862
863 // CodeGen
Mehdi Aminib2990462017-01-20 22:45:34 +0000864 auto OutputBuffer = codegen(*TheModule);
865 if (SavedObjectsDirectoryPath.empty())
866 ProducedBinaries[count] = std::move(OutputBuffer);
867 else
868 ProducedBinaryFiles[count] = writeGeneratedObject(
869 count, "", SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000870 }, count++);
871 }
872
873 return;
874 }
875
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000876 // Sequential linking phase
877 auto Index = linkCombinedIndex();
878
879 // Save temps: index.
880 if (!SaveTempsDir.empty()) {
881 auto SaveTempPath = SaveTempsDir + "index.bc";
882 std::error_code EC;
883 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
884 if (EC)
885 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
886 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000887 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000888 }
889
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000890
891 // Prepare the module map.
892 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000893 auto ModuleCount = Modules.size();
894
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000895 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000896 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000897 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
898
Teresa Johnson6c475a72017-01-05 21:34:18 +0000899 // Convert the preserved symbols set from string to GUID, this is needed for
900 // computing the caching hash and the internalization.
901 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000902 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000903
904 // Compute "dead" symbols, we don't want to import/export these!
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000905 computeDeadSymbols(*Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000906
Mehdi Amini01e32132016-03-26 05:40:34 +0000907 // Collect the import/export lists for all modules from the call-graph in the
908 // combined index.
909 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
910 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000911 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000912 ExportLists);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000913
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000914 // We use a std::map here to be able to have a defined ordering when
915 // producing a hash for the cache entry.
916 // FIXME: we should be able to compute the caching hash for the entry based
917 // on the index, and nuke this map.
918 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
919
920 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
921 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000922 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000923
Mehdi Amini1380edf2017-02-03 07:41:43 +0000924 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000925 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000926 return (ExportList != ExportLists.end() &&
927 ExportList->second.count(GUID)) ||
928 GUIDPreservedSymbols.count(GUID);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000929 };
930
931 // Use global summary-based analysis to identify symbols that can be
932 // internalized (because they aren't exported or preserved as per callback).
933 // Changes are made in the index, consumed in the ThinLTO backends.
934 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
935
Teresa Johnson141149f2016-05-24 18:44:01 +0000936 // Make sure that every module has an entry in the ExportLists and
937 // ResolvedODR maps to enable threaded access to these maps below.
938 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000939 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000940 ResolvedODR[DefinedGVSummaries.first()];
941 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000942
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000943 // Compute the ordering we will process the inputs: the rough heuristic here
944 // is to sort them per size so that the largest module get schedule as soon as
945 // possible. This is purely a compile-time optimization.
946 std::vector<int> ModulesOrdering;
947 ModulesOrdering.resize(Modules.size());
948 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
949 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
950 [&](int LeftIndex, int RightIndex) {
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000951 auto LSize = Modules[LeftIndex].getBuffer().size();
952 auto RSize = Modules[RightIndex].getBuffer().size();
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000953 return LSize > RSize;
954 });
955
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000956 // Parallel optimizer + codegen
957 {
958 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000959 for (auto IndexCount : ModulesOrdering) {
960 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000961 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000962 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000963 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000964
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000965 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
966
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000967 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000968 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
969 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000970 ResolvedODR[ModuleIdentifier],
Mehdi Aminic92b6122017-01-10 00:55:47 +0000971 DefinedFunctions, GUIDPreservedSymbols,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000972 OptLevel, Freestanding, TMBuilder);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000973 auto CacheEntryPath = CacheEntry.getEntryPath();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000974
975 {
976 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000977 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000978 << CacheEntryPath << "' for buffer " << count << " "
979 << ModuleIdentifier << "\n");
Mehdi Amini059464f2016-04-24 03:18:01 +0000980
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000981 if (ErrOrBuffer) {
982 // Cache Hit!
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000983 if (SavedObjectsDirectoryPath.empty())
984 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
985 else
986 ProducedBinaryFiles[count] = writeGeneratedObject(
987 count, CacheEntryPath, SavedObjectsDirectoryPath,
988 *ErrOrBuffer.get());
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000989 return;
990 }
991 }
992
993 LLVMContext Context;
994 Context.setDiscardValueNames(LTODiscardValueNames);
995 Context.enableDebugTypeODRUniquing();
Davide Italiano690ed9d2017-02-10 23:49:38 +0000996 auto DiagFileOrErr = lto::setupOptimizationRemarks(
997 Context, LTORemarksFilename, LTOPassRemarksWithHotness, count);
Mehdi Amini19f176b2016-11-19 18:20:05 +0000998 if (!DiagFileOrErr) {
999 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
1000 report_fatal_error("ThinLTO: Can't get an output file for the "
1001 "remarks");
1002 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001003
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001004 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +00001005 auto TheModule =
1006 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
1007 /*IsImporting*/ false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001008
1009 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +00001010 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001011
Mehdi Amini1aafabf2016-04-16 07:02:16 +00001012 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +00001013 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001014 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +00001015 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +00001016 ExportList, GUIDPreservedSymbols,
1017 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Aminib5a46c12017-03-28 18:55:44 +00001018 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001019
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001020 // Commit to the cache (if enabled)
1021 CacheEntry.write(*OutputBuffer);
1022
1023 if (SavedObjectsDirectoryPath.empty()) {
1024 // We need to generated a memory buffer for the linker.
1025 if (!CacheEntryPath.empty()) {
1026 // Cache is enabled, reload from the cache
1027 // We do this to lower memory pressuree: the buffer is on the heap
1028 // and releasing it frees memory that can be used for the next input
1029 // file. The final binary link will read from the VFS cache
1030 // (hopefully!) or from disk if the memory pressure wasn't too high.
1031 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1032 if (auto EC = ReloadedBufferOrErr.getError()) {
1033 // On error, keeping the preexisting buffer and printing a
1034 // diagnostic is more friendly than just crashing.
1035 errs() << "error: can't reload cached file '" << CacheEntryPath
1036 << "': " << EC.message() << "\n";
1037 } else {
1038 OutputBuffer = std::move(*ReloadedBufferOrErr);
1039 }
1040 }
1041 ProducedBinaries[count] = std::move(OutputBuffer);
1042 return;
1043 }
1044 ProducedBinaryFiles[count] = writeGeneratedObject(
1045 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001046 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001047 }
1048 }
1049
Peter Collingbournecead56f2017-03-15 22:54:18 +00001050 pruneCache(CacheOptions.Path, CacheOptions.Policy);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001051
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001052 // If statistics were requested, print them out now.
1053 if (llvm::AreStatisticsEnabled())
1054 llvm::PrintStatistics();
James Henderson852f6fd2017-05-16 09:43:21 +00001055 reportAndResetTimings();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001056}