blob: 8c65a868580b73eae7eb228e49b42fb2020b8d74 [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"
Nico Weber432a3882018-04-30 14:59:11 +000026#include "llvm/Config/llvm-config.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"
Weiming Zhao79f2d092018-04-16 03:44:03 +000042#include "llvm/Support/SmallVectorMemoryBuffer.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;
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000067}
68
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000069namespace {
70
Teresa Johnsonec544c52016-10-19 17:35:01 +000071static cl::opt<int>
72 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000073
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000074// Simple helper to save temporary files for debug.
75static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
76 unsigned count, StringRef Suffix) {
77 if (TempDir.empty())
78 return;
79 // User asked to save temps, let dump the bitcode file after import.
Benjamin Kramer3a13ed62017-12-28 16:58:54 +000080 std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000081 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000082 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000083 if (EC)
84 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
85 " to save optimized bitcode\n");
Rafael Espindola6a86e252018-02-14 19:11:32 +000086 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000087}
88
Teresa Johnson4d2613f2016-05-24 17:24:25 +000089static const GlobalValueSummary *
90getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
91 // If there is any strong definition anywhere, get it.
92 auto StrongDefForLinker = llvm::find_if(
93 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
94 auto Linkage = Summary->linkage();
95 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
96 !GlobalValue::isWeakForLinker(Linkage);
97 });
98 if (StrongDefForLinker != GVSummaryList.end())
99 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000100 // Get the first *linker visible* definition for this global in the summary
101 // list.
102 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000103 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
104 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000105 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
106 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000107 // Extern templates can be emitted as available_externally.
108 if (FirstDefForLinker == GVSummaryList.end())
109 return nullptr;
110 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000111}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000112
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000113// Populate map of GUID to the prevailing copy for any multiply defined
114// symbols. Currently assume first copy is prevailing, or any strong
115// definition. Can be refined with Linker information in the future.
116static void computePrevailingCopies(
117 const ModuleSummaryIndex &Index,
118 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000119 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
120 return GVSummaryList.size() > 1;
121 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000122
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000123 for (auto &I : Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000124 if (HasMultipleCopies(I.second.SummaryList))
125 PrevailingCopy[I.first] =
126 getFirstDefinitionForLinker(I.second.SummaryList);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000127 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000128}
129
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000130static StringMap<MemoryBufferRef>
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000131generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000132 StringMap<MemoryBufferRef> ModuleMap;
133 for (auto &ModuleBuffer : Modules) {
134 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
135 ModuleMap.end() &&
136 "Expect unique Buffer Identifier");
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000137 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000138 }
139 return ModuleMap;
140}
141
Teresa Johnson26ab5772016-03-15 00:04:37 +0000142static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000143 if (renameModuleForThinLTO(TheModule, Index))
144 report_fatal_error("renameModuleForThinLTO failed");
145}
146
Adrian Prantl981a7992017-05-20 00:00:08 +0000147namespace {
148class ThinLTODiagnosticInfo : public DiagnosticInfo {
149 const Twine &Msg;
150public:
151 ThinLTODiagnosticInfo(const Twine &DiagMsg,
152 DiagnosticSeverity Severity = DS_Error)
153 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
154 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
155};
156}
157
158/// Verify the module and strip broken debug info.
159static void verifyLoadedModule(Module &TheModule) {
160 bool BrokenDebugInfo = false;
Adrian Prantla8b2ddb2017-10-02 18:31:29 +0000161 if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
Adrian Prantl981a7992017-05-20 00:00:08 +0000162 report_fatal_error("Broken module found, compilation aborted!");
163 if (BrokenDebugInfo) {
164 TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
165 "Invalid debug info found, debug info will be stripped", DS_Warning));
166 StripDebugInfo(TheModule);
167 }
168}
169
Peter Collingbournedac43b42016-12-01 05:52:32 +0000170static std::unique_ptr<Module>
171loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000172 bool Lazy, bool IsImporting) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000173 SMDiagnostic Err;
174 Expected<std::unique_ptr<Module>> ModuleOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000175 Lazy
176 ? getLazyBitcodeModule(Buffer, Context,
177 /* ShouldLazyLoadMetadata */ true, IsImporting)
178 : parseBitcodeFile(Buffer, Context);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000179 if (!ModuleOrErr) {
180 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
181 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
182 SourceMgr::DK_Error, EIB.message());
183 Err.print("ThinLTO", errs());
184 });
185 report_fatal_error("Can't load module, abort.");
186 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000187 if (!Lazy)
188 verifyLoadedModule(*ModuleOrErr.get());
Peter Collingbournedac43b42016-12-01 05:52:32 +0000189 return std::move(ModuleOrErr.get());
190}
191
Mehdi Amini01e32132016-03-26 05:40:34 +0000192static void
193crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
194 StringMap<MemoryBufferRef> &ModuleMap,
195 const FunctionImporter::ImportMapTy &ImportList) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000196 auto Loader = [&](StringRef Identifier) {
197 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000198 /*Lazy=*/true, /*IsImporting*/ true);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000199 };
200
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000201 FunctionImporter Importer(Index, Loader);
Adrian Prantl66043792017-05-19 23:32:21 +0000202 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
Mehdi Amini83a807e2017-01-08 00:30:27 +0000203 if (!Result) {
204 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
205 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
206 SourceMgr::DK_Error, EIB.message());
207 Err.print("ThinLTO", errs());
208 });
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000209 report_fatal_error("importFunctions failed");
Mehdi Amini83a807e2017-01-08 00:30:27 +0000210 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000211 // Verify again after cross-importing.
212 verifyLoadedModule(TheModule);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000213}
214
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000215static void optimizeModule(Module &TheModule, TargetMachine &TM,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000216 unsigned OptLevel, bool Freestanding) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000217 // Populate the PassManager
218 PassManagerBuilder PMB;
219 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000220 if (Freestanding)
221 PMB.LibraryInfo->disableAllFunctions();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000222 PMB.Inliner = createFunctionInliningPass();
223 // FIXME: should get it from the bitcode?
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000224 PMB.OptLevel = OptLevel;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000225 PMB.LoopVectorize = true;
226 PMB.SLPVectorize = true;
Adrian Prantl981a7992017-05-20 00:00:08 +0000227 // Already did this in verifyLoadedModule().
228 PMB.VerifyInput = false;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000229 PMB.VerifyOutput = false;
230
231 legacy::PassManager PM;
232
233 // Add the TTI (required to inform the vectorizer about register size for
234 // instance)
235 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
236
237 // Add optimizations
238 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000239
240 PM.run(TheModule);
241}
242
Mehdi Amini059464f2016-04-24 03:18:01 +0000243// Convert the PreservedSymbols map from "Name" based to "GUID" based.
244static DenseSet<GlobalValue::GUID>
Mehdi Amini1380edf2017-02-03 07:41:43 +0000245computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
246 const Triple &TheTriple) {
247 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
248 for (auto &Entry : PreservedSymbols) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000249 StringRef Name = Entry.first();
250 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
251 Name = Name.drop_front();
Mehdi Amini1380edf2017-02-03 07:41:43 +0000252 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
Mehdi Amini059464f2016-04-24 03:18:01 +0000253 }
Mehdi Amini1380edf2017-02-03 07:41:43 +0000254 return GUIDPreservedSymbols;
Mehdi Amini059464f2016-04-24 03:18:01 +0000255}
256
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000257std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
258 TargetMachine &TM) {
259 SmallVector<char, 128> OutputBuffer;
260
261 // CodeGen
262 {
263 raw_svector_ostream OS(OutputBuffer);
264 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000265
266 // If the bitcode files contain ARC code and were compiled with optimization,
267 // the ObjCARCContractPass must be run, so do it unconditionally here.
268 PM.add(createObjCARCContractPass());
269
270 // Setup the codegen now.
Peter Collingbourne9a451142018-05-21 20:16:41 +0000271 if (TM.addPassesToEmitFile(PM, OS, nullptr, TargetMachine::CGFT_ObjectFile,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000272 /* DisableVerify */ true))
273 report_fatal_error("Failed to setup codegen");
274
275 // Run codegen now. resulting binary is in OutputBuffer.
276 PM.run(TheModule);
277 }
Weiming Zhao79f2d092018-04-16 03:44:03 +0000278 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000279}
280
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000281/// Manage caching for a single Module.
282class ModuleCacheEntry {
283 SmallString<128> EntryPath;
284
285public:
286 // Create a cache entry. This compute a unique hash for the Module considering
287 // the current list of export/import, and offer an interface to query to
288 // access the content in the cache.
289 ModuleCacheEntry(
290 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
291 const FunctionImporter::ImportMapTy &ImportList,
292 const FunctionImporter::ExportSetTy &ExportList,
293 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000294 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminic92b6122017-01-10 00:55:47 +0000295 const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000296 bool Freestanding, const TargetMachineBuilder &TMBuilder) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000297 if (CachePath.empty())
298 return;
299
Mehdi Amini00fa1402016-10-08 04:44:18 +0000300 if (!Index.modulePaths().count(ModuleID))
301 // The module does not have an entry, it can't have a hash at all
302 return;
303
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000304 // Compute the unique hash for this entry
305 // This is based on the current compiler version, the module itself, the
306 // export list, the hash for every single module in the import list, the
307 // list of ResolvedODR for the module, and the list of preserved symbols.
308
Mehdi Aminif82bda02016-10-08 04:44:23 +0000309 // Include the hash for the current module
310 auto ModHash = Index.getModuleHash(ModuleID);
311
312 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
313 // No hash entry, no caching!
314 return;
315
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000316 SHA1 Hasher;
317
Mehdi Aminic92b6122017-01-10 00:55:47 +0000318 // Include the parts of the LTO configuration that affect code generation.
319 auto AddString = [&](StringRef Str) {
320 Hasher.update(Str);
321 Hasher.update(ArrayRef<uint8_t>{0});
322 };
323 auto AddUnsigned = [&](unsigned I) {
324 uint8_t Data[4];
325 Data[0] = I;
326 Data[1] = I >> 8;
327 Data[2] = I >> 16;
328 Data[3] = I >> 24;
329 Hasher.update(ArrayRef<uint8_t>{Data, 4});
330 };
331
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000332 // Start with the compiler revision
333 Hasher.update(LLVM_VERSION_STRING);
Peter Collingbourne942fa562017-04-13 01:26:12 +0000334#ifdef LLVM_REVISION
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000335 Hasher.update(LLVM_REVISION);
336#endif
337
Mehdi Aminic92b6122017-01-10 00:55:47 +0000338 // Hash the optimization level and the target machine settings.
339 AddString(TMBuilder.MCpu);
340 // FIXME: Hash more of Options. For now all clients initialize Options from
341 // command-line flags (which is unsupported in production), but may set
342 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
343 // DataSections and DebuggerTuning via command line flags.
344 AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
345 AddUnsigned(TMBuilder.Options.FunctionSections);
346 AddUnsigned(TMBuilder.Options.DataSections);
347 AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
348 AddString(TMBuilder.MAttr);
349 if (TMBuilder.RelocModel)
350 AddUnsigned(*TMBuilder.RelocModel);
351 AddUnsigned(TMBuilder.CGOptLevel);
352 AddUnsigned(OptLevel);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000353 AddUnsigned(Freestanding);
Mehdi Aminic92b6122017-01-10 00:55:47 +0000354
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000355 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
356 for (auto F : ExportList)
357 // The export list can impact the internalization, be conservative here
358 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
359
360 // Include the hash for every module we import functions from
361 for (auto &Entry : ImportList) {
362 auto ModHash = Index.getModuleHash(Entry.first());
363 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
364 }
365
366 // Include the hash for the resolved ODR.
367 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000368 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000369 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000370 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000371 sizeof(GlobalValue::LinkageTypes)));
372 }
373
374 // Include the hash for the preserved symbols.
375 for (auto &Entry : PreservedSymbols) {
376 if (DefinedFunctions.count(Entry))
377 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000378 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000379 }
380
Peter Collingbourne25a17ba2017-03-20 16:41:57 +0000381 // This choice of file name allows the cache to be pruned (see pruneCache()
382 // in include/llvm/Support/CachePruning.h).
383 sys::path::append(EntryPath, CachePath,
384 "llvmcache-" + toHex(Hasher.result()));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000385 }
386
Mehdi Amini059464f2016-04-24 03:18:01 +0000387 // Access the path to this entry in the cache.
388 StringRef getEntryPath() { return EntryPath; }
389
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000390 // Try loading the buffer for this cache entry.
391 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
392 if (EntryPath.empty())
393 return std::error_code();
394 return MemoryBuffer::getFile(EntryPath);
395 }
396
397 // Cache the Produced object file
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000398 void write(const MemoryBuffer &OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000399 if (EntryPath.empty())
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000400 return;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000401
402 // Write to a temporary to avoid race condition
403 SmallString<128> TempFilename;
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000404 SmallString<128> CachePath(EntryPath);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000405 int TempFD;
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000406 llvm::sys::path::remove_filename(CachePath);
407 sys::path::append(TempFilename, CachePath, "Thin-%%%%%%.tmp.o");
408 std::error_code EC =
409 sys::fs::createUniqueFile(TempFilename, TempFD, TempFilename);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000410 if (EC) {
411 errs() << "Error: " << EC.message() << "\n";
412 report_fatal_error("ThinLTO: Can't get a temporary file");
413 }
414 {
415 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000416 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000417 }
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000418 // Rename temp file to final destination; rename is atomic
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000419 EC = sys::fs::rename(TempFilename, EntryPath);
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000420 if (EC)
Mehdi Aminib02139d2016-05-14 05:16:35 +0000421 sys::fs::remove(TempFilename);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000422 }
423};
424
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000425static std::unique_ptr<MemoryBuffer>
426ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
427 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
428 const FunctionImporter::ImportMapTy &ImportList,
429 const FunctionImporter::ExportSetTy &ExportList,
430 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
431 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000432 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000433 bool DisableCodeGen, StringRef SaveTempsDir,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000434 bool Freestanding, unsigned OptLevel, unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000435
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000436 // "Benchmark"-like optimization: single-source case
437 bool SingleModule = (ModuleMap.size() == 1);
438
439 if (!SingleModule) {
440 promoteModule(TheModule, Index);
441
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000442 // Apply summary-based LinkOnce/Weak resolution decisions.
443 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000444
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000445 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000446 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000447 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000448
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000449 // Be friendly and don't nuke totally the module when the client didn't
450 // supply anything to preserve.
451 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
452 // Apply summary-based internalization decisions.
453 thinLTOInternalizeModule(TheModule, DefinedGlobals);
454 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000455
456 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000457 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000458
459 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000460 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000461
462 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000463 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000464 }
465
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000466 optimizeModule(TheModule, TM, OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000467
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000468 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000469
Mehdi Amini43b657b2016-04-01 06:47:02 +0000470 if (DisableCodeGen) {
471 // Configured to stop before CodeGen, serialize the bitcode and return.
472 SmallVector<char, 128> OutputBuffer;
473 {
474 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000475 ProfileSummaryInfo PSI(TheModule);
Teresa Johnson94624ac2017-05-10 18:52:16 +0000476 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000477 WriteBitcodeToFile(TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000478 }
Weiming Zhao79f2d092018-04-16 03:44:03 +0000479 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
Mehdi Amini43b657b2016-04-01 06:47:02 +0000480 }
481
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000482 return codegenModule(TheModule, TM);
483}
484
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000485/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
486/// for caching, and in the \p Index for application during the ThinLTO
487/// backends. This is needed for correctness for exported symbols (ensure
488/// at least one copy kept) and a compile-time optimization (to drop duplicate
489/// copies when possible).
490static void resolveWeakForLinkerInIndex(
491 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000492 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
493 &ResolvedODR) {
494
495 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
496 computePrevailingCopies(Index, PrevailingCopy);
497
498 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
499 const auto &Prevailing = PrevailingCopy.find(GUID);
500 // Not in map means that there was only one copy, which must be prevailing.
501 if (Prevailing == PrevailingCopy.end())
502 return true;
503 return Prevailing->second == S;
504 };
505
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000506 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
507 GlobalValue::GUID GUID,
508 GlobalValue::LinkageTypes NewLinkage) {
509 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
510 };
511
Peter Collingbourne73589f32016-07-07 18:31:51 +0000512 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000513}
514
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000515// Initialize the TargetMachine builder for a given Triple
516static void initTMBuilder(TargetMachineBuilder &TMBuilder,
517 const Triple &TheTriple) {
518 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
519 // FIXME this looks pretty terrible...
520 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
521 if (TheTriple.getArch() == llvm::Triple::x86_64)
522 TMBuilder.MCpu = "core2";
523 else if (TheTriple.getArch() == llvm::Triple::x86)
524 TMBuilder.MCpu = "yonah";
525 else if (TheTriple.getArch() == llvm::Triple::aarch64)
526 TMBuilder.MCpu = "cyclone";
527 }
528 TMBuilder.TheTriple = std::move(TheTriple);
529}
530
531} // end anonymous namespace
532
533void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
Johan Engelendcebe4f2017-09-17 18:11:26 +0000534 ThinLTOBuffer Buffer(Data, Identifier);
Akira Hatanakab10bff12017-05-18 03:52:29 +0000535 LLVMContext Context;
536 StringRef TripleStr;
537 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
538 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
539
540 if (TripleOrErr)
541 TripleStr = *TripleOrErr;
542
543 Triple TheTriple(TripleStr);
544
545 if (Modules.empty())
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000546 initTMBuilder(TMBuilder, Triple(TheTriple));
Akira Hatanakab10bff12017-05-18 03:52:29 +0000547 else if (TMBuilder.TheTriple != TheTriple) {
548 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
549 report_fatal_error("ThinLTO modules with incompatible triples not "
550 "supported");
551 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000552 }
Akira Hatanakab10bff12017-05-18 03:52:29 +0000553
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000554 Modules.push_back(Buffer);
555}
556
557void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
558 PreservedSymbols.insert(Name);
559}
560
561void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000562 // FIXME: At the moment, we don't take advantage of this extra information,
563 // we're conservatively considering cross-references as preserved.
564 // CrossReferencedSymbols.insert(Name);
565 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000566}
567
568// TargetMachine factory
569std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
570 std::string ErrMsg;
571 const Target *TheTarget =
572 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
573 if (!TheTarget) {
574 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
575 }
576
577 // Use MAttr as the default set of features.
578 SubtargetFeatures Features(MAttr);
579 Features.getDefaultSubtargetFeatures(TheTriple);
580 std::string FeatureStr = Features.getString();
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000581
Rafael Espindola79e238a2017-08-03 02:16:21 +0000582 return std::unique_ptr<TargetMachine>(
583 TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options,
584 RelocModel, None, CGOptLevel));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000585}
586
587/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000588 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000589 * "thin-link".
590 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000591std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000592 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
Teresa Johnson4ffc3e72018-06-06 22:22:01 +0000593 llvm::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000594 uint64_t NextModuleId = 0;
595 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000596 if (Error Err = readModuleSummaryIndex(ModuleBuffer.getMemBuffer(),
597 *CombinedIndex, NextModuleId++)) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000598 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000599 logAllUnhandledErrors(
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000600 std::move(Err), errs(),
Peter Collingbournec15d60b2017-05-01 20:42:32 +0000601 "error: can't create module summary index for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000602 return nullptr;
603 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000604 }
605 return CombinedIndex;
606}
607
George Rimar2421b6f2018-01-17 10:33:05 +0000608static void internalizeAndPromoteInIndex(
609 const StringMap<FunctionImporter::ExportSetTy> &ExportLists,
610 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
611 ModuleSummaryIndex &Index) {
612 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
613 const auto &ExportList = ExportLists.find(ModuleIdentifier);
614 return (ExportList != ExportLists.end() &&
615 ExportList->second.count(GUID)) ||
616 GUIDPreservedSymbols.count(GUID);
617 };
618
619 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
620}
621
George Rimareaf51722018-01-29 08:03:30 +0000622static void computeDeadSymbolsInIndex(
623 ModuleSummaryIndex &Index,
624 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
625 // We have no symbols resolution available. And can't do any better now in the
626 // case where the prevailing symbol is in a native object. It can be refined
627 // with linker information in the future.
628 auto isPrevailing = [&](GlobalValue::GUID G) {
629 return PrevailingType::Unknown;
630 };
631 computeDeadSymbols(Index, GUIDPreservedSymbols, isPrevailing);
632}
633
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000634/**
635 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000636 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000637 */
638void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000639 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000640 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000641 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000642
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000643 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000644 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000645 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000646
Teresa Johnson6c475a72017-01-05 21:34:18 +0000647 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000648 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000649 PreservedSymbols, Triple(TheModule.getTargetTriple()));
650
651 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000652 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000653
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000654 // Generate import/export list
655 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
656 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
657 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000658 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000659
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000660 // Resolve LinkOnce/Weak symbols.
661 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000662 resolveWeakForLinkerInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000663
664 thinLTOResolveWeakForLinkerModule(
665 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000666
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000667 // Promote the exported values in the index, so that they are promoted
668 // in the module.
George Rimar2421b6f2018-01-17 10:33:05 +0000669 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000670
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000671 promoteModule(TheModule, Index);
672}
673
674/**
675 * Perform cross-module importing for the module identified by ModuleIdentifier.
676 */
677void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000678 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000679 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000680 auto ModuleCount = Index.modulePaths().size();
681
682 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000683 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000684 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000685
Teresa Johnson6c475a72017-01-05 21:34:18 +0000686 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000687 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000688 PreservedSymbols, Triple(TheModule.getTargetTriple()));
689
690 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000691 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000692
Mehdi Amini01e32132016-03-26 05:40:34 +0000693 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000694 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
695 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000696 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000697 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000698 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
699
700 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000701}
702
703/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000704 * Compute the list of summaries needed for importing into module.
705 */
706void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
707 StringRef ModulePath, ModuleSummaryIndex &Index,
708 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
709 auto ModuleCount = Index.modulePaths().size();
710
711 // Collect for each module the list of function it defines (GUID -> Summary).
712 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
713 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
714
715 // Generate import/export list
716 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
717 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
718 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
719 ExportLists);
720
721 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000722 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000723 ModuleToSummariesForIndex);
724}
725
726/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000727 * Emit the list of files needed for importing into module.
728 */
729void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
730 StringRef OutputName,
731 ModuleSummaryIndex &Index) {
732 auto ModuleCount = Index.modulePaths().size();
733
734 // Collect for each module the list of function it defines (GUID -> Summary).
735 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
736 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
737
738 // Generate import/export list
739 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
740 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
741 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
742 ExportLists);
743
744 std::error_code EC;
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000745 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000746 report_fatal_error(Twine("Failed to open ") + OutputName +
747 " to save imports lists\n");
748}
749
750/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000751 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000752 */
753void ThinLTOCodeGenerator::internalize(Module &TheModule,
754 ModuleSummaryIndex &Index) {
755 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
756 auto ModuleCount = Index.modulePaths().size();
757 auto ModuleIdentifier = TheModule.getModuleIdentifier();
758
759 // Convert the preserved symbols set from string to GUID
760 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000761 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Amini059464f2016-04-24 03:18:01 +0000762
763 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000764 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000765 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
766
Teresa Johnson6c475a72017-01-05 21:34:18 +0000767 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000768 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000769
Mehdi Amini059464f2016-04-24 03:18:01 +0000770 // Generate import/export list
771 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
772 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
773 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000774 ExportLists);
Mehdi Amini059464f2016-04-24 03:18:01 +0000775 auto &ExportList = ExportLists[ModuleIdentifier];
776
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000777 // Be friendly and don't nuke totally the module when the client didn't
778 // supply anything to preserve.
779 if (ExportList.empty() && GUIDPreservedSymbols.empty())
780 return;
781
Mehdi Amini059464f2016-04-24 03:18:01 +0000782 // Internalization
George Rimar2421b6f2018-01-17 10:33:05 +0000783 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000784 thinLTOInternalizeModule(TheModule,
785 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000786}
787
788/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000789 * Perform post-importing ThinLTO optimizations.
790 */
791void ThinLTOCodeGenerator::optimize(Module &TheModule) {
792 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000793
794 // Optimize now
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000795 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000796}
797
798/**
799 * Perform ThinLTO CodeGen.
800 */
801std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
802 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
803 return codegenModule(TheModule, *TMBuilder.create());
804}
805
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000806/// Write out the generated object file, either from CacheEntryPath or from
807/// OutputBuffer, preferring hard-link when possible.
808/// Returns the path to the generated file in SavedObjectsDirectoryPath.
809static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
810 StringRef SavedObjectsDirectoryPath,
811 const MemoryBuffer &OutputBuffer) {
812 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
813 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
814 OutputPath.c_str(); // Ensure the string is null terminated.
815 if (sys::fs::exists(OutputPath))
816 sys::fs::remove(OutputPath);
817
818 // We don't return a memory buffer to the linker, just a list of files.
819 if (!CacheEntryPath.empty()) {
820 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
821 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
822 if (!Err)
823 return OutputPath.str();
824 // Hard linking failed, try to copy.
825 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
826 if (!Err)
827 return OutputPath.str();
828 // Copy failed (could be because the CacheEntry was removed from the cache
829 // in the meantime by another process), fall back and try to write down the
830 // buffer to the output.
831 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
832 << "' to '" << OutputPath << "'\n";
833 }
834 // No cache entry, just write out the buffer.
835 std::error_code Err;
836 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
837 if (Err)
838 report_fatal_error("Can't open output '" + OutputPath + "'\n");
839 OS << OutputBuffer.getBuffer();
840 return OutputPath.str();
841}
842
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000843// Main entry point for the ThinLTO processing
844void ThinLTOCodeGenerator::run() {
Mehdi Aminib2990462017-01-20 22:45:34 +0000845 // Prepare the resulting object vector
846 assert(ProducedBinaries.empty() && "The generator should not be reused");
847 if (SavedObjectsDirectoryPath.empty())
848 ProducedBinaries.resize(Modules.size());
849 else {
850 sys::fs::create_directories(SavedObjectsDirectoryPath);
851 bool IsDir;
852 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
853 if (!IsDir)
854 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
855 ProducedBinaryFiles.resize(Modules.size());
856 }
857
Mehdi Amini43b657b2016-04-01 06:47:02 +0000858 if (CodeGenOnly) {
859 // Perform only parallel codegen and return.
860 ThreadPool Pool;
Mehdi Amini43b657b2016-04-01 06:47:02 +0000861 int count = 0;
862 for (auto &ModuleBuffer : Modules) {
863 Pool.async([&](int count) {
864 LLVMContext Context;
865 Context.setDiscardValueNames(LTODiscardValueNames);
866
867 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000868 auto TheModule =
869 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
870 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000871
872 // CodeGen
Mehdi Aminib2990462017-01-20 22:45:34 +0000873 auto OutputBuffer = codegen(*TheModule);
874 if (SavedObjectsDirectoryPath.empty())
875 ProducedBinaries[count] = std::move(OutputBuffer);
876 else
877 ProducedBinaryFiles[count] = writeGeneratedObject(
878 count, "", SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000879 }, count++);
880 }
881
882 return;
883 }
884
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000885 // Sequential linking phase
886 auto Index = linkCombinedIndex();
887
888 // Save temps: index.
889 if (!SaveTempsDir.empty()) {
890 auto SaveTempPath = SaveTempsDir + "index.bc";
891 std::error_code EC;
892 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
893 if (EC)
894 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
895 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000896 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000897 }
898
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000899
900 // Prepare the module map.
901 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000902 auto ModuleCount = Modules.size();
903
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000904 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000905 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000906 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
907
Teresa Johnson6c475a72017-01-05 21:34:18 +0000908 // Convert the preserved symbols set from string to GUID, this is needed for
909 // computing the caching hash and the internalization.
910 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000911 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000912
913 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000914 computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000915
Mehdi Amini01e32132016-03-26 05:40:34 +0000916 // Collect the import/export lists for all modules from the call-graph in the
917 // combined index.
918 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
919 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000920 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000921 ExportLists);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000922
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000923 // We use a std::map here to be able to have a defined ordering when
924 // producing a hash for the cache entry.
925 // FIXME: we should be able to compute the caching hash for the entry based
926 // on the index, and nuke this map.
927 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
928
929 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
930 // impacts the caching.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000931 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000932
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000933 // Use global summary-based analysis to identify symbols that can be
934 // internalized (because they aren't exported or preserved as per callback).
935 // Changes are made in the index, consumed in the ThinLTO backends.
George Rimar2421b6f2018-01-17 10:33:05 +0000936 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, *Index);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000937
Teresa Johnson141149f2016-05-24 18:44:01 +0000938 // Make sure that every module has an entry in the ExportLists and
939 // ResolvedODR maps to enable threaded access to these maps below.
940 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000941 ExportLists[DefinedGVSummaries.first()];
Teresa Johnson141149f2016-05-24 18:44:01 +0000942 ResolvedODR[DefinedGVSummaries.first()];
943 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000944
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000945 // Compute the ordering we will process the inputs: the rough heuristic here
946 // is to sort them per size so that the largest module get schedule as soon as
947 // possible. This is purely a compile-time optimization.
948 std::vector<int> ModulesOrdering;
949 ModulesOrdering.resize(Modules.size());
950 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
Mandeep Singh Grang5416af72018-04-13 19:12:20 +0000951 llvm::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
952 [&](int LeftIndex, int RightIndex) {
953 auto LSize = Modules[LeftIndex].getBuffer().size();
954 auto RSize = Modules[RightIndex].getBuffer().size();
955 return LSize > RSize;
956 });
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000957
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000958 // Parallel optimizer + codegen
959 {
960 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000961 for (auto IndexCount : ModulesOrdering) {
962 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000963 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000964 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000965 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000966
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000967 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
968
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000969 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000970 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
971 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000972 ResolvedODR[ModuleIdentifier],
Mehdi Aminic92b6122017-01-10 00:55:47 +0000973 DefinedFunctions, GUIDPreservedSymbols,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000974 OptLevel, Freestanding, TMBuilder);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000975 auto CacheEntryPath = CacheEntry.getEntryPath();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000976
977 {
978 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000979 LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss")
980 << " '" << CacheEntryPath << "' for buffer "
981 << count << " " << ModuleIdentifier << "\n");
Mehdi Amini059464f2016-04-24 03:18:01 +0000982
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000983 if (ErrOrBuffer) {
984 // Cache Hit!
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000985 if (SavedObjectsDirectoryPath.empty())
986 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
987 else
988 ProducedBinaryFiles[count] = writeGeneratedObject(
989 count, CacheEntryPath, SavedObjectsDirectoryPath,
990 *ErrOrBuffer.get());
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000991 return;
992 }
993 }
994
995 LLVMContext Context;
996 Context.setDiscardValueNames(LTODiscardValueNames);
997 Context.enableDebugTypeODRUniquing();
Davide Italiano690ed9d2017-02-10 23:49:38 +0000998 auto DiagFileOrErr = lto::setupOptimizationRemarks(
Bob Haarmanfb2d3422018-03-08 01:13:10 +0000999 Context, LTORemarksFilename, LTOPassRemarksWithHotness, count);
Mehdi Amini19f176b2016-11-19 18:20:05 +00001000 if (!DiagFileOrErr) {
1001 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
1002 report_fatal_error("ThinLTO: Can't get an output file for the "
1003 "remarks");
1004 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001005
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001006 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +00001007 auto TheModule =
1008 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
1009 /*IsImporting*/ false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001010
1011 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +00001012 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001013
Mehdi Amini1aafabf2016-04-16 07:02:16 +00001014 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +00001015 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001016 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +00001017 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +00001018 ExportList, GUIDPreservedSymbols,
1019 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Aminib5a46c12017-03-28 18:55:44 +00001020 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001021
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001022 // Commit to the cache (if enabled)
1023 CacheEntry.write(*OutputBuffer);
1024
1025 if (SavedObjectsDirectoryPath.empty()) {
1026 // We need to generated a memory buffer for the linker.
1027 if (!CacheEntryPath.empty()) {
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +00001028 // When cache is enabled, reload from the cache if possible.
1029 // Releasing the buffer from the heap and reloading it from the
1030 // cache file with mmap helps us to lower memory pressure.
1031 // The freed memory can be used for the next input file.
1032 // The final binary link will read from the VFS cache (hopefully!)
1033 // or from disk (if the memory pressure was too high).
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001034 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1035 if (auto EC = ReloadedBufferOrErr.getError()) {
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +00001036 // On error, keep the preexisting buffer and print a diagnostic.
Mehdi Amini8e13bc42016-12-14 04:56:42 +00001037 errs() << "error: can't reload cached file '" << CacheEntryPath
1038 << "': " << EC.message() << "\n";
1039 } else {
1040 OutputBuffer = std::move(*ReloadedBufferOrErr);
1041 }
1042 }
1043 ProducedBinaries[count] = std::move(OutputBuffer);
1044 return;
1045 }
1046 ProducedBinaryFiles[count] = writeGeneratedObject(
1047 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001048 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001049 }
1050 }
1051
Peter Collingbournecead56f2017-03-15 22:54:18 +00001052 pruneCache(CacheOptions.Path, CacheOptions.Policy);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001053
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001054 // If statistics were requested, print them out now.
1055 if (llvm::AreStatisticsEnabled())
1056 llvm::PrintStatistics();
James Henderson852f6fd2017-05-16 09:43:21 +00001057 reportAndResetTimings();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001058}