blob: e9633b015c181cddd5b476429892fd317b7e0cde [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"
Fedor Sergeeva43fd952018-09-26 13:01:43 +000032#include "llvm/IR/PassTimingInfo.h"
Adrian Prantl981a7992017-05-20 00:00:08 +000033#include "llvm/IR/Verifier.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000034#include "llvm/IRReader/IRReader.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000035#include "llvm/LTO/LTO.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000036#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"
Weiming Zhao79f2d092018-04-16 03:44:03 +000043#include "llvm/Support/SmallVectorMemoryBuffer.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000044#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000046#include "llvm/Support/Threading.h"
Mehdi Amini19f176b2016-11-19 18:20:05 +000047#include "llvm/Support/ToolOutputFile.h"
Peter Collingbourne942fa562017-04-13 01:26:12 +000048#include "llvm/Support/VCSRevision.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000049#include "llvm/Target/TargetMachine.h"
50#include "llvm/Transforms/IPO.h"
51#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000052#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000053#include "llvm/Transforms/IPO/PassManagerBuilder.h"
54#include "llvm/Transforms/ObjCARC.h"
55#include "llvm/Transforms/Utils/FunctionImportUtils.h"
56
Mehdi Amini819e9cd2016-05-16 19:33:07 +000057#include <numeric>
58
Andrew Ng089303d2018-07-04 14:17:10 +000059#if !defined(_MSC_VER) && !defined(__MINGW32__)
60#include <unistd.h>
61#else
62#include <io.h>
63#endif
64
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000065using namespace llvm;
66
Mehdi Amini1aafabf2016-04-16 07:02:16 +000067#define DEBUG_TYPE "thinlto"
68
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000069namespace llvm {
70// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
71extern cl::opt<bool> LTODiscardValueNames;
Mehdi Amini19f176b2016-11-19 18:20:05 +000072extern cl::opt<std::string> LTORemarksFilename;
Adam Nemet4c207a62016-12-02 17:53:56 +000073extern cl::opt<bool> LTOPassRemarksWithHotness;
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000074}
75
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000076namespace {
77
Teresa Johnsonec544c52016-10-19 17:35:01 +000078static cl::opt<int>
79 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000080
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000081// Simple helper to save temporary files for debug.
82static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
83 unsigned count, StringRef Suffix) {
84 if (TempDir.empty())
85 return;
86 // User asked to save temps, let dump the bitcode file after import.
Benjamin Kramer3a13ed62017-12-28 16:58:54 +000087 std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000088 std::error_code EC;
Teresa Johnsonc44a1222016-08-15 23:24:57 +000089 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000090 if (EC)
91 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
92 " to save optimized bitcode\n");
Rafael Espindola6a86e252018-02-14 19:11:32 +000093 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000094}
95
Teresa Johnson4d2613f2016-05-24 17:24:25 +000096static const GlobalValueSummary *
97getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
98 // If there is any strong definition anywhere, get it.
99 auto StrongDefForLinker = llvm::find_if(
100 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
101 auto Linkage = Summary->linkage();
102 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
103 !GlobalValue::isWeakForLinker(Linkage);
104 });
105 if (StrongDefForLinker != GVSummaryList.end())
106 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000107 // Get the first *linker visible* definition for this global in the summary
108 // list.
109 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000110 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
111 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000112 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
113 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000114 // Extern templates can be emitted as available_externally.
115 if (FirstDefForLinker == GVSummaryList.end())
116 return nullptr;
117 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000118}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000119
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000120// Populate map of GUID to the prevailing copy for any multiply defined
121// symbols. Currently assume first copy is prevailing, or any strong
122// definition. Can be refined with Linker information in the future.
123static void computePrevailingCopies(
124 const ModuleSummaryIndex &Index,
125 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000126 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
127 return GVSummaryList.size() > 1;
128 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000129
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000130 for (auto &I : Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000131 if (HasMultipleCopies(I.second.SummaryList))
132 PrevailingCopy[I.first] =
133 getFirstDefinitionForLinker(I.second.SummaryList);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000134 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000135}
136
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000137static StringMap<MemoryBufferRef>
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000138generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000139 StringMap<MemoryBufferRef> ModuleMap;
140 for (auto &ModuleBuffer : Modules) {
141 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
142 ModuleMap.end() &&
143 "Expect unique Buffer Identifier");
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000144 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000145 }
146 return ModuleMap;
147}
148
Teresa Johnson26ab5772016-03-15 00:04:37 +0000149static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000150 if (renameModuleForThinLTO(TheModule, Index))
151 report_fatal_error("renameModuleForThinLTO failed");
152}
153
Adrian Prantl981a7992017-05-20 00:00:08 +0000154namespace {
155class ThinLTODiagnosticInfo : public DiagnosticInfo {
156 const Twine &Msg;
157public:
158 ThinLTODiagnosticInfo(const Twine &DiagMsg,
159 DiagnosticSeverity Severity = DS_Error)
160 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
161 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
162};
163}
164
165/// Verify the module and strip broken debug info.
166static void verifyLoadedModule(Module &TheModule) {
167 bool BrokenDebugInfo = false;
Adrian Prantla8b2ddb2017-10-02 18:31:29 +0000168 if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
Adrian Prantl981a7992017-05-20 00:00:08 +0000169 report_fatal_error("Broken module found, compilation aborted!");
170 if (BrokenDebugInfo) {
171 TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
172 "Invalid debug info found, debug info will be stripped", DS_Warning));
173 StripDebugInfo(TheModule);
174 }
175}
176
Peter Collingbournedac43b42016-12-01 05:52:32 +0000177static std::unique_ptr<Module>
178loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000179 bool Lazy, bool IsImporting) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000180 SMDiagnostic Err;
181 Expected<std::unique_ptr<Module>> ModuleOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000182 Lazy
183 ? getLazyBitcodeModule(Buffer, Context,
184 /* ShouldLazyLoadMetadata */ true, IsImporting)
185 : parseBitcodeFile(Buffer, Context);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000186 if (!ModuleOrErr) {
187 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
188 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
189 SourceMgr::DK_Error, EIB.message());
190 Err.print("ThinLTO", errs());
191 });
192 report_fatal_error("Can't load module, abort.");
193 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000194 if (!Lazy)
195 verifyLoadedModule(*ModuleOrErr.get());
Peter Collingbournedac43b42016-12-01 05:52:32 +0000196 return std::move(ModuleOrErr.get());
197}
198
Mehdi Amini01e32132016-03-26 05:40:34 +0000199static void
200crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
201 StringMap<MemoryBufferRef> &ModuleMap,
202 const FunctionImporter::ImportMapTy &ImportList) {
Peter Collingbournedac43b42016-12-01 05:52:32 +0000203 auto Loader = [&](StringRef Identifier) {
204 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000205 /*Lazy=*/true, /*IsImporting*/ true);
Peter Collingbournedac43b42016-12-01 05:52:32 +0000206 };
207
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000208 FunctionImporter Importer(Index, Loader);
Adrian Prantl66043792017-05-19 23:32:21 +0000209 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
Mehdi Amini83a807e2017-01-08 00:30:27 +0000210 if (!Result) {
211 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
212 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
213 SourceMgr::DK_Error, EIB.message());
214 Err.print("ThinLTO", errs());
215 });
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000216 report_fatal_error("importFunctions failed");
Mehdi Amini83a807e2017-01-08 00:30:27 +0000217 }
Adrian Prantl981a7992017-05-20 00:00:08 +0000218 // Verify again after cross-importing.
219 verifyLoadedModule(TheModule);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000220}
221
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000222static void optimizeModule(Module &TheModule, TargetMachine &TM,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000223 unsigned OptLevel, bool Freestanding) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000224 // Populate the PassManager
225 PassManagerBuilder PMB;
226 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000227 if (Freestanding)
228 PMB.LibraryInfo->disableAllFunctions();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000229 PMB.Inliner = createFunctionInliningPass();
230 // FIXME: should get it from the bitcode?
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000231 PMB.OptLevel = OptLevel;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000232 PMB.LoopVectorize = true;
233 PMB.SLPVectorize = true;
Adrian Prantl981a7992017-05-20 00:00:08 +0000234 // Already did this in verifyLoadedModule().
235 PMB.VerifyInput = false;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000236 PMB.VerifyOutput = false;
237
238 legacy::PassManager PM;
239
240 // Add the TTI (required to inform the vectorizer about register size for
241 // instance)
242 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
243
244 // Add optimizations
245 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000246
247 PM.run(TheModule);
248}
249
Mehdi Amini059464f2016-04-24 03:18:01 +0000250// Convert the PreservedSymbols map from "Name" based to "GUID" based.
251static DenseSet<GlobalValue::GUID>
Mehdi Amini1380edf2017-02-03 07:41:43 +0000252computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
253 const Triple &TheTriple) {
254 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
255 for (auto &Entry : PreservedSymbols) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000256 StringRef Name = Entry.first();
257 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
258 Name = Name.drop_front();
Mehdi Amini1380edf2017-02-03 07:41:43 +0000259 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
Mehdi Amini059464f2016-04-24 03:18:01 +0000260 }
Mehdi Amini1380edf2017-02-03 07:41:43 +0000261 return GUIDPreservedSymbols;
Mehdi Amini059464f2016-04-24 03:18:01 +0000262}
263
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000264std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
265 TargetMachine &TM) {
266 SmallVector<char, 128> OutputBuffer;
267
268 // CodeGen
269 {
270 raw_svector_ostream OS(OutputBuffer);
271 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000272
273 // If the bitcode files contain ARC code and were compiled with optimization,
274 // the ObjCARCContractPass must be run, so do it unconditionally here.
275 PM.add(createObjCARCContractPass());
276
277 // Setup the codegen now.
Peter Collingbourne9a451142018-05-21 20:16:41 +0000278 if (TM.addPassesToEmitFile(PM, OS, nullptr, TargetMachine::CGFT_ObjectFile,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000279 /* DisableVerify */ true))
280 report_fatal_error("Failed to setup codegen");
281
282 // Run codegen now. resulting binary is in OutputBuffer.
283 PM.run(TheModule);
284 }
Weiming Zhao79f2d092018-04-16 03:44:03 +0000285 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000286}
287
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000288/// Manage caching for a single Module.
289class ModuleCacheEntry {
290 SmallString<128> EntryPath;
291
292public:
293 // Create a cache entry. This compute a unique hash for the Module considering
294 // the current list of export/import, and offer an interface to query to
295 // access the content in the cache.
296 ModuleCacheEntry(
297 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
298 const FunctionImporter::ImportMapTy &ImportList,
299 const FunctionImporter::ExportSetTy &ExportList,
300 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnson5f312ad2018-11-26 20:40:37 +0000301 const GVSummaryMapTy &DefinedGVSummaries, unsigned OptLevel,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000302 bool Freestanding, const TargetMachineBuilder &TMBuilder) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000303 if (CachePath.empty())
304 return;
305
Mehdi Amini00fa1402016-10-08 04:44:18 +0000306 if (!Index.modulePaths().count(ModuleID))
307 // The module does not have an entry, it can't have a hash at all
308 return;
309
Teresa Johnson5f312ad2018-11-26 20:40:37 +0000310 if (all_of(Index.getModuleHash(ModuleID),
311 [](uint32_t V) { return V == 0; }))
Mehdi Aminif82bda02016-10-08 04:44:23 +0000312 // No hash entry, no caching!
313 return;
314
Teresa Johnson5f312ad2018-11-26 20:40:37 +0000315 llvm::lto::Config Conf;
316 Conf.OptLevel = OptLevel;
317 Conf.Options = TMBuilder.Options;
318 Conf.CPU = TMBuilder.MCpu;
319 Conf.MAttrs.push_back(TMBuilder.MAttr);
320 Conf.RelocModel = TMBuilder.RelocModel;
321 Conf.CGOptLevel = TMBuilder.CGOptLevel;
322 Conf.Freestanding = Freestanding;
323 SmallString<40> Key;
324 computeLTOCacheKey(Key, Conf, Index, ModuleID, ImportList, ExportList,
325 ResolvedODR, DefinedGVSummaries);
Eugene Leviantbf46e742018-11-16 07:08:00 +0000326
Peter Collingbourne25a17ba2017-03-20 16:41:57 +0000327 // This choice of file name allows the cache to be pruned (see pruneCache()
328 // in include/llvm/Support/CachePruning.h).
Teresa Johnson5f312ad2018-11-26 20:40:37 +0000329 sys::path::append(EntryPath, CachePath, "llvmcache-" + Key);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000330 }
331
Mehdi Amini059464f2016-04-24 03:18:01 +0000332 // Access the path to this entry in the cache.
333 StringRef getEntryPath() { return EntryPath; }
334
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000335 // Try loading the buffer for this cache entry.
336 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
337 if (EntryPath.empty())
338 return std::error_code();
Andrew Ng089303d2018-07-04 14:17:10 +0000339 int FD;
340 SmallString<64> ResultPath;
341 std::error_code EC = sys::fs::openFileForRead(
342 Twine(EntryPath), FD, sys::fs::OF_UpdateAtime, &ResultPath);
343 if (EC)
344 return EC;
345 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
346 MemoryBuffer::getOpenFile(FD, EntryPath,
347 /*FileSize*/ -1,
348 /*RequiresNullTerminator*/ false);
349 close(FD);
350 return MBOrErr;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000351 }
352
353 // Cache the Produced object file
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000354 void write(const MemoryBuffer &OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000355 if (EntryPath.empty())
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000356 return;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000357
358 // Write to a temporary to avoid race condition
359 SmallString<128> TempFilename;
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000360 SmallString<128> CachePath(EntryPath);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000361 int TempFD;
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000362 llvm::sys::path::remove_filename(CachePath);
363 sys::path::append(TempFilename, CachePath, "Thin-%%%%%%.tmp.o");
Fangrui Songf78650a2018-07-30 19:41:25 +0000364 std::error_code EC =
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000365 sys::fs::createUniqueFile(TempFilename, TempFD, TempFilename);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000366 if (EC) {
367 errs() << "Error: " << EC.message() << "\n";
368 report_fatal_error("ThinLTO: Can't get a temporary file");
369 }
370 {
371 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000372 OS << OutputBuffer.getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000373 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000374 // Rename temp file to final destination; rename is atomic
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000375 EC = sys::fs::rename(TempFilename, EntryPath);
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000376 if (EC)
Mehdi Aminib02139d2016-05-14 05:16:35 +0000377 sys::fs::remove(TempFilename);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000378 }
379};
380
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000381static std::unique_ptr<MemoryBuffer>
382ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
383 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
384 const FunctionImporter::ImportMapTy &ImportList,
385 const FunctionImporter::ExportSetTy &ExportList,
386 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
387 const GVSummaryMapTy &DefinedGlobals,
Benjamin Kramerc321e532016-06-08 19:09:22 +0000388 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000389 bool DisableCodeGen, StringRef SaveTempsDir,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000390 bool Freestanding, unsigned OptLevel, unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000391
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000392 // "Benchmark"-like optimization: single-source case
393 bool SingleModule = (ModuleMap.size() == 1);
394
395 if (!SingleModule) {
396 promoteModule(TheModule, Index);
397
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000398 // Apply summary-based prevailing-symbol resolution decisions.
399 thinLTOResolvePrevailingInModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000400
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000401 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000402 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000403 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000404
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000405 // Be friendly and don't nuke totally the module when the client didn't
406 // supply anything to preserve.
407 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
408 // Apply summary-based internalization decisions.
409 thinLTOInternalizeModule(TheModule, DefinedGlobals);
410 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000411
412 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000413 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000414
415 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000416 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000417
418 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000419 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000420 }
421
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000422 optimizeModule(TheModule, TM, OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000423
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000424 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000425
Mehdi Amini43b657b2016-04-01 06:47:02 +0000426 if (DisableCodeGen) {
427 // Configured to stop before CodeGen, serialize the bitcode and return.
428 SmallVector<char, 128> OutputBuffer;
429 {
430 raw_svector_ostream OS(OutputBuffer);
Dehao Chen5461d8b2016-09-28 21:00:58 +0000431 ProfileSummaryInfo PSI(TheModule);
Teresa Johnson94624ac2017-05-10 18:52:16 +0000432 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000433 WriteBitcodeToFile(TheModule, OS, true, &Index);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000434 }
Weiming Zhao79f2d092018-04-16 03:44:03 +0000435 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
Mehdi Amini43b657b2016-04-01 06:47:02 +0000436 }
437
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000438 return codegenModule(TheModule, TM);
439}
440
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000441/// Resolve prevailing symbols. Record resolutions in the \p ResolvedODR map
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000442/// for caching, and in the \p Index for application during the ThinLTO
443/// backends. This is needed for correctness for exported symbols (ensure
444/// at least one copy kept) and a compile-time optimization (to drop duplicate
445/// copies when possible).
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000446static void resolvePrevailingInIndex(
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000447 ModuleSummaryIndex &Index,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000448 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
449 &ResolvedODR) {
450
451 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
452 computePrevailingCopies(Index, PrevailingCopy);
453
454 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
455 const auto &Prevailing = PrevailingCopy.find(GUID);
456 // Not in map means that there was only one copy, which must be prevailing.
457 if (Prevailing == PrevailingCopy.end())
458 return true;
459 return Prevailing->second == S;
460 };
461
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000462 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
463 GlobalValue::GUID GUID,
464 GlobalValue::LinkageTypes NewLinkage) {
465 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
466 };
467
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000468 thinLTOResolvePrevailingInIndex(Index, isPrevailing, recordNewLinkage);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000469}
470
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000471// Initialize the TargetMachine builder for a given Triple
472static void initTMBuilder(TargetMachineBuilder &TMBuilder,
473 const Triple &TheTriple) {
474 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
475 // FIXME this looks pretty terrible...
476 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
477 if (TheTriple.getArch() == llvm::Triple::x86_64)
478 TMBuilder.MCpu = "core2";
479 else if (TheTriple.getArch() == llvm::Triple::x86)
480 TMBuilder.MCpu = "yonah";
481 else if (TheTriple.getArch() == llvm::Triple::aarch64)
482 TMBuilder.MCpu = "cyclone";
483 }
484 TMBuilder.TheTriple = std::move(TheTriple);
485}
486
487} // end anonymous namespace
488
489void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
Johan Engelendcebe4f2017-09-17 18:11:26 +0000490 ThinLTOBuffer Buffer(Data, Identifier);
Akira Hatanakab10bff12017-05-18 03:52:29 +0000491 LLVMContext Context;
492 StringRef TripleStr;
493 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
494 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
495
496 if (TripleOrErr)
497 TripleStr = *TripleOrErr;
498
499 Triple TheTriple(TripleStr);
500
501 if (Modules.empty())
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000502 initTMBuilder(TMBuilder, Triple(TheTriple));
Akira Hatanakab10bff12017-05-18 03:52:29 +0000503 else if (TMBuilder.TheTriple != TheTriple) {
504 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
505 report_fatal_error("ThinLTO modules with incompatible triples not "
506 "supported");
507 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000508 }
Akira Hatanakab10bff12017-05-18 03:52:29 +0000509
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000510 Modules.push_back(Buffer);
511}
512
513void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
514 PreservedSymbols.insert(Name);
515}
516
517void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000518 // FIXME: At the moment, we don't take advantage of this extra information,
519 // we're conservatively considering cross-references as preserved.
520 // CrossReferencedSymbols.insert(Name);
521 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000522}
523
524// TargetMachine factory
525std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
526 std::string ErrMsg;
527 const Target *TheTarget =
528 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
529 if (!TheTarget) {
530 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
531 }
532
533 // Use MAttr as the default set of features.
534 SubtargetFeatures Features(MAttr);
535 Features.getDefaultSubtargetFeatures(TheTriple);
536 std::string FeatureStr = Features.getString();
Mehdi Aminicc7fbf72016-12-28 19:37:16 +0000537
Rafael Espindola79e238a2017-08-03 02:16:21 +0000538 return std::unique_ptr<TargetMachine>(
539 TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options,
540 RelocModel, None, CGOptLevel));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000541}
542
543/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000544 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000545 * "thin-link".
546 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000547std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000548 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
Teresa Johnson4ffc3e72018-06-06 22:22:01 +0000549 llvm::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000550 uint64_t NextModuleId = 0;
551 for (auto &ModuleBuffer : Modules) {
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000552 if (Error Err = readModuleSummaryIndex(ModuleBuffer.getMemBuffer(),
553 *CombinedIndex, NextModuleId++)) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000554 // FIXME diagnose
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000555 logAllUnhandledErrors(
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000556 std::move(Err), errs(),
Peter Collingbournec15d60b2017-05-01 20:42:32 +0000557 "error: can't create module summary index for buffer: ");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000558 return nullptr;
559 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000560 }
561 return CombinedIndex;
562}
563
George Rimar2421b6f2018-01-17 10:33:05 +0000564static void internalizeAndPromoteInIndex(
565 const StringMap<FunctionImporter::ExportSetTy> &ExportLists,
566 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
567 ModuleSummaryIndex &Index) {
568 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
569 const auto &ExportList = ExportLists.find(ModuleIdentifier);
570 return (ExportList != ExportLists.end() &&
571 ExportList->second.count(GUID)) ||
572 GUIDPreservedSymbols.count(GUID);
573 };
574
575 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
576}
577
George Rimareaf51722018-01-29 08:03:30 +0000578static void computeDeadSymbolsInIndex(
579 ModuleSummaryIndex &Index,
580 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
581 // We have no symbols resolution available. And can't do any better now in the
582 // case where the prevailing symbol is in a native object. It can be refined
583 // with linker information in the future.
584 auto isPrevailing = [&](GlobalValue::GUID G) {
585 return PrevailingType::Unknown;
586 };
Eugene Leviantbf46e742018-11-16 07:08:00 +0000587 computeDeadSymbolsWithConstProp(Index, GUIDPreservedSymbols, isPrevailing,
588 /* ImportEnabled = */ true);
George Rimareaf51722018-01-29 08:03:30 +0000589}
590
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000591/**
592 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000593 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000594 */
595void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000596 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000597 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000598 auto ModuleIdentifier = TheModule.getModuleIdentifier();
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000599
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000600 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000601 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000602 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000603
Teresa Johnson6c475a72017-01-05 21:34:18 +0000604 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000605 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000606 PreservedSymbols, Triple(TheModule.getTargetTriple()));
607
608 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000609 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000610
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000611 // Generate import/export list
612 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
613 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
614 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000615 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000616
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000617 // Resolve prevailing symbols
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000618 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000619 resolvePrevailingInIndex(Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000620
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000621 thinLTOResolvePrevailingInModule(
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000622 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000623
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000624 // Promote the exported values in the index, so that they are promoted
625 // in the module.
George Rimar2421b6f2018-01-17 10:33:05 +0000626 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
Teresa Johnson4fef68c2016-11-14 19:21:41 +0000627
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000628 promoteModule(TheModule, Index);
629}
630
631/**
632 * Perform cross-module importing for the module identified by ModuleIdentifier.
633 */
634void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000635 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000636 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000637 auto ModuleCount = Index.modulePaths().size();
638
639 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000640 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000641 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000642
Teresa Johnson6c475a72017-01-05 21:34:18 +0000643 // Convert the preserved symbols set from string to GUID
Mehdi Amini1380edf2017-02-03 07:41:43 +0000644 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
Teresa Johnson6c475a72017-01-05 21:34:18 +0000645 PreservedSymbols, Triple(TheModule.getTargetTriple()));
646
647 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000648 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000649
Mehdi Amini01e32132016-03-26 05:40:34 +0000650 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000651 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
652 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000653 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000654 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000655 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
656
657 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000658}
659
660/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000661 * Compute the list of summaries needed for importing into module.
662 */
663void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
664 StringRef ModulePath, ModuleSummaryIndex &Index,
665 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
666 auto ModuleCount = Index.modulePaths().size();
667
668 // Collect for each module the list of function it defines (GUID -> Summary).
669 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
670 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
671
672 // Generate import/export list
673 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
674 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
675 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
676 ExportLists);
677
678 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000679 ImportLists[ModulePath],
Teresa Johnson84174c32016-05-10 13:48:23 +0000680 ModuleToSummariesForIndex);
681}
682
683/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000684 * Emit the list of files needed for importing into module.
685 */
686void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
687 StringRef OutputName,
688 ModuleSummaryIndex &Index) {
689 auto ModuleCount = Index.modulePaths().size();
690
691 // Collect for each module the list of function it defines (GUID -> Summary).
692 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
693 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
694
695 // Generate import/export list
696 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
697 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
698 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
699 ExportLists);
700
Teresa Johnsonc0320ef2018-07-10 20:06:04 +0000701 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
702 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
703 ImportLists[ModulePath],
704 ModuleToSummariesForIndex);
705
Teresa Johnson8570fe42016-05-10 15:54:09 +0000706 std::error_code EC;
Teresa Johnsonc0320ef2018-07-10 20:06:04 +0000707 if ((EC =
708 EmitImportsFiles(ModulePath, OutputName, ModuleToSummariesForIndex)))
Teresa Johnson8570fe42016-05-10 15:54:09 +0000709 report_fatal_error(Twine("Failed to open ") + OutputName +
710 " to save imports lists\n");
711}
712
713/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000714 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000715 */
716void ThinLTOCodeGenerator::internalize(Module &TheModule,
717 ModuleSummaryIndex &Index) {
718 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
719 auto ModuleCount = Index.modulePaths().size();
720 auto ModuleIdentifier = TheModule.getModuleIdentifier();
721
722 // Convert the preserved symbols set from string to GUID
723 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000724 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Amini059464f2016-04-24 03:18:01 +0000725
726 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000727 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000728 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
729
Teresa Johnson6c475a72017-01-05 21:34:18 +0000730 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000731 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000732
Mehdi Amini059464f2016-04-24 03:18:01 +0000733 // Generate import/export list
734 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
735 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
736 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000737 ExportLists);
Mehdi Amini059464f2016-04-24 03:18:01 +0000738 auto &ExportList = ExportLists[ModuleIdentifier];
739
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000740 // Be friendly and don't nuke totally the module when the client didn't
741 // supply anything to preserve.
742 if (ExportList.empty() && GUIDPreservedSymbols.empty())
743 return;
744
Mehdi Amini059464f2016-04-24 03:18:01 +0000745 // Internalization
George Rimar2421b6f2018-01-17 10:33:05 +0000746 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000747 thinLTOInternalizeModule(TheModule,
748 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000749}
750
751/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000752 * Perform post-importing ThinLTO optimizations.
753 */
754void ThinLTOCodeGenerator::optimize(Module &TheModule) {
755 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000756
757 // Optimize now
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000758 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000759}
760
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000761/// Write out the generated object file, either from CacheEntryPath or from
762/// OutputBuffer, preferring hard-link when possible.
763/// Returns the path to the generated file in SavedObjectsDirectoryPath.
764static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
765 StringRef SavedObjectsDirectoryPath,
766 const MemoryBuffer &OutputBuffer) {
767 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
768 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
769 OutputPath.c_str(); // Ensure the string is null terminated.
770 if (sys::fs::exists(OutputPath))
771 sys::fs::remove(OutputPath);
772
773 // We don't return a memory buffer to the linker, just a list of files.
774 if (!CacheEntryPath.empty()) {
775 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
776 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
777 if (!Err)
778 return OutputPath.str();
779 // Hard linking failed, try to copy.
780 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
781 if (!Err)
782 return OutputPath.str();
783 // Copy failed (could be because the CacheEntry was removed from the cache
784 // in the meantime by another process), fall back and try to write down the
785 // buffer to the output.
786 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
787 << "' to '" << OutputPath << "'\n";
788 }
789 // No cache entry, just write out the buffer.
790 std::error_code Err;
791 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
792 if (Err)
793 report_fatal_error("Can't open output '" + OutputPath + "'\n");
794 OS << OutputBuffer.getBuffer();
795 return OutputPath.str();
796}
797
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000798// Main entry point for the ThinLTO processing
799void ThinLTOCodeGenerator::run() {
Mehdi Aminib2990462017-01-20 22:45:34 +0000800 // Prepare the resulting object vector
801 assert(ProducedBinaries.empty() && "The generator should not be reused");
802 if (SavedObjectsDirectoryPath.empty())
803 ProducedBinaries.resize(Modules.size());
804 else {
805 sys::fs::create_directories(SavedObjectsDirectoryPath);
806 bool IsDir;
807 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
808 if (!IsDir)
809 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
810 ProducedBinaryFiles.resize(Modules.size());
811 }
812
Mehdi Amini43b657b2016-04-01 06:47:02 +0000813 if (CodeGenOnly) {
814 // Perform only parallel codegen and return.
815 ThreadPool Pool;
Mehdi Amini43b657b2016-04-01 06:47:02 +0000816 int count = 0;
817 for (auto &ModuleBuffer : Modules) {
818 Pool.async([&](int count) {
819 LLVMContext Context;
820 Context.setDiscardValueNames(LTODiscardValueNames);
821
822 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000823 auto TheModule =
824 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
825 /*IsImporting*/ false);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000826
827 // CodeGen
Steven Wucf902032018-09-04 22:54:17 +0000828 auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create());
Mehdi Aminib2990462017-01-20 22:45:34 +0000829 if (SavedObjectsDirectoryPath.empty())
830 ProducedBinaries[count] = std::move(OutputBuffer);
831 else
832 ProducedBinaryFiles[count] = writeGeneratedObject(
833 count, "", SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini43b657b2016-04-01 06:47:02 +0000834 }, count++);
835 }
836
837 return;
838 }
839
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000840 // Sequential linking phase
841 auto Index = linkCombinedIndex();
842
843 // Save temps: index.
844 if (!SaveTempsDir.empty()) {
845 auto SaveTempPath = SaveTempsDir + "index.bc";
846 std::error_code EC;
847 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
848 if (EC)
849 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
850 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000851 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000852 }
853
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000854
855 // Prepare the module map.
856 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000857 auto ModuleCount = Modules.size();
858
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000859 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000860 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000861 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
862
Teresa Johnson6c475a72017-01-05 21:34:18 +0000863 // Convert the preserved symbols set from string to GUID, this is needed for
864 // computing the caching hash and the internalization.
865 auto GUIDPreservedSymbols =
Mehdi Amini1380edf2017-02-03 07:41:43 +0000866 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000867
868 // Compute "dead" symbols, we don't want to import/export these!
George Rimareaf51722018-01-29 08:03:30 +0000869 computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols);
Teresa Johnson6c475a72017-01-05 21:34:18 +0000870
Mehdi Amini01e32132016-03-26 05:40:34 +0000871 // Collect the import/export lists for all modules from the call-graph in the
872 // combined index.
873 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
874 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000875 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
Evgeniy Stepanov56584bb2017-06-01 20:30:06 +0000876 ExportLists);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000877
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000878 // We use a std::map here to be able to have a defined ordering when
879 // producing a hash for the cache entry.
880 // FIXME: we should be able to compute the caching hash for the entry based
881 // on the index, and nuke this map.
882 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
883
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000884 // Resolve prevailing symbols, this has to be computed early because it
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000885 // impacts the caching.
Pirama Arumuga Nainare61652a2018-11-08 20:10:07 +0000886 resolvePrevailingInIndex(*Index, ResolvedODR);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000887
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000888 // Use global summary-based analysis to identify symbols that can be
889 // internalized (because they aren't exported or preserved as per callback).
890 // Changes are made in the index, consumed in the ThinLTO backends.
George Rimar2421b6f2018-01-17 10:33:05 +0000891 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, *Index);
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000892
Steven Wuec53c892018-09-14 19:38:21 +0000893 // Make sure that every module has an entry in the ExportLists, ImportList,
894 // GVSummary and ResolvedODR maps to enable threaded access to these maps
895 // below.
896 for (auto &Module : Modules) {
897 auto ModuleIdentifier = Module.getBufferIdentifier();
898 ExportLists[ModuleIdentifier];
899 ImportLists[ModuleIdentifier];
900 ResolvedODR[ModuleIdentifier];
901 ModuleToDefinedGVSummaries[ModuleIdentifier];
Teresa Johnson141149f2016-05-24 18:44:01 +0000902 }
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000903
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000904 // Compute the ordering we will process the inputs: the rough heuristic here
905 // is to sort them per size so that the largest module get schedule as soon as
906 // possible. This is purely a compile-time optimization.
907 std::vector<int> ModulesOrdering;
908 ModulesOrdering.resize(Modules.size());
909 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
Fangrui Song0cac7262018-09-27 02:13:45 +0000910 llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) {
911 auto LSize = Modules[LeftIndex].getBuffer().size();
912 auto RSize = Modules[RightIndex].getBuffer().size();
913 return LSize > RSize;
914 });
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000915
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000916 // Parallel optimizer + codegen
917 {
918 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000919 for (auto IndexCount : ModulesOrdering) {
920 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000921 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000922 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000923 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000924
Eugene Leviantbf46e742018-11-16 07:08:00 +0000925 auto &DefinedGVSummaries = ModuleToDefinedGVSummaries[ModuleIdentifier];
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000926
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000927 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000928 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
929 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000930 ResolvedODR[ModuleIdentifier],
Teresa Johnson5f312ad2018-11-26 20:40:37 +0000931 DefinedGVSummaries, OptLevel, Freestanding,
932 TMBuilder);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000933 auto CacheEntryPath = CacheEntry.getEntryPath();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000934
935 {
936 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000937 LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss")
938 << " '" << CacheEntryPath << "' for buffer "
939 << count << " " << ModuleIdentifier << "\n");
Mehdi Amini059464f2016-04-24 03:18:01 +0000940
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000941 if (ErrOrBuffer) {
942 // Cache Hit!
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000943 if (SavedObjectsDirectoryPath.empty())
944 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
945 else
946 ProducedBinaryFiles[count] = writeGeneratedObject(
947 count, CacheEntryPath, SavedObjectsDirectoryPath,
948 *ErrOrBuffer.get());
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000949 return;
950 }
951 }
952
953 LLVMContext Context;
954 Context.setDiscardValueNames(LTODiscardValueNames);
955 Context.enableDebugTypeODRUniquing();
Davide Italiano690ed9d2017-02-10 23:49:38 +0000956 auto DiagFileOrErr = lto::setupOptimizationRemarks(
Bob Haarmanfb2d3422018-03-08 01:13:10 +0000957 Context, LTORemarksFilename, LTOPassRemarksWithHotness, count);
Mehdi Amini19f176b2016-11-19 18:20:05 +0000958 if (!DiagFileOrErr) {
959 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
960 report_fatal_error("ThinLTO: Can't get an output file for the "
961 "remarks");
962 }
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000963
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000964 // Parse module now
Mehdi Aminia0ddb1e2017-02-14 02:20:51 +0000965 auto TheModule =
966 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
967 /*IsImporting*/ false);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000968
969 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000970 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000971
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000972 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000973 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000974 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000975 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000976 ExportList, GUIDPreservedSymbols,
977 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000978 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000979
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000980 // Commit to the cache (if enabled)
981 CacheEntry.write(*OutputBuffer);
982
983 if (SavedObjectsDirectoryPath.empty()) {
984 // We need to generated a memory buffer for the linker.
985 if (!CacheEntryPath.empty()) {
Fangrui Songf78650a2018-07-30 19:41:25 +0000986 // When cache is enabled, reload from the cache if possible.
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000987 // Releasing the buffer from the heap and reloading it from the
Fangrui Songf78650a2018-07-30 19:41:25 +0000988 // cache file with mmap helps us to lower memory pressure.
989 // The freed memory can be used for the next input file.
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000990 // The final binary link will read from the VFS cache (hopefully!)
991 // or from disk (if the memory pressure was too high).
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000992 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
993 if (auto EC = ReloadedBufferOrErr.getError()) {
Ekaterina Romanova0b01dfb2018-03-30 21:35:42 +0000994 // On error, keep the preexisting buffer and print a diagnostic.
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000995 errs() << "error: can't reload cached file '" << CacheEntryPath
996 << "': " << EC.message() << "\n";
997 } else {
998 OutputBuffer = std::move(*ReloadedBufferOrErr);
999 }
1000 }
1001 ProducedBinaries[count] = std::move(OutputBuffer);
1002 return;
1003 }
1004 ProducedBinaryFiles[count] = writeGeneratedObject(
1005 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001006 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001007 }
1008 }
1009
Peter Collingbournecead56f2017-03-15 22:54:18 +00001010 pruneCache(CacheOptions.Path, CacheOptions.Policy);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001011
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001012 // If statistics were requested, print them out now.
1013 if (llvm::AreStatisticsEnabled())
1014 llvm::PrintStatistics();
James Henderson852f6fd2017-05-16 09:43:21 +00001015 reportAndResetTimings();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001016}