blob: bfcff4c9cfef97e101be4546e3428554b20b10d5 [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"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000035#include "llvm/LTO/LTO.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000036#include "llvm/Linker/Linker.h"
37#include "llvm/MC/SubtargetFeature.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000038#include "llvm/Object/IRObjectFile.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000039#include "llvm/Object/ModuleSummaryIndexObjectFile.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/TargetRegistry.h"
45#include "llvm/Support/ThreadPool.h"
46#include "llvm/Target/TargetMachine.h"
47#include "llvm/Transforms/IPO.h"
48#include "llvm/Transforms/IPO/FunctionImport.h"
Mehdi Amini059464f2016-04-24 03:18:01 +000049#include "llvm/Transforms/IPO/Internalize.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000050#include "llvm/Transforms/IPO/PassManagerBuilder.h"
51#include "llvm/Transforms/ObjCARC.h"
52#include "llvm/Transforms/Utils/FunctionImportUtils.h"
53
Mehdi Amini819e9cd2016-05-16 19:33:07 +000054#include <numeric>
55
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000056using namespace llvm;
57
Mehdi Amini1aafabf2016-04-16 07:02:16 +000058#define DEBUG_TYPE "thinlto"
59
Mehdi Amini09b4a8d2016-03-10 01:28:54 +000060namespace llvm {
61// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
62extern cl::opt<bool> LTODiscardValueNames;
63}
64
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000065namespace {
66
67static cl::opt<int> ThreadCount("threads",
68 cl::init(std::thread::hardware_concurrency()));
69
70static void diagnosticHandler(const DiagnosticInfo &DI) {
71 DiagnosticPrinterRawOStream DP(errs());
72 DI.print(DP);
73 errs() << '\n';
74}
75
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000076// Simple helper to save temporary files for debug.
77static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
78 unsigned count, StringRef Suffix) {
79 if (TempDir.empty())
80 return;
81 // User asked to save temps, let dump the bitcode file after import.
82 auto SaveTempPath = TempDir + llvm::utostr(count) + Suffix;
83 std::error_code EC;
84 raw_fd_ostream OS(SaveTempPath.str(), EC, sys::fs::F_None);
85 if (EC)
86 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
87 " to save optimized bitcode\n");
Teresa Johnson3c35e092016-04-04 21:19:31 +000088 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000089}
90
Teresa Johnson4d2613f2016-05-24 17:24:25 +000091static const GlobalValueSummary *
92getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
93 // If there is any strong definition anywhere, get it.
94 auto StrongDefForLinker = llvm::find_if(
95 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
96 auto Linkage = Summary->linkage();
97 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
98 !GlobalValue::isWeakForLinker(Linkage);
99 });
100 if (StrongDefForLinker != GVSummaryList.end())
101 return StrongDefForLinker->get();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000102 // Get the first *linker visible* definition for this global in the summary
103 // list.
104 auto FirstDefForLinker = llvm::find_if(
Teresa Johnson28e457b2016-04-24 14:57:11 +0000105 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
106 auto Linkage = Summary->linkage();
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000107 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
108 });
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000109 // Extern templates can be emitted as available_externally.
110 if (FirstDefForLinker == GVSummaryList.end())
111 return nullptr;
112 return FirstDefForLinker->get();
Hans Wennborgfa6e4142016-04-02 01:03:41 +0000113}
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000114
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000115// Populate map of GUID to the prevailing copy for any multiply defined
116// symbols. Currently assume first copy is prevailing, or any strong
117// definition. Can be refined with Linker information in the future.
118static void computePrevailingCopies(
119 const ModuleSummaryIndex &Index,
120 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
Teresa Johnson28e457b2016-04-24 14:57:11 +0000121 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
122 return GVSummaryList.size() > 1;
123 };
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000124
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000125 for (auto &I : Index) {
126 if (HasMultipleCopies(I.second))
127 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000128 }
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000129}
130
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000131static void thinLTOResolveWeakForLinkerGUID(
132 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
133 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
134 std::function<bool(GlobalValue::GUID, const GlobalValueSummary *)>
135 isPrevailing,
136 std::function<bool(StringRef, GlobalValue::GUID)> isExported,
137 std::function<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
138 recordNewLinkage) {
139 auto HasMultipleCopies = GVSummaryList.size() > 1;
140
141 for (auto &S : GVSummaryList) {
142 if (GlobalInvolvedWithAlias.count(S.get()))
143 continue;
144 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
145 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
146 continue;
147 // We need to emit only one of these, the first module will keep it,
148 // but turned into a weak, while the others will drop it when possible.
149 if (!HasMultipleCopies) {
150 // Exported Linkonce needs to be promoted to not be discarded.
151 // FIXME: This should handle LinkOnceAny as well, but that should be a
152 // follow-on to the NFC restructuring:
153 // if (GlobalValue::isLinkOnceLinkage(OriginalLinkage) &&
154 // isExported(S->modulePath(), GUID))
155 // S->setLinkage(GlobalValue::getWeakLinkage(
156 // GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
157 if (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage) &&
158 isExported(S->modulePath(), GUID))
159 S->setLinkage(GlobalValue::WeakODRLinkage);
160 } else if (isPrevailing(GUID, S.get())) {
161 // FIXME: This should handle LinkOnceAny as well, but that should be a
162 // follow-on to the NFC restructuring:
163 // if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
164 // S->setLinkage(GlobalValue::getWeakLinkage(
165 // GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
166 if (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage))
167 S->setLinkage(GlobalValue::WeakODRLinkage);
168 }
169 // Alias can't be turned into available_externally.
170 else if (!isa<AliasSummary>(S.get()) &&
171 (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage) ||
172 GlobalValue::isWeakODRLinkage(OriginalLinkage)))
173 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
174 if (S->linkage() != OriginalLinkage)
175 recordNewLinkage(S->modulePath(), GUID, S->linkage());
176 }
177}
178
179// Resolve Weak and LinkOnce values in the \p Index.
180//
181// We'd like to drop these functions if they are no longer referenced in the
182// current module. However there is a chance that another module is still
183// referencing them because of the import. We make sure we always emit at least
184// one copy.
185void thinLTOResolveWeakForLinkerInIndex(
186 ModuleSummaryIndex &Index,
187 std::function<bool(GlobalValue::GUID, const GlobalValueSummary *)>
188 isPrevailing,
189 std::function<bool(StringRef, GlobalValue::GUID)> isExported,
190 std::function<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
191 recordNewLinkage) {
Mehdi Amini8dcc8082016-04-14 08:46:22 +0000192 if (Index.modulePaths().size() == 1)
193 // Nothing to do if we don't have multiple modules
194 return;
195
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000196 // We won't optimize the globals that are referenced by an alias for now
197 // Ideally we should turn the alias into a global and duplicate the definition
198 // when needed.
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000199 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000200 for (auto &I : Index)
201 for (auto &S : I.second)
202 if (auto AS = dyn_cast<AliasSummary>(S.get()))
203 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000204
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000205 for (auto &I : Index)
206 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
207 isPrevailing, isExported, recordNewLinkage);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000208}
209
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000210/// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
211void thinLTOResolveWeakForLinkerModule(Module &TheModule,
212 const GVSummaryMapTy &DefinedGlobals) {
213 auto updateLinkage = [&](GlobalValue &GV) {
214 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
215 return;
216 // See if the global summary analysis computed a new resolved linkage.
217 const auto &GS = DefinedGlobals.find(GV.getGUID());
218 if (GS == DefinedGlobals.end())
219 return;
220 auto NewLinkage = GS->second->linkage();
221 if (NewLinkage == GV.getLinkage())
222 return;
223 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
224 << GV.getLinkage() << " to " << NewLinkage << "\n");
225 GV.setLinkage(NewLinkage);
226 };
227
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000228 // Process functions and global now
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000229 for (auto &GV : TheModule)
230 updateLinkage(GV);
231 for (auto &GV : TheModule.globals())
232 updateLinkage(GV);
233 for (auto &GV : TheModule.aliases())
234 updateLinkage(GV);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000235}
236
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000237static StringMap<MemoryBufferRef>
238generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
239 StringMap<MemoryBufferRef> ModuleMap;
240 for (auto &ModuleBuffer : Modules) {
241 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
242 ModuleMap.end() &&
243 "Expect unique Buffer Identifier");
244 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
245 }
246 return ModuleMap;
247}
248
Teresa Johnson26ab5772016-03-15 00:04:37 +0000249static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000250 if (renameModuleForThinLTO(TheModule, Index))
251 report_fatal_error("renameModuleForThinLTO failed");
252}
253
Mehdi Amini01e32132016-03-26 05:40:34 +0000254static void
255crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
256 StringMap<MemoryBufferRef> &ModuleMap,
257 const FunctionImporter::ImportMapTy &ImportList) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000258 ModuleLoader Loader(TheModule.getContext(), ModuleMap);
259 FunctionImporter Importer(Index, Loader);
Mehdi Amini01e32132016-03-26 05:40:34 +0000260 Importer.importFunctions(TheModule, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000261}
262
263static void optimizeModule(Module &TheModule, TargetMachine &TM) {
264 // Populate the PassManager
265 PassManagerBuilder PMB;
266 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
267 PMB.Inliner = createFunctionInliningPass();
268 // FIXME: should get it from the bitcode?
269 PMB.OptLevel = 3;
270 PMB.LoopVectorize = true;
271 PMB.SLPVectorize = true;
272 PMB.VerifyInput = true;
273 PMB.VerifyOutput = false;
274
275 legacy::PassManager PM;
276
277 // Add the TTI (required to inform the vectorizer about register size for
278 // instance)
279 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
280
281 // Add optimizations
282 PMB.populateThinLTOPassManager(PM);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000283
284 PM.run(TheModule);
285}
286
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000287static void thinLTOInternalizeAndPromoteGUID(
288 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
289 std::function<bool(StringRef, GlobalValue::GUID)> isExported) {
290 for (auto &S : GVSummaryList) {
291 if (isExported(S->modulePath(), GUID)) {
292 if (GlobalValue::isLocalLinkage(S->linkage()))
293 S->setLinkage(GlobalValue::ExternalLinkage);
294 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
295 S->setLinkage(GlobalValue::InternalLinkage);
296 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000297}
298
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000299// Update the linkages in the given \p Index to mark exported values
300// as external and non-exported values as internal.
301void thinLTOInternalizeAndPromoteInIndex(
302 ModuleSummaryIndex &Index,
303 std::function<bool(StringRef, GlobalValue::GUID)> isExported) {
304 for (auto &I : Index)
305 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
306}
Mehdi Amini059464f2016-04-24 03:18:01 +0000307
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000308// Run internalization on \p TheModule based on symmary analysis.
309void thinLTOInternalizeModule(Module &TheModule,
310 const GVSummaryMapTy &DefinedGlobals) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000311 // Parse inline ASM and collect the list of symbols that are not defined in
312 // the current module.
313 StringSet<> AsmUndefinedRefs;
314 object::IRObjectFile::CollectAsmUndefinedRefs(
315 Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
316 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
317 if (Flags & object::BasicSymbolRef::SF_Undefined)
318 AsmUndefinedRefs.insert(Name);
319 });
320
Mehdi Amini059464f2016-04-24 03:18:01 +0000321 // Declare a callback for the internalize pass that will ask for every
322 // candidate GlobalValue if it can be internalized or not.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000323 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
324 // Can't be internalized if referenced in inline asm.
325 if (AsmUndefinedRefs.count(GV.getName()))
326 return true;
Mehdi Amini059464f2016-04-24 03:18:01 +0000327
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000328 // Lookup the linkage recorded in the summaries during global analysis.
329 const auto &GS = DefinedGlobals.find(GV.getGUID());
330 GlobalValue::LinkageTypes Linkage;
331 if (GS == DefinedGlobals.end()) {
332 // Must have been promoted (possibly conservatively). Find original
333 // name so that we can access the correct summary and see if it can
334 // be internalized again.
335 // FIXME: Eventually we should control promotion instead of promoting
336 // and internalizing again.
337 StringRef OrigName =
338 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
339 std::string OrigId = GlobalValue::getGlobalIdentifier(
340 OrigName, GlobalValue::InternalLinkage,
341 TheModule.getSourceFileName());
342 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
343 assert(GS != DefinedGlobals.end());
344 Linkage = GS->second->linkage();
345 } else
346 Linkage = GS->second->linkage();
347 return !GlobalValue::isLocalLinkage(Linkage);
348 };
349
350 // FIXME: See if we can just internalize directly here via linkage changes
351 // based on the index, rather than invoking internalizeModule.
Mehdi Amini059464f2016-04-24 03:18:01 +0000352 llvm::internalizeModule(TheModule, MustPreserveGV);
353}
354
355// Convert the PreservedSymbols map from "Name" based to "GUID" based.
356static DenseSet<GlobalValue::GUID>
357computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
358 const Triple &TheTriple) {
359 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
360 for (auto &Entry : PreservedSymbols) {
361 StringRef Name = Entry.first();
362 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
363 Name = Name.drop_front();
364 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
365 }
366 return GUIDPreservedSymbols;
367}
368
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000369std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
370 TargetMachine &TM) {
371 SmallVector<char, 128> OutputBuffer;
372
373 // CodeGen
374 {
375 raw_svector_ostream OS(OutputBuffer);
376 legacy::PassManager PM;
Mehdi Amini215d59e2016-04-01 08:22:59 +0000377
378 // If the bitcode files contain ARC code and were compiled with optimization,
379 // the ObjCARCContractPass must be run, so do it unconditionally here.
380 PM.add(createObjCARCContractPass());
381
382 // Setup the codegen now.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000383 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
384 /* DisableVerify */ true))
385 report_fatal_error("Failed to setup codegen");
386
387 // Run codegen now. resulting binary is in OutputBuffer.
388 PM.run(TheModule);
389 }
390 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
391}
392
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000393/// Manage caching for a single Module.
394class ModuleCacheEntry {
395 SmallString<128> EntryPath;
396
397public:
398 // Create a cache entry. This compute a unique hash for the Module considering
399 // the current list of export/import, and offer an interface to query to
400 // access the content in the cache.
401 ModuleCacheEntry(
402 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
403 const FunctionImporter::ImportMapTy &ImportList,
404 const FunctionImporter::ExportSetTy &ExportList,
405 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Teresa Johnsonc851d212016-04-25 21:09:51 +0000406 const GVSummaryMapTy &DefinedFunctions,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000407 const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
408 if (CachePath.empty())
409 return;
410
411 // Compute the unique hash for this entry
412 // This is based on the current compiler version, the module itself, the
413 // export list, the hash for every single module in the import list, the
414 // list of ResolvedODR for the module, and the list of preserved symbols.
415
416 SHA1 Hasher;
417
418 // Start with the compiler revision
419 Hasher.update(LLVM_VERSION_STRING);
420#ifdef HAVE_LLVM_REVISION
421 Hasher.update(LLVM_REVISION);
422#endif
423
424 // Include the hash for the current module
425 auto ModHash = Index.getModuleHash(ModuleID);
426 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
427 for (auto F : ExportList)
428 // The export list can impact the internalization, be conservative here
429 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
430
431 // Include the hash for every module we import functions from
432 for (auto &Entry : ImportList) {
433 auto ModHash = Index.getModuleHash(Entry.first());
434 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
435 }
436
437 // Include the hash for the resolved ODR.
438 for (auto &Entry : ResolvedODR) {
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000439 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000440 sizeof(GlobalValue::GUID)));
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000441 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000442 sizeof(GlobalValue::LinkageTypes)));
443 }
444
445 // Include the hash for the preserved symbols.
446 for (auto &Entry : PreservedSymbols) {
447 if (DefinedFunctions.count(Entry))
448 Hasher.update(
Sjoerd Meijer41beee62016-04-27 18:35:02 +0000449 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000450 }
451
452 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
453 }
454
Mehdi Amini059464f2016-04-24 03:18:01 +0000455 // Access the path to this entry in the cache.
456 StringRef getEntryPath() { return EntryPath; }
457
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000458 // Try loading the buffer for this cache entry.
459 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
460 if (EntryPath.empty())
461 return std::error_code();
462 return MemoryBuffer::getFile(EntryPath);
463 }
464
465 // Cache the Produced object file
Mehdi Amini001bb412016-05-16 19:11:59 +0000466 std::unique_ptr<MemoryBuffer>
467 write(std::unique_ptr<MemoryBuffer> OutputBuffer) {
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000468 if (EntryPath.empty())
Mehdi Amini001bb412016-05-16 19:11:59 +0000469 return OutputBuffer;
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000470
471 // Write to a temporary to avoid race condition
472 SmallString<128> TempFilename;
473 int TempFD;
474 std::error_code EC =
475 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
476 if (EC) {
477 errs() << "Error: " << EC.message() << "\n";
478 report_fatal_error("ThinLTO: Can't get a temporary file");
479 }
480 {
481 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
Mehdi Amini001bb412016-05-16 19:11:59 +0000482 OS << OutputBuffer->getBuffer();
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000483 }
484 // Rename to final destination (hopefully race condition won't matter here)
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000485 EC = sys::fs::rename(TempFilename, EntryPath);
486 if (EC) {
Mehdi Aminib02139d2016-05-14 05:16:35 +0000487 sys::fs::remove(TempFilename);
488 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
489 if (EC)
490 report_fatal_error(Twine("Failed to open ") + EntryPath +
491 " to save cached entry\n");
Mehdi Amini001bb412016-05-16 19:11:59 +0000492 OS << OutputBuffer->getBuffer();
Mehdi Amini2a16a5f2016-05-14 04:58:38 +0000493 }
Mehdi Amini001bb412016-05-16 19:11:59 +0000494 auto ReloadedBufferOrErr = MemoryBuffer::getFile(EntryPath);
495 if (auto EC = ReloadedBufferOrErr.getError()) {
496 // FIXME diagnose
497 errs() << "error: can't reload cached file '" << EntryPath
498 << "': " << EC.message() << "\n";
499 return OutputBuffer;
500 }
501 return std::move(*ReloadedBufferOrErr);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000502 }
503};
504
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000505static std::unique_ptr<MemoryBuffer>
506ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
507 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
508 const FunctionImporter::ImportMapTy &ImportList,
509 const FunctionImporter::ExportSetTy &ExportList,
510 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
511 const GVSummaryMapTy &DefinedGlobals,
512 ThinLTOCodeGenerator::CachingOptions CacheOptions,
513 bool DisableCodeGen, StringRef SaveTempsDir,
514 unsigned count) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000515
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000516 // "Benchmark"-like optimization: single-source case
517 bool SingleModule = (ModuleMap.size() == 1);
518
519 if (!SingleModule) {
520 promoteModule(TheModule, Index);
521
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000522 // Apply summary-based LinkOnce/Weak resolution decisions.
523 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000524
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000525 // Save temps: after promotion.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000526 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000527 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000528
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000529 // Be friendly and don't nuke totally the module when the client didn't
530 // supply anything to preserve.
531 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
532 // Apply summary-based internalization decisions.
533 thinLTOInternalizeModule(TheModule, DefinedGlobals);
534 }
Mehdi Amini059464f2016-04-24 03:18:01 +0000535
536 // Save internalized bitcode
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000537 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
Mehdi Amini059464f2016-04-24 03:18:01 +0000538
539 if (!SingleModule) {
Mehdi Amini01e32132016-03-26 05:40:34 +0000540 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000541
542 // Save temps: after cross-module import.
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000543 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000544 }
545
546 optimizeModule(TheModule, TM);
547
Mehdi Amini4b300e0a2016-05-05 05:14:16 +0000548 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000549
Mehdi Amini43b657b2016-04-01 06:47:02 +0000550 if (DisableCodeGen) {
551 // Configured to stop before CodeGen, serialize the bitcode and return.
552 SmallVector<char, 128> OutputBuffer;
553 {
554 raw_svector_ostream OS(OutputBuffer);
Teresa Johnson2d5487c2016-04-11 13:58:45 +0000555 ModuleSummaryIndexBuilder IndexBuilder(&TheModule);
556 WriteBitcodeToFile(&TheModule, OS, true, &IndexBuilder.getIndex());
Mehdi Amini43b657b2016-04-01 06:47:02 +0000557 }
558 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
559 }
560
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000561 return codegenModule(TheModule, TM);
562}
563
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000564/// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
565/// for caching, and in the \p Index for application during the ThinLTO
566/// backends. This is needed for correctness for exported symbols (ensure
567/// at least one copy kept) and a compile-time optimization (to drop duplicate
568/// copies when possible).
569static void resolveWeakForLinkerInIndex(
570 ModuleSummaryIndex &Index,
571 const StringMap<FunctionImporter::ExportSetTy> &ExportLists,
572 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
573 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
574 &ResolvedODR) {
575
576 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
577 computePrevailingCopies(Index, PrevailingCopy);
578
579 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
580 const auto &Prevailing = PrevailingCopy.find(GUID);
581 // Not in map means that there was only one copy, which must be prevailing.
582 if (Prevailing == PrevailingCopy.end())
583 return true;
584 return Prevailing->second == S;
585 };
586
587 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
588 const auto &ExportList = ExportLists.find(ModuleIdentifier);
589 assert(ExportList != ExportLists.end() && "Missing export list for module");
590 return ExportList->second.count(GUID) || GUIDPreservedSymbols.count(GUID);
591 };
592
593 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
594 GlobalValue::GUID GUID,
595 GlobalValue::LinkageTypes NewLinkage) {
596 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
597 };
598
599 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, isExported,
600 recordNewLinkage);
601}
602
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000603// Initialize the TargetMachine builder for a given Triple
604static void initTMBuilder(TargetMachineBuilder &TMBuilder,
605 const Triple &TheTriple) {
606 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
607 // FIXME this looks pretty terrible...
608 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
609 if (TheTriple.getArch() == llvm::Triple::x86_64)
610 TMBuilder.MCpu = "core2";
611 else if (TheTriple.getArch() == llvm::Triple::x86)
612 TMBuilder.MCpu = "yonah";
613 else if (TheTriple.getArch() == llvm::Triple::aarch64)
614 TMBuilder.MCpu = "cyclone";
615 }
616 TMBuilder.TheTriple = std::move(TheTriple);
617}
618
619} // end anonymous namespace
620
621void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
622 MemoryBufferRef Buffer(Data, Identifier);
623 if (Modules.empty()) {
624 // First module added, so initialize the triple and some options
625 LLVMContext Context;
626 Triple TheTriple(getBitcodeTargetTriple(Buffer, Context));
627 initTMBuilder(TMBuilder, Triple(TheTriple));
628 }
629#ifndef NDEBUG
630 else {
631 LLVMContext Context;
632 assert(TMBuilder.TheTriple.str() ==
633 getBitcodeTargetTriple(Buffer, Context) &&
634 "ThinLTO modules with different triple not supported");
635 }
636#endif
637 Modules.push_back(Buffer);
638}
639
640void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
641 PreservedSymbols.insert(Name);
642}
643
644void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
Mehdi Amini059464f2016-04-24 03:18:01 +0000645 // FIXME: At the moment, we don't take advantage of this extra information,
646 // we're conservatively considering cross-references as preserved.
647 // CrossReferencedSymbols.insert(Name);
648 PreservedSymbols.insert(Name);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000649}
650
651// TargetMachine factory
652std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
653 std::string ErrMsg;
654 const Target *TheTarget =
655 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
656 if (!TheTarget) {
657 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
658 }
659
660 // Use MAttr as the default set of features.
661 SubtargetFeatures Features(MAttr);
662 Features.getDefaultSubtargetFeatures(TheTriple);
663 std::string FeatureStr = Features.getString();
664 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
665 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
666 CodeModel::Default, CGOptLevel));
667}
668
669/**
Teresa Johnson26ab5772016-03-15 00:04:37 +0000670 * Produce the combined summary index from all the bitcode files:
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000671 * "thin-link".
672 */
Teresa Johnson26ab5772016-03-15 00:04:37 +0000673std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
674 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000675 uint64_t NextModuleId = 0;
676 for (auto &ModuleBuffer : Modules) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000677 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
678 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer,
Teresa Johnson6fb3f192016-04-22 01:52:00 +0000679 diagnosticHandler);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000680 if (std::error_code EC = ObjOrErr.getError()) {
681 // FIXME diagnose
Teresa Johnson26ab5772016-03-15 00:04:37 +0000682 errs() << "error: can't create ModuleSummaryIndexObjectFile for buffer: "
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000683 << EC.message() << "\n";
684 return nullptr;
685 }
686 auto Index = (*ObjOrErr)->takeIndex();
687 if (CombinedIndex) {
688 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
689 } else {
690 CombinedIndex = std::move(Index);
691 }
692 }
693 return CombinedIndex;
694}
695
696/**
697 * Perform promotion and renaming of exported internal functions.
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000698 * Index is updated to reflect linkage changes from weak resolution.
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000699 */
700void ThinLTOCodeGenerator::promote(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000701 ModuleSummaryIndex &Index) {
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000702 auto ModuleCount = Index.modulePaths().size();
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000703 auto ModuleIdentifier = TheModule.getModuleIdentifier();
704 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000705 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000706 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000707
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000708 // Generate import/export list
709 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
710 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
711 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
712 ExportLists);
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000713
Mehdi Aminiaa309b12016-04-26 10:35:01 +0000714 // Convert the preserved symbols set from string to GUID
715 auto GUIDPreservedSymbols =
716 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
717
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000718 // Resolve LinkOnce/Weak symbols.
719 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
720 resolveWeakForLinkerInIndex(Index, ExportLists, GUIDPreservedSymbols,
721 ResolvedODR);
722
723 thinLTOResolveWeakForLinkerModule(
724 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini5a2e5d32016-04-01 21:53:50 +0000725
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000726 promoteModule(TheModule, Index);
727}
728
729/**
730 * Perform cross-module importing for the module identified by ModuleIdentifier.
731 */
732void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000733 ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000734 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000735 auto ModuleCount = Index.modulePaths().size();
736
737 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000738 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000739 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
Mehdi Amini01e32132016-03-26 05:40:34 +0000740
741 // Generate import/export list
Mehdi Amini01e32132016-03-26 05:40:34 +0000742 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
743 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000744 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
745 ExportLists);
Mehdi Amini01e32132016-03-26 05:40:34 +0000746 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
747
748 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000749}
750
751/**
Teresa Johnson84174c32016-05-10 13:48:23 +0000752 * Compute the list of summaries needed for importing into module.
753 */
754void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
755 StringRef ModulePath, ModuleSummaryIndex &Index,
756 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
757 auto ModuleCount = Index.modulePaths().size();
758
759 // Collect for each module the list of function it defines (GUID -> Summary).
760 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
761 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
762
763 // Generate import/export list
764 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
765 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
766 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
767 ExportLists);
768
769 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
770 ImportLists,
771 ModuleToSummariesForIndex);
772}
773
774/**
Teresa Johnson8570fe42016-05-10 15:54:09 +0000775 * Emit the list of files needed for importing into module.
776 */
777void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
778 StringRef OutputName,
779 ModuleSummaryIndex &Index) {
780 auto ModuleCount = Index.modulePaths().size();
781
782 // Collect for each module the list of function it defines (GUID -> Summary).
783 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
784 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
785
786 // Generate import/export list
787 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
788 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
789 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
790 ExportLists);
791
792 std::error_code EC;
793 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists)))
794 report_fatal_error(Twine("Failed to open ") + OutputName +
795 " to save imports lists\n");
796}
797
798/**
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000799 * Perform internalization. Index is updated to reflect linkage changes.
Mehdi Amini059464f2016-04-24 03:18:01 +0000800 */
801void ThinLTOCodeGenerator::internalize(Module &TheModule,
802 ModuleSummaryIndex &Index) {
803 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
804 auto ModuleCount = Index.modulePaths().size();
805 auto ModuleIdentifier = TheModule.getModuleIdentifier();
806
807 // Convert the preserved symbols set from string to GUID
808 auto GUIDPreservedSymbols =
809 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
810
811 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000812 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini059464f2016-04-24 03:18:01 +0000813 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
814
815 // Generate import/export list
816 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
817 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
818 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
819 ExportLists);
820 auto &ExportList = ExportLists[ModuleIdentifier];
821
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000822 // Be friendly and don't nuke totally the module when the client didn't
823 // supply anything to preserve.
824 if (ExportList.empty() && GUIDPreservedSymbols.empty())
825 return;
826
Mehdi Amini059464f2016-04-24 03:18:01 +0000827 // Internalization
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000828 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
829 const auto &ExportList = ExportLists.find(ModuleIdentifier);
830 assert(ExportList != ExportLists.end() && "Missing export list for module");
831 return ExportList->second.count(GUID) || GUIDPreservedSymbols.count(GUID);
832 };
833 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
834 thinLTOInternalizeModule(TheModule,
835 ModuleToDefinedGVSummaries[ModuleIdentifier]);
Mehdi Amini059464f2016-04-24 03:18:01 +0000836}
837
838/**
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000839 * Perform post-importing ThinLTO optimizations.
840 */
841void ThinLTOCodeGenerator::optimize(Module &TheModule) {
842 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
Mehdi Amini059464f2016-04-24 03:18:01 +0000843
844 // Optimize now
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000845 optimizeModule(TheModule, *TMBuilder.create());
846}
847
848/**
849 * Perform ThinLTO CodeGen.
850 */
851std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
852 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
853 return codegenModule(TheModule, *TMBuilder.create());
854}
855
856// Main entry point for the ThinLTO processing
857void ThinLTOCodeGenerator::run() {
Mehdi Amini43b657b2016-04-01 06:47:02 +0000858 if (CodeGenOnly) {
859 // Perform only parallel codegen and return.
860 ThreadPool Pool;
861 assert(ProducedBinaries.empty() && "The generator should not be reused");
862 ProducedBinaries.resize(Modules.size());
863 int count = 0;
864 for (auto &ModuleBuffer : Modules) {
865 Pool.async([&](int count) {
866 LLVMContext Context;
867 Context.setDiscardValueNames(LTODiscardValueNames);
868
869 // Parse module now
870 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
871
872 // CodeGen
873 ProducedBinaries[count] = codegen(*TheModule);
874 }, count++);
875 }
876
877 return;
878 }
879
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000880 // Sequential linking phase
881 auto Index = linkCombinedIndex();
882
883 // Save temps: index.
884 if (!SaveTempsDir.empty()) {
885 auto SaveTempPath = SaveTempsDir + "index.bc";
886 std::error_code EC;
887 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
888 if (EC)
889 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
890 " to save optimized bitcode\n");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000891 WriteIndexToFile(*Index, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000892 }
893
894 // Prepare the resulting object vector
895 assert(ProducedBinaries.empty() && "The generator should not be reused");
896 ProducedBinaries.resize(Modules.size());
897
898 // Prepare the module map.
899 auto ModuleMap = generateModuleMap(Modules);
Mehdi Amini01e32132016-03-26 05:40:34 +0000900 auto ModuleCount = Modules.size();
901
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000902 // Collect for each module the list of function it defines (GUID -> Summary).
Teresa Johnsonc851d212016-04-25 21:09:51 +0000903 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000904 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
905
Mehdi Amini01e32132016-03-26 05:40:34 +0000906 // Collect the import/export lists for all modules from the call-graph in the
907 // combined index.
908 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
909 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000910 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
911 ExportLists);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000912
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000913 // Convert the preserved symbols set from string to GUID, this is needed for
Mehdi Amini059464f2016-04-24 03:18:01 +0000914 // computing the caching hash and the internalization.
915 auto GUIDPreservedSymbols =
916 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000917
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000918 // We use a std::map here to be able to have a defined ordering when
919 // producing a hash for the cache entry.
920 // FIXME: we should be able to compute the caching hash for the entry based
921 // on the index, and nuke this map.
922 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
923
924 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
925 // impacts the caching.
926 resolveWeakForLinkerInIndex(*Index, ExportLists, GUIDPreservedSymbols,
927 ResolvedODR);
928
929 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
930 const auto &ExportList = ExportLists.find(ModuleIdentifier);
931 assert(ExportList != ExportLists.end() && "Missing export list for module");
932 return ExportList->second.count(GUID) || GUIDPreservedSymbols.count(GUID);
933 };
934
935 // Use global summary-based analysis to identify symbols that can be
936 // internalized (because they aren't exported or preserved as per callback).
937 // Changes are made in the index, consumed in the ThinLTO backends.
938 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
939
Mehdi Aminiaf52f282016-05-15 05:49:47 +0000940 // Make sure that every module has an entry in the ExportLists to enable
941 // threaded access to this map below
942 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries)
943 ExportLists[DefinedGVSummaries.first()];
944
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000945 // Compute the ordering we will process the inputs: the rough heuristic here
946 // is to sort them per size so that the largest module get schedule as soon as
947 // possible. This is purely a compile-time optimization.
948 std::vector<int> ModulesOrdering;
949 ModulesOrdering.resize(Modules.size());
950 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
951 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
952 [&](int LeftIndex, int RightIndex) {
953 auto LSize = Modules[LeftIndex].getBufferSize();
954 auto RSize = Modules[RightIndex].getBufferSize();
955 return LSize > RSize;
956 });
957
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000958 // Parallel optimizer + codegen
959 {
960 ThreadPool Pool(ThreadCount);
Mehdi Amini819e9cd2016-05-16 19:33:07 +0000961 for (auto IndexCount : ModulesOrdering) {
962 auto &ModuleBuffer = Modules[IndexCount];
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000963 Pool.async([&](int count) {
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000964 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
Mehdi Aminia71a5a62016-04-21 05:47:17 +0000965 auto &ExportList = ExportLists[ModuleIdentifier];
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000966
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000967 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
968
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000969 // The module may be cached, this helps handling it.
Mehdi Amini059464f2016-04-24 03:18:01 +0000970 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
971 ImportLists[ModuleIdentifier], ExportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +0000972 ResolvedODR[ModuleIdentifier],
973 DefinedFunctions, GUIDPreservedSymbols);
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000974
975 {
976 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
Mehdi Amini059464f2016-04-24 03:18:01 +0000977 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
978 << CacheEntry.getEntryPath() << "' for buffer " << count
979 << " " << ModuleIdentifier << "\n");
980
Mehdi Aminif95f77a2016-04-21 05:54:23 +0000981 if (ErrOrBuffer) {
982 // Cache Hit!
983 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
984 return;
985 }
986 }
987
988 LLVMContext Context;
989 Context.setDiscardValueNames(LTODiscardValueNames);
990 Context.enableDebugTypeODRUniquing();
991
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000992 // Parse module now
993 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
994
995 // Save temps: original file.
Mehdi Amini059464f2016-04-24 03:18:01 +0000996 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000997
Mehdi Amini1aafabf2016-04-16 07:02:16 +0000998 auto &ImportList = ImportLists[ModuleIdentifier];
Mehdi Amini059464f2016-04-24 03:18:01 +0000999 // Run the main process now, and generates a binary
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001000 auto OutputBuffer = ProcessThinLTOModule(
Mehdi Amini01e32132016-03-26 05:40:34 +00001001 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
Teresa Johnson4d2613f2016-05-24 17:24:25 +00001002 ExportList, GUIDPreservedSymbols,
1003 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
Mehdi Amini059464f2016-04-24 03:18:01 +00001004 DisableCodeGen, SaveTempsDir, count);
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001005
Mehdi Amini001bb412016-05-16 19:11:59 +00001006 OutputBuffer = CacheEntry.write(std::move(OutputBuffer));
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001007 ProducedBinaries[count] = std::move(OutputBuffer);
Mehdi Amini819e9cd2016-05-16 19:33:07 +00001008 }, IndexCount);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001009 }
1010 }
1011
Mehdi Aminif95f77a2016-04-21 05:54:23 +00001012 CachePruning(CacheOptions.Path)
1013 .setPruningInterval(CacheOptions.PruningInterval)
1014 .setEntryExpiration(CacheOptions.Expiration)
1015 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
1016 .prune();
1017
Mehdi Amini7c4a1a82016-03-09 01:37:22 +00001018 // If statistics were requested, print them out now.
1019 if (llvm::AreStatisticsEnabled())
1020 llvm::PrintStatistics();
1021}