blob: a91cf4f8d4a5b4e76651e9df9d76da854046c050 [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
15#include "llvm/LTO/ThinLTOCodeGenerator.h"
16
Mehdi Aminif95f77a2016-04-21 05:54:23 +000017#ifdef HAVE_LLVM_REVISION
18#include "LLVMLTORevision.h"
19#endif
Mehdi Amini059464f2016-04-24 03:18:01 +000020
21#include "UpdateCompilerUsed.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000022#include "llvm/ADT/Statistic.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000023#include "llvm/ADT/StringExtras.h"
Teresa Johnson2d5487c2016-04-11 13:58:45 +000024#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000025#include "llvm/Analysis/TargetLibraryInfo.h"
26#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000027#include "llvm/Bitcode/BitcodeWriterPass.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000028#include "llvm/Bitcode/ReaderWriter.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000029#include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000030#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000031#include "llvm/IR/LLVMContext.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000032#include "llvm/IR/LegacyPassManager.h"
33#include "llvm/IR/Mangler.h"
34#include "llvm/IRReader/IRReader.h"
35#include "llvm/Linker/Linker.h"
36#include "llvm/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000037#include "llvm/Object/IRObjectFile.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000038#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Mehdi Amini1aafabf2016-04-16 07:02:16 +000039#include "llvm/Support/Debug.h"
Mehdi Aminif95f77a2016-04-21 05:54:23 +000040#include "llvm/Support/CachePruning.h"
41#include "llvm/Support/Debug.h"
42#include "llvm/Support/Path.h"
43#include "llvm/Support/SHA1.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000044#include "llvm/Support/SourceMgr.h"
45#include "llvm/Support/TargetRegistry.h"
46#include "llvm/Support/ThreadPool.h"
47#include "llvm/Target/TargetMachine.h"
48#include "llvm/Transforms/IPO.h"
49#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000050#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000051#include "llvm/Transforms/IPO/PassManagerBuilder.h"
52#include "llvm/Transforms/ObjCARC.h"
53#include "llvm/Transforms/Utils/FunctionImportUtils.h"
54
55using namespace llvm;
56
Mehdi Amini1aafabf2016-04-16 07:02:16 +000057#define DEBUG_TYPE "thinlto"
58
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000059namespace llvm {
60// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
61extern cl::opt<bool> LTODiscardValueNames;
62}
63
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000064namespace {
65
66static cl::opt<int> ThreadCount("threads",
67 cl::init(std::thread::hardware_concurrency()));
68
69static void diagnosticHandler(const DiagnosticInfo &DI) {
70 DiagnosticPrinterRawOStream DP(errs());
71 DI.print(DP);
72 errs() << '\n';
73}
74
75// Simple helper to load a module from bitcode
76static std::unique_ptr<Module>
77loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
78 bool Lazy) {
79 SMDiagnostic Err;
80 ErrorOr<std::unique_ptr<Module>> ModuleOrErr(nullptr);
81 if (Lazy) {
82 ModuleOrErr =
83 getLazyBitcodeModule(MemoryBuffer::getMemBuffer(Buffer, false), Context,
84 /* ShouldLazyLoadMetadata */ Lazy);
85 } else {
86 ModuleOrErr = parseBitcodeFile(Buffer, Context);
87 }
88 if (std::error_code EC = ModuleOrErr.getError()) {
89 Err = SMDiagnostic(Buffer.getBufferIdentifier(), SourceMgr::DK_Error,
90 EC.message());
91 Err.print("ThinLTO", errs());
92 report_fatal_error("Can't load module, abort.");
93 }
94 return std::move(ModuleOrErr.get());
95}
96
97// Simple helper to save temporary files for debug.
98static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
99 unsigned count, StringRef Suffix) {
100 if (TempDir.empty())
101 return;
102 // User asked to save temps, let dump the bitcode file after import.
103 auto SaveTempPath = TempDir + llvm::utostr(count) + Suffix;
104 std::error_code EC;
105 raw_fd_ostream OS(SaveTempPath.str(), EC, sys::fs::F_None);
106 if (EC)
107 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
108 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +0000109 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000110}
111
Teresa Johnson28e457b2016-04-24 14:57:11 +0000112bool IsFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList,
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000113 const ModuleSummaryIndex &Index,
114 StringRef ModulePath) {
115 // Get the first *linker visible* definition for this global in the summary
116 // list.
117 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000118 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
119 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000120 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
121 });
122 // If \p GV is not the first definition, give up...
Teresa Johnson28e457b2016-04-24 14:57:11 +0000123 if ((*FirstDefForLinker)->modulePath() != ModulePath)
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000124 return false;
125 // If there is any strong definition anywhere, do not bother emitting this.
126 if (llvm::any_of(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000127 GVSummaryList,
128 [](const std::unique_ptr<GlobalValueSummary> &Summary) {
129 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000130 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
131 !GlobalValue::isWeakForLinker(Linkage);
132 }))
133 return false;
134 return true;
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000135}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000136
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000137static GlobalValue::LinkageTypes
138ResolveODR(const ModuleSummaryIndex &Index,
139 const FunctionImporter::ExportSetTy &ExportList,
Mehdi Aminiaa309b12016-04-26 10:35:01 +0000140 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000141 StringRef ModuleIdentifier, GlobalValue::GUID GUID,
142 const GlobalValueSummary &GV) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000143 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
144 return GVSummaryList.size() > 1;
145 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000146
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000147 auto OriginalLinkage = GV.linkage();
148 switch (OriginalLinkage) {
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000149 case GlobalValue::ExternalLinkage:
150 case GlobalValue::AvailableExternallyLinkage:
151 case GlobalValue::AppendingLinkage:
152 case GlobalValue::InternalLinkage:
153 case GlobalValue::PrivateLinkage:
154 case GlobalValue::ExternalWeakLinkage:
155 case GlobalValue::CommonLinkage:
156 case GlobalValue::LinkOnceAnyLinkage:
157 case GlobalValue::WeakAnyLinkage:
158 break;
159 case GlobalValue::LinkOnceODRLinkage:
160 case GlobalValue::WeakODRLinkage: {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000161 auto &GVSummaryList = Index.findGlobalValueSummaryList(GUID)->second;
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000162 // We need to emit only one of these, the first module will keep
163 // it, but turned into a weak while the others will drop it.
Teresa Johnson28e457b2016-04-24 14:57:11 +0000164 if (!HasMultipleCopies(GVSummaryList)) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000165 // Exported LinkonceODR needs to be promoted to not be discarded
166 if (GlobalValue::isDiscardableIfUnused(OriginalLinkage) &&
Mehdi Aminiaa309b12016-04-26 10:35:01 +0000167 (ExportList.count(GUID) || GUIDPreservedSymbols.count(GUID)))
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000168 return GlobalValue::WeakODRLinkage;
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000169 break;
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000170 }
Teresa Johnson28e457b2016-04-24 14:57:11 +0000171 if (IsFirstDefinitionForLinker(GVSummaryList, Index, ModuleIdentifier))
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000172 return GlobalValue::WeakODRLinkage;
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000173 else if (isa<AliasSummary>(&GV))
174 // Alias can't be turned into available_externally.
175 return OriginalLinkage;
176 return GlobalValue::AvailableExternallyLinkage;
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000177 }
178 }
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000179 return OriginalLinkage;
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000180}
181
182/// Resolve LinkOnceODR and WeakODR.
183///
184/// We'd like to drop these function if they are no longer referenced in the
185/// current module. However there is a chance that another module is still
186/// referencing them because of the import. We make sure we always emit at least
187/// one copy.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000188static void ResolveODR(
189 const ModuleSummaryIndex &Index,
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000190 const FunctionImporter::ExportSetTy &ExportList,
Mehdi Aminiaa309b12016-04-26 10:35:01 +0000191 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000192 const GVSummaryMapTy &DefinedGlobals, StringRef ModuleIdentifier,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000193 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR) {
Mehdi Amini8dcc8082016-04-14 08:46:22 +0000194 if (Index.modulePaths().size() == 1)
195 // Nothing to do if we don't have multiple modules
196 return;
197
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000198 // We won't optimize the globals that are referenced by an alias for now
199 // Ideally we should turn the alias into a global and duplicate the definition
200 // when needed.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000201 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
202 for (auto &GA : DefinedGlobals) {
203 if (auto AS = dyn_cast<AliasSummary>(GA.second))
204 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000205 }
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000206
207 for (auto &GV : DefinedGlobals) {
208 if (GlobalInvolvedWithAlias.count(GV.second))
209 continue;
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000210 auto NewLinkage =
Mehdi Aminiaa309b12016-04-26 10:35:01 +0000211 ResolveODR(Index, ExportList, GUIDPreservedSymbols, ModuleIdentifier, GV.first, *GV.second);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000212 if (NewLinkage != GV.second->linkage()) {
213 ResolvedODR[GV.first] = NewLinkage;
214 }
215 }
216}
217
218/// Fixup linkage, see ResolveODR() above.
219void fixupODR(
220 Module &TheModule,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000221 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR) {
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000222 // Process functions and global now
223 for (auto &GV : TheModule) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000224 auto NewLinkage = ResolvedODR.find(GV.getGUID());
225 if (NewLinkage == ResolvedODR.end())
226 continue;
227 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
228 << GV.getLinkage() << " to " << NewLinkage->second << "\n");
229 GV.setLinkage(NewLinkage->second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000230 }
231 for (auto &GV : TheModule.globals()) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000232 auto NewLinkage = ResolvedODR.find(GV.getGUID());
233 if (NewLinkage == ResolvedODR.end())
234 continue;
235 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
236 << GV.getLinkage() << " to " << NewLinkage->second << "\n");
237 GV.setLinkage(NewLinkage->second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000238 }
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000239 for (auto &GV : TheModule.aliases()) {
240 auto NewLinkage = ResolvedODR.find(GV.getGUID());
241 if (NewLinkage == ResolvedODR.end())
242 continue;
243 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
244 << GV.getLinkage() << " to " << NewLinkage->second << "\n");
245 GV.setLinkage(NewLinkage->second);
246 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000247}
248
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000249static StringMap<MemoryBufferRef>
250generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
251 StringMap<MemoryBufferRef> ModuleMap;
252 for (auto &ModuleBuffer : Modules) {
253 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
254 ModuleMap.end() &&
255 "Expect unique Buffer Identifier");
256 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
257 }
258 return ModuleMap;
259}
260
261/// Provide a "loader" for the FunctionImporter to access function from other
262/// modules.
263class ModuleLoader {
264 /// The context that will be used for importing.
265 LLVMContext &Context;
266
267 /// Map from Module identifier to MemoryBuffer. Used by clients like the
268 /// FunctionImported to request loading a Module.
269 StringMap<MemoryBufferRef> &ModuleMap;
270
271public:
272 ModuleLoader(LLVMContext &Context, StringMap<MemoryBufferRef> &ModuleMap)
273 : Context(Context), ModuleMap(ModuleMap) {}
274
275 /// Load a module on demand.
276 std::unique_ptr<Module> operator()(StringRef Identifier) {
277 return loadModuleFromBuffer(ModuleMap[Identifier], Context, /*Lazy*/ true);
278 }
279};
280
Teresa Johnson26ab5772016-03-15 00:04:37 +0000281static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000282 if (renameModuleForThinLTO(TheModule, Index))
283 report_fatal_error("renameModuleForThinLTO failed");
284}
285
Mehdi Amini01e32132016-03-26 05:40:34 +0000286static void
287crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
288 StringMap<MemoryBufferRef> &ModuleMap,
289 const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000290 ModuleLoader Loader(TheModule.getContext(), ModuleMap);
291 FunctionImporter Importer(Index, Loader);
Mehdi Amini01e32132016-03-26 05:40:34 +0000292 Importer.importFunctions(TheModule, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000293}
294
295static void optimizeModule(Module &TheModule, TargetMachine &TM) {
296 // Populate the PassManager
297 PassManagerBuilder PMB;
298 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
299 PMB.Inliner = createFunctionInliningPass();
300 // FIXME: should get it from the bitcode?
301 PMB.OptLevel = 3;
302 PMB.LoopVectorize = true;
303 PMB.SLPVectorize = true;
304 PMB.VerifyInput = true;
305 PMB.VerifyOutput = false;
306
307 legacy::PassManager PM;
308
309 // Add the TTI (required to inform the vectorizer about register size for
310 // instance)
311 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
312
313 // Add optimizations
314 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000315
316 PM.run(TheModule);
317}
318
Mehdi Amini059464f2016-04-24 03:18:01 +0000319// Create a DenseSet of GlobalValue to be used with the Internalizer.
320static DenseSet<const GlobalValue *> computePreservedSymbolsForModule(
321 Module &TheModule, const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
322 const FunctionImporter::ExportSetTy &ExportList) {
323 DenseSet<const GlobalValue *> PreservedGV;
324 if (GUIDPreservedSymbols.empty())
325 // Early exit: internalize is disabled when there is nothing to preserve.
326 return PreservedGV;
327
328 auto AddPreserveGV = [&](const GlobalValue &GV) {
329 auto GUID = GV.getGUID();
330 if (GUIDPreservedSymbols.count(GUID) || ExportList.count(GUID))
331 PreservedGV.insert(&GV);
332 };
333
334 for (auto &GV : TheModule)
335 AddPreserveGV(GV);
336 for (auto &GV : TheModule.globals())
337 AddPreserveGV(GV);
338 for (auto &GV : TheModule.aliases())
339 AddPreserveGV(GV);
340
341 return PreservedGV;
342}
343
344// Run internalization on \p TheModule
345static void
346doInternalizeModule(Module &TheModule, const TargetMachine &TM,
347 const DenseSet<const GlobalValue *> &PreservedGV) {
348 if (PreservedGV.empty()) {
349 // Be friendly and don't nuke totally the module when the client didn't
350 // supply anything to preserve.
351 return;
352 }
353
354 // Parse inline ASM and collect the list of symbols that are not defined in
355 // the current module.
356 StringSet<> AsmUndefinedRefs;
357 object::IRObjectFile::CollectAsmUndefinedRefs(
358 Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
359 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
360 if (Flags & object::BasicSymbolRef::SF_Undefined)
361 AsmUndefinedRefs.insert(Name);
362 });
363
364 // Update the llvm.compiler_used globals to force preserving libcalls and
365 // symbols referenced from asm
366 UpdateCompilerUsed(TheModule, TM, AsmUndefinedRefs);
367
368 // Declare a callback for the internalize pass that will ask for every
369 // candidate GlobalValue if it can be internalized or not.
370 auto MustPreserveGV =
371 [&](const GlobalValue &GV) -> bool { return PreservedGV.count(&GV); };
372
373 llvm::internalizeModule(TheModule, MustPreserveGV);
374}
375
376// Convert the PreservedSymbols map from "Name" based to "GUID" based.
377static DenseSet<GlobalValue::GUID>
378computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
379 const Triple &TheTriple) {
380 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
381 for (auto &Entry : PreservedSymbols) {
382 StringRef Name = Entry.first();
383 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
384 Name = Name.drop_front();
385 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
386 }
387 return GUIDPreservedSymbols;
388}
389
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000390std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
391 TargetMachine &TM) {
392 SmallVector<char, 128> OutputBuffer;
393
394 // CodeGen
395 {
396 raw_svector_ostream OS(OutputBuffer);
397 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000398
399 // If the bitcode files contain ARC code and were compiled with optimization,
400 // the ObjCARCContractPass must be run, so do it unconditionally here.
401 PM.add(createObjCARCContractPass());
402
403 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000404 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
405 /* DisableVerify */ true))
406 report_fatal_error("Failed to setup codegen");
407
408 // Run codegen now. resulting binary is in OutputBuffer.
409 PM.run(TheModule);
410 }
411 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
412}
413
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000414/// Manage caching for a single Module.
415class ModuleCacheEntry {
416 SmallString<128> EntryPath;
417
418public:
419 // Create a cache entry. This compute a unique hash for the Module considering
420 // the current list of export/import, and offer an interface to query to
421 // access the content in the cache.
422 ModuleCacheEntry(
423 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
424 const FunctionImporter::ImportMapTy &ImportList,
425 const FunctionImporter::ExportSetTy &ExportList,
426 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000427 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000428 const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
429 if (CachePath.empty())
430 return;
431
432 // Compute the unique hash for this entry
433 // This is based on the current compiler version, the module itself, the
434 // export list, the hash for every single module in the import list, the
435 // list of ResolvedODR for the module, and the list of preserved symbols.
436
437 SHA1 Hasher;
438
439 // Start with the compiler revision
440 Hasher.update(LLVM_VERSION_STRING);
441#ifdef HAVE_LLVM_REVISION
442 Hasher.update(LLVM_REVISION);
443#endif
444
445 // Include the hash for the current module
446 auto ModHash = Index.getModuleHash(ModuleID);
447 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
448 for (auto F : ExportList)
449 // The export list can impact the internalization, be conservative here
450 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
451
452 // Include the hash for every module we import functions from
453 for (auto &Entry : ImportList) {
454 auto ModHash = Index.getModuleHash(Entry.first());
455 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
456 }
457
458 // Include the hash for the resolved ODR.
459 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000460 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000461 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000462 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000463 sizeof(GlobalValue::LinkageTypes)));
464 }
465
466 // Include the hash for the preserved symbols.
467 for (auto &Entry : PreservedSymbols) {
468 if (DefinedFunctions.count(Entry))
469 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000470 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000471 }
472
473 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
474 }
475
Mehdi Amini059464f2016-04-24 03:18:01 +0000476 // Access the path to this entry in the cache.
477 StringRef getEntryPath() { return EntryPath; }
478
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000479 // Try loading the buffer for this cache entry.
480 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
481 if (EntryPath.empty())
482 return std::error_code();
483 return MemoryBuffer::getFile(EntryPath);
484 }
485
486 // Cache the Produced object file
Mehdi Amini001bb412016-05-16 19:11:59 +0000487 std::unique_ptr<MemoryBuffer>
488 write(std::unique_ptr<MemoryBuffer> OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000489 if (EntryPath.empty())
Mehdi Amini001bb412016-05-16 19:11:59 +0000490 return OutputBuffer;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000491
492 // Write to a temporary to avoid race condition
493 SmallString<128> TempFilename;
494 int TempFD;
495 std::error_code EC =
496 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
497 if (EC) {
498 errs() << "Error: " << EC.message() << "\n";
499 report_fatal_error("ThinLTO: Can't get a temporary file");
500 }
501 {
502 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini001bb412016-05-16 19:11:59 +0000503 OS << OutputBuffer->getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000504 }
505 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000506 EC = sys::fs::rename(TempFilename, EntryPath);
507 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000508 sys::fs::remove(TempFilename);
509 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
510 if (EC)
511 report_fatal_error(Twine("Failed to open ") + EntryPath +
512 " to save cached entry\n");
Mehdi Amini001bb412016-05-16 19:11:59 +0000513 OS << OutputBuffer->getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000514 }
Mehdi Amini001bb412016-05-16 19:11:59 +0000515 auto ReloadedBufferOrErr = MemoryBuffer::getFile(EntryPath);
516 if (auto EC = ReloadedBufferOrErr.getError()) {
517 // FIXME diagnose
518 errs() << "error: can't reload cached file '" << EntryPath
519 << "': " << EC.message() << "\n";
520 return OutputBuffer;
521 }
522 return std::move(*ReloadedBufferOrErr);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000523 }
524};
525
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000526static std::unique_ptr<MemoryBuffer> ProcessThinLTOModule(
527 Module &TheModule, const ModuleSummaryIndex &Index,
528 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
529 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Amini059464f2016-04-24 03:18:01 +0000530 const FunctionImporter::ExportSetTy &ExportList,
531 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000532 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000533 ThinLTOCodeGenerator::CachingOptions CacheOptions, bool DisableCodeGen,
534 StringRef SaveTempsDir, unsigned count) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000535
Mehdi Amini059464f2016-04-24 03:18:01 +0000536 // Prepare for internalization by computing the set of symbols to preserve.
537 // We need to compute the list of symbols to preserve during internalization
538 // before doing any promotion because after renaming we won't (easily) match
539 // to the original name.
540 auto PreservedGV = computePreservedSymbolsForModule(
541 TheModule, GUIDPreservedSymbols, ExportList);
542
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000543 // "Benchmark"-like optimization: single-source case
544 bool SingleModule = (ModuleMap.size() == 1);
545
546 if (!SingleModule) {
547 promoteModule(TheModule, Index);
548
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000549 // Resolve the LinkOnce/Weak ODR, trying to turn them into
550 // "available_externally" when possible.
551 // This is a compile-time optimization.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000552 fixupODR(TheModule, ResolvedODR);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000553
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000554 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000555 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000556 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000557
Mehdi Amini059464f2016-04-24 03:18:01 +0000558 // Internalization
559 doInternalizeModule(TheModule, TM, PreservedGV);
560
561 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000562 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000563
564 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000565 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000566
567 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000568 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000569 }
570
571 optimizeModule(TheModule, TM);
572
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000573 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000574
Mehdi Amini43b657b2016-04-01 06:47:02 +0000575 if (DisableCodeGen) {
576 // Configured to stop before CodeGen, serialize the bitcode and return.
577 SmallVector<char, 128> OutputBuffer;
578 {
579 raw_svector_ostream OS(OutputBuffer);
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000580 ModuleSummaryIndexBuilder IndexBuilder(&TheModule);
581 WriteBitcodeToFile(&TheModule, OS, true, &IndexBuilder.getIndex());
Mehdi Amini43b657b2016-04-01 06:47:02 +0000582 }
583 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
584 }
585
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000586 return codegenModule(TheModule, TM);
587}
588
589// Initialize the TargetMachine builder for a given Triple
590static void initTMBuilder(TargetMachineBuilder &TMBuilder,
591 const Triple &TheTriple) {
592 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
593 // FIXME this looks pretty terrible...
594 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
595 if (TheTriple.getArch() == llvm::Triple::x86_64)
596 TMBuilder.MCpu = "core2";
597 else if (TheTriple.getArch() == llvm::Triple::x86)
598 TMBuilder.MCpu = "yonah";
599 else if (TheTriple.getArch() == llvm::Triple::aarch64)
600 TMBuilder.MCpu = "cyclone";
601 }
602 TMBuilder.TheTriple = std::move(TheTriple);
603}
604
605} // end anonymous namespace
606
607void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
608 MemoryBufferRef Buffer(Data, Identifier);
609 if (Modules.empty()) {
610 // First module added, so initialize the triple and some options
611 LLVMContext Context;
612 Triple TheTriple(getBitcodeTargetTriple(Buffer, Context));
613 initTMBuilder(TMBuilder, Triple(TheTriple));
614 }
615#ifndef NDEBUG
616 else {
617 LLVMContext Context;
618 assert(TMBuilder.TheTriple.str() ==
619 getBitcodeTargetTriple(Buffer, Context) &&
620 "ThinLTO modules with different triple not supported");
621 }
622#endif
623 Modules.push_back(Buffer);
624}
625
626void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
627 PreservedSymbols.insert(Name);
628}
629
630void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000631 // FIXME: At the moment, we don't take advantage of this extra information,
632 // we're conservatively considering cross-references as preserved.
633 // CrossReferencedSymbols.insert(Name);
634 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000635}
636
637// TargetMachine factory
638std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
639 std::string ErrMsg;
640 const Target *TheTarget =
641 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
642 if (!TheTarget) {
643 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
644 }
645
646 // Use MAttr as the default set of features.
647 SubtargetFeatures Features(MAttr);
648 Features.getDefaultSubtargetFeatures(TheTriple);
649 std::string FeatureStr = Features.getString();
650 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
651 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
652 CodeModel::Default, CGOptLevel));
653}
654
655/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000656 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000657 * "thin-link".
658 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000659std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
660 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000661 uint64_t NextModuleId = 0;
662 for (auto &ModuleBuffer : Modules) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000663 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
664 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer,
Teresa Johnson6fb3f192016-04-22 01:52:00 +0000665 diagnosticHandler);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000666 if (std::error_code EC = ObjOrErr.getError()) {
667 // FIXME diagnose
Teresa Johnson26ab5772016-03-15 00:04:37 +0000668 errs() << "error: can't create ModuleSummaryIndexObjectFile for buffer: "
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000669 << EC.message() << "\n";
670 return nullptr;
671 }
672 auto Index = (*ObjOrErr)->takeIndex();
673 if (CombinedIndex) {
674 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
675 } else {
676 CombinedIndex = std::move(Index);
677 }
678 }
679 return CombinedIndex;
680}
681
682/**
683 * Perform promotion and renaming of exported internal functions.
684 */
685void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000686 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000687 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000688 auto ModuleIdentifier = TheModule.getModuleIdentifier();
689 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000690 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000691 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000692
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000693 // Generate import/export list
694 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
695 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
696 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
697 ExportLists);
698 auto &ExportList = ExportLists[ModuleIdentifier];
699
Mehdi Aminiaa309b12016-04-26 10:35:01 +0000700 // Convert the preserved symbols set from string to GUID
701 auto GUIDPreservedSymbols =
702 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
703
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000704 // Resolve the LinkOnceODR, trying to turn them into "available_externally"
705 // where possible.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000706 // This is a compile-time optimization.
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000707 // We use a std::map here to be able to have a defined ordering when
708 // producing a hash for the cache entry.
709 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> ResolvedODR;
Mehdi Aminiaa309b12016-04-26 10:35:01 +0000710 ResolveODR(Index, ExportList, GUIDPreservedSymbols, ModuleToDefinedGVSummaries[ModuleIdentifier],
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000711 ModuleIdentifier, ResolvedODR);
712 fixupODR(TheModule, ResolvedODR);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000713
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000714 promoteModule(TheModule, Index);
715}
716
717/**
718 * Perform cross-module importing for the module identified by ModuleIdentifier.
719 */
720void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000721 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000722 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000723 auto ModuleCount = Index.modulePaths().size();
724
725 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000726 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000727 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000728
729 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000730 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
731 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000732 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
733 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000734 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
735
736 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000737}
738
739/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000740 * Compute the list of summaries needed for importing into module.
741 */
742void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
743 StringRef ModulePath, ModuleSummaryIndex &Index,
744 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
745 auto ModuleCount = Index.modulePaths().size();
746
747 // Collect for each module the list of function it defines (GUID -> Summary).
748 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
749 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
750
751 // Generate import/export list
752 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
753 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
754 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
755 ExportLists);
756
757 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
758 ImportLists,
759 ModuleToSummariesForIndex);
760}
761
762/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000763 * Emit the list of files needed for importing into module.
764 */
765void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
766 StringRef OutputName,
767 ModuleSummaryIndex &Index) {
768 auto ModuleCount = Index.modulePaths().size();
769
770 // Collect for each module the list of function it defines (GUID -> Summary).
771 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
772 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
773
774 // Generate import/export list
775 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
776 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
777 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
778 ExportLists);
779
780 std::error_code EC;
781 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists)))
782 report_fatal_error(Twine("Failed to open ") + OutputName +
783 " to save imports lists\n");
784}
785
786/**
Mehdi Amini059464f2016-04-24 03:18:01 +0000787 * Perform internalization.
788 */
789void ThinLTOCodeGenerator::internalize(Module &TheModule,
790 ModuleSummaryIndex &Index) {
791 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
792 auto ModuleCount = Index.modulePaths().size();
793 auto ModuleIdentifier = TheModule.getModuleIdentifier();
794
795 // Convert the preserved symbols set from string to GUID
796 auto GUIDPreservedSymbols =
797 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
798
799 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000800 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000801 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
802
803 // Generate import/export list
804 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
805 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
806 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
807 ExportLists);
808 auto &ExportList = ExportLists[ModuleIdentifier];
809
810 // Internalization
811 auto PreservedGV = computePreservedSymbolsForModule(
812 TheModule, GUIDPreservedSymbols, ExportList);
813 doInternalizeModule(TheModule, *TMBuilder.create(), PreservedGV);
814}
815
816/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000817 * Perform post-importing ThinLTO optimizations.
818 */
819void ThinLTOCodeGenerator::optimize(Module &TheModule) {
820 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000821
822 // Optimize now
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000823 optimizeModule(TheModule, *TMBuilder.create());
824}
825
826/**
827 * Perform ThinLTO CodeGen.
828 */
829std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
830 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
831 return codegenModule(TheModule, *TMBuilder.create());
832}
833
834// Main entry point for the ThinLTO processing
835void ThinLTOCodeGenerator::run() {
Mehdi Amini43b657b2016-04-01 06:47:02 +0000836 if (CodeGenOnly) {
837 // Perform only parallel codegen and return.
838 ThreadPool Pool;
839 assert(ProducedBinaries.empty() && "The generator should not be reused");
840 ProducedBinaries.resize(Modules.size());
841 int count = 0;
842 for (auto &ModuleBuffer : Modules) {
843 Pool.async([&](int count) {
844 LLVMContext Context;
845 Context.setDiscardValueNames(LTODiscardValueNames);
846
847 // Parse module now
848 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
849
850 // CodeGen
851 ProducedBinaries[count] = codegen(*TheModule);
852 }, count++);
853 }
854
855 return;
856 }
857
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000858 // Sequential linking phase
859 auto Index = linkCombinedIndex();
860
861 // Save temps: index.
862 if (!SaveTempsDir.empty()) {
863 auto SaveTempPath = SaveTempsDir + "index.bc";
864 std::error_code EC;
865 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
866 if (EC)
867 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
868 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000869 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000870 }
871
872 // Prepare the resulting object vector
873 assert(ProducedBinaries.empty() && "The generator should not be reused");
874 ProducedBinaries.resize(Modules.size());
875
876 // Prepare the module map.
877 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000878 auto ModuleCount = Modules.size();
879
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000880 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000881 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000882 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
883
Mehdi Amini01e32132016-03-26 05:40:34 +0000884 // Collect the import/export lists for all modules from the call-graph in the
885 // combined index.
886 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
887 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000888 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
889 ExportLists);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000890
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000891 // Convert the preserved symbols set from string to GUID, this is needed for
Mehdi Amini059464f2016-04-24 03:18:01 +0000892 // computing the caching hash and the internalization.
893 auto GUIDPreservedSymbols =
894 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000895
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000896 // Make sure that every module has an entry in the ExportLists to enable
897 // threaded access to this map below
898 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries)
899 ExportLists[DefinedGVSummaries.first()];
900
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000901 // Parallel optimizer + codegen
902 {
903 ThreadPool Pool(ThreadCount);
904 int count = 0;
905 for (auto &ModuleBuffer : Modules) {
906 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000907 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000908 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000909
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000910 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
911
912 // Resolve ODR, this has to be done early because it impacts the caching
913 // We use a std::map here to be able to have a defined ordering when
914 // producing a hash for the cache entry.
915 std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> ResolvedODR;
Mehdi Aminiaa309b12016-04-26 10:35:01 +0000916 ResolveODR(*Index, ExportList, GUIDPreservedSymbols, DefinedFunctions, ModuleIdentifier,
Mehdi Amini059464f2016-04-24 03:18:01 +0000917 ResolvedODR);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000918
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000919 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000920 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
921 ImportLists[ModuleIdentifier], ExportList,
922 ResolvedODR, DefinedFunctions,
923 GUIDPreservedSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000924
925 {
926 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000927 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
928 << CacheEntry.getEntryPath() << "' for buffer " << count
929 << " " << ModuleIdentifier << "\n");
930
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000931 if (ErrOrBuffer) {
932 // Cache Hit!
933 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
934 return;
935 }
936 }
937
938 LLVMContext Context;
939 Context.setDiscardValueNames(LTODiscardValueNames);
940 Context.enableDebugTypeODRUniquing();
941
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000942 // Parse module now
943 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
944
945 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000946 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000947
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000948 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000949 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000950 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +0000951 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Mehdi Amini059464f2016-04-24 03:18:01 +0000952 ExportList, GUIDPreservedSymbols, ResolvedODR, CacheOptions,
953 DisableCodeGen, SaveTempsDir, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000954
Mehdi Amini001bb412016-05-16 19:11:59 +0000955 OutputBuffer = CacheEntry.write(std::move(OutputBuffer));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000956 ProducedBinaries[count] = std::move(OutputBuffer);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000957 }, count);
958 count++;
959 }
960 }
961
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000962 CachePruning(CacheOptions.Path)
963 .setPruningInterval(CacheOptions.PruningInterval)
964 .setEntryExpiration(CacheOptions.Expiration)
965 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
966 .prune();
967
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000968 // If statistics were requested, print them out now.
969 if (llvm::AreStatisticsEnabled())
970 llvm::PrintStatistics();
971}