1 //===-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/legacy/ThinLTOCodeGenerator.h"
16 
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
20 #include "llvm/Analysis/ProfileSummaryInfo.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/Bitcode/BitcodeReader.h"
24 #include "llvm/Bitcode/BitcodeWriter.h"
25 #include "llvm/Bitcode/BitcodeWriterPass.h"
26 #include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/DiagnosticPrinter.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/LegacyPassManager.h"
31 #include "llvm/IR/Mangler.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/IRReader/IRReader.h"
34 #include "llvm/LTO/LTO.h"
35 #include "llvm/MC/SubtargetFeature.h"
36 #include "llvm/Object/IRObjectFile.h"
37 #include "llvm/Support/CachePruning.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Error.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/SHA1.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/ThreadPool.h"
44 #include "llvm/Support/Threading.h"
45 #include "llvm/Support/ToolOutputFile.h"
46 #include "llvm/Support/VCSRevision.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Transforms/IPO.h"
49 #include "llvm/Transforms/IPO/FunctionImport.h"
50 #include "llvm/Transforms/IPO/Internalize.h"
51 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
52 #include "llvm/Transforms/ObjCARC.h"
53 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
54 
55 #include <numeric>
56 
57 using namespace llvm;
58 
59 #define DEBUG_TYPE "thinlto"
60 
61 namespace llvm {
62 // Flags -discard-value-names, defined in LTOCodeGenerator.cpp
63 extern cl::opt<bool> LTODiscardValueNames;
64 extern cl::opt<std::string> LTORemarksFilename;
65 extern cl::opt<bool> LTOPassRemarksWithHotness;
66 }
67 
68 namespace {
69 
70 static cl::opt<int>
71     ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
72 
73 // Simple helper to save temporary files for debug.
74 static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
75                             unsigned count, StringRef Suffix) {
76   if (TempDir.empty())
77     return;
78   // User asked to save temps, let dump the bitcode file after import.
79   std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str();
80   std::error_code EC;
81   raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
82   if (EC)
83     report_fatal_error(Twine("Failed to open ") + SaveTempPath +
84                        " to save optimized bitcode\n");
85   WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
86 }
87 
88 static const GlobalValueSummary *
89 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
90   // If there is any strong definition anywhere, get it.
91   auto StrongDefForLinker = llvm::find_if(
92       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
93         auto Linkage = Summary->linkage();
94         return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
95                !GlobalValue::isWeakForLinker(Linkage);
96       });
97   if (StrongDefForLinker != GVSummaryList.end())
98     return StrongDefForLinker->get();
99   // Get the first *linker visible* definition for this global in the summary
100   // list.
101   auto FirstDefForLinker = llvm::find_if(
102       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
103         auto Linkage = Summary->linkage();
104         return !GlobalValue::isAvailableExternallyLinkage(Linkage);
105       });
106   // Extern templates can be emitted as available_externally.
107   if (FirstDefForLinker == GVSummaryList.end())
108     return nullptr;
109   return FirstDefForLinker->get();
110 }
111 
112 // Populate map of GUID to the prevailing copy for any multiply defined
113 // symbols. Currently assume first copy is prevailing, or any strong
114 // definition. Can be refined with Linker information in the future.
115 static void computePrevailingCopies(
116     const ModuleSummaryIndex &Index,
117     DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
118   auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
119     return GVSummaryList.size() > 1;
120   };
121 
122   for (auto &I : Index) {
123     if (HasMultipleCopies(I.second.SummaryList))
124       PrevailingCopy[I.first] =
125           getFirstDefinitionForLinker(I.second.SummaryList);
126   }
127 }
128 
129 static StringMap<MemoryBufferRef>
130 generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) {
131   StringMap<MemoryBufferRef> ModuleMap;
132   for (auto &ModuleBuffer : Modules) {
133     assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
134                ModuleMap.end() &&
135            "Expect unique Buffer Identifier");
136     ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
137   }
138   return ModuleMap;
139 }
140 
141 static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
142   if (renameModuleForThinLTO(TheModule, Index))
143     report_fatal_error("renameModuleForThinLTO failed");
144 }
145 
146 namespace {
147 class ThinLTODiagnosticInfo : public DiagnosticInfo {
148   const Twine &Msg;
149 public:
150   ThinLTODiagnosticInfo(const Twine &DiagMsg,
151                         DiagnosticSeverity Severity = DS_Error)
152       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
153   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
154 };
155 }
156 
157 /// Verify the module and strip broken debug info.
158 static void verifyLoadedModule(Module &TheModule) {
159   bool BrokenDebugInfo = false;
160   if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
161     report_fatal_error("Broken module found, compilation aborted!");
162   if (BrokenDebugInfo) {
163     TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
164         "Invalid debug info found, debug info will be stripped", DS_Warning));
165     StripDebugInfo(TheModule);
166   }
167 }
168 
169 static std::unique_ptr<Module>
170 loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
171                      bool Lazy, bool IsImporting) {
172   SMDiagnostic Err;
173   Expected<std::unique_ptr<Module>> ModuleOrErr =
174       Lazy
175           ? getLazyBitcodeModule(Buffer, Context,
176                                  /* ShouldLazyLoadMetadata */ true, IsImporting)
177           : parseBitcodeFile(Buffer, Context);
178   if (!ModuleOrErr) {
179     handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
180       SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
181                                       SourceMgr::DK_Error, EIB.message());
182       Err.print("ThinLTO", errs());
183     });
184     report_fatal_error("Can't load module, abort.");
185   }
186   if (!Lazy)
187     verifyLoadedModule(*ModuleOrErr.get());
188   return std::move(ModuleOrErr.get());
189 }
190 
191 static void
192 crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
193                       StringMap<MemoryBufferRef> &ModuleMap,
194                       const FunctionImporter::ImportMapTy &ImportList) {
195   auto Loader = [&](StringRef Identifier) {
196     return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
197                                 /*Lazy=*/true, /*IsImporting*/ true);
198   };
199 
200   FunctionImporter Importer(Index, Loader);
201   Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
202   if (!Result) {
203     handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
204       SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
205                                       SourceMgr::DK_Error, EIB.message());
206       Err.print("ThinLTO", errs());
207     });
208     report_fatal_error("importFunctions failed");
209   }
210   // Verify again after cross-importing.
211   verifyLoadedModule(TheModule);
212 }
213 
214 static void optimizeModule(Module &TheModule, TargetMachine &TM,
215                            unsigned OptLevel, bool Freestanding) {
216   // Populate the PassManager
217   PassManagerBuilder PMB;
218   PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
219   if (Freestanding)
220     PMB.LibraryInfo->disableAllFunctions();
221   PMB.Inliner = createFunctionInliningPass();
222   // FIXME: should get it from the bitcode?
223   PMB.OptLevel = OptLevel;
224   PMB.LoopVectorize = true;
225   PMB.SLPVectorize = true;
226   // Already did this in verifyLoadedModule().
227   PMB.VerifyInput = false;
228   PMB.VerifyOutput = false;
229 
230   legacy::PassManager PM;
231 
232   // Add the TTI (required to inform the vectorizer about register size for
233   // instance)
234   PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
235 
236   // Add optimizations
237   PMB.populateThinLTOPassManager(PM);
238 
239   PM.run(TheModule);
240 }
241 
242 // Convert the PreservedSymbols map from "Name" based to "GUID" based.
243 static DenseSet<GlobalValue::GUID>
244 computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
245                             const Triple &TheTriple) {
246   DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
247   for (auto &Entry : PreservedSymbols) {
248     StringRef Name = Entry.first();
249     if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
250       Name = Name.drop_front();
251     GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
252   }
253   return GUIDPreservedSymbols;
254 }
255 
256 std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
257                                             TargetMachine &TM) {
258   SmallVector<char, 128> OutputBuffer;
259 
260   // CodeGen
261   {
262     raw_svector_ostream OS(OutputBuffer);
263     legacy::PassManager PM;
264 
265     // If the bitcode files contain ARC code and were compiled with optimization,
266     // the ObjCARCContractPass must be run, so do it unconditionally here.
267     PM.add(createObjCARCContractPass());
268 
269     // Setup the codegen now.
270     if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
271                                /* DisableVerify */ true))
272       report_fatal_error("Failed to setup codegen");
273 
274     // Run codegen now. resulting binary is in OutputBuffer.
275     PM.run(TheModule);
276   }
277   return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
278 }
279 
280 /// Manage caching for a single Module.
281 class ModuleCacheEntry {
282   SmallString<128> EntryPath;
283 
284 public:
285   // Create a cache entry. This compute a unique hash for the Module considering
286   // the current list of export/import, and offer an interface to query to
287   // access the content in the cache.
288   ModuleCacheEntry(
289       StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
290       const FunctionImporter::ImportMapTy &ImportList,
291       const FunctionImporter::ExportSetTy &ExportList,
292       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
293       const GVSummaryMapTy &DefinedFunctions,
294       const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
295       bool Freestanding, const TargetMachineBuilder &TMBuilder) {
296     if (CachePath.empty())
297       return;
298 
299     if (!Index.modulePaths().count(ModuleID))
300       // The module does not have an entry, it can't have a hash at all
301       return;
302 
303     // Compute the unique hash for this entry
304     // This is based on the current compiler version, the module itself, the
305     // export list, the hash for every single module in the import list, the
306     // list of ResolvedODR for the module, and the list of preserved symbols.
307 
308     // Include the hash for the current module
309     auto ModHash = Index.getModuleHash(ModuleID);
310 
311     if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
312       // No hash entry, no caching!
313       return;
314 
315     SHA1 Hasher;
316 
317     // Include the parts of the LTO configuration that affect code generation.
318     auto AddString = [&](StringRef Str) {
319       Hasher.update(Str);
320       Hasher.update(ArrayRef<uint8_t>{0});
321     };
322     auto AddUnsigned = [&](unsigned I) {
323       uint8_t Data[4];
324       Data[0] = I;
325       Data[1] = I >> 8;
326       Data[2] = I >> 16;
327       Data[3] = I >> 24;
328       Hasher.update(ArrayRef<uint8_t>{Data, 4});
329     };
330 
331     // Start with the compiler revision
332     Hasher.update(LLVM_VERSION_STRING);
333 #ifdef LLVM_REVISION
334     Hasher.update(LLVM_REVISION);
335 #endif
336 
337     // Hash the optimization level and the target machine settings.
338     AddString(TMBuilder.MCpu);
339     // FIXME: Hash more of Options. For now all clients initialize Options from
340     // command-line flags (which is unsupported in production), but may set
341     // RelaxELFRelocations. The clang driver can also pass FunctionSections,
342     // DataSections and DebuggerTuning via command line flags.
343     AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
344     AddUnsigned(TMBuilder.Options.FunctionSections);
345     AddUnsigned(TMBuilder.Options.DataSections);
346     AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
347     AddString(TMBuilder.MAttr);
348     if (TMBuilder.RelocModel)
349       AddUnsigned(*TMBuilder.RelocModel);
350     AddUnsigned(TMBuilder.CGOptLevel);
351     AddUnsigned(OptLevel);
352     AddUnsigned(Freestanding);
353 
354     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
355     for (auto F : ExportList)
356       // The export list can impact the internalization, be conservative here
357       Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
358 
359     // Include the hash for every module we import functions from
360     for (auto &Entry : ImportList) {
361       auto ModHash = Index.getModuleHash(Entry.first());
362       Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
363     }
364 
365     // Include the hash for the resolved ODR.
366     for (auto &Entry : ResolvedODR) {
367       Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
368                                       sizeof(GlobalValue::GUID)));
369       Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
370                                       sizeof(GlobalValue::LinkageTypes)));
371     }
372 
373     // Include the hash for the preserved symbols.
374     for (auto &Entry : PreservedSymbols) {
375       if (DefinedFunctions.count(Entry))
376         Hasher.update(
377             ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
378     }
379 
380     // This choice of file name allows the cache to be pruned (see pruneCache()
381     // in include/llvm/Support/CachePruning.h).
382     sys::path::append(EntryPath, CachePath,
383                       "llvmcache-" + toHex(Hasher.result()));
384   }
385 
386   // Access the path to this entry in the cache.
387   StringRef getEntryPath() { return EntryPath; }
388 
389   // Try loading the buffer for this cache entry.
390   ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
391     if (EntryPath.empty())
392       return std::error_code();
393     return MemoryBuffer::getFile(EntryPath);
394   }
395 
396   // Cache the Produced object file
397   void write(const MemoryBuffer &OutputBuffer) {
398     if (EntryPath.empty())
399       return;
400 
401     // Write to a temporary to avoid race condition
402     SmallString<128> TempFilename;
403     int TempFD;
404     std::error_code EC =
405         sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
406     if (EC) {
407       errs() << "Error: " << EC.message() << "\n";
408       report_fatal_error("ThinLTO: Can't get a temporary file");
409     }
410     {
411       raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
412       OS << OutputBuffer.getBuffer();
413     }
414     // Rename to final destination (hopefully race condition won't matter here)
415     EC = sys::fs::rename(TempFilename, EntryPath);
416     if (EC) {
417       sys::fs::remove(TempFilename);
418       raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
419       if (EC)
420         report_fatal_error(Twine("Failed to open ") + EntryPath +
421                            " to save cached entry\n");
422       OS << OutputBuffer.getBuffer();
423     }
424   }
425 };
426 
427 static std::unique_ptr<MemoryBuffer>
428 ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
429                      StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
430                      const FunctionImporter::ImportMapTy &ImportList,
431                      const FunctionImporter::ExportSetTy &ExportList,
432                      const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
433                      const GVSummaryMapTy &DefinedGlobals,
434                      const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
435                      bool DisableCodeGen, StringRef SaveTempsDir,
436                      bool Freestanding, unsigned OptLevel, unsigned count) {
437 
438   // "Benchmark"-like optimization: single-source case
439   bool SingleModule = (ModuleMap.size() == 1);
440 
441   if (!SingleModule) {
442     promoteModule(TheModule, Index);
443 
444     // Apply summary-based LinkOnce/Weak resolution decisions.
445     thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
446 
447     // Save temps: after promotion.
448     saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
449   }
450 
451   // Be friendly and don't nuke totally the module when the client didn't
452   // supply anything to preserve.
453   if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
454     // Apply summary-based internalization decisions.
455     thinLTOInternalizeModule(TheModule, DefinedGlobals);
456   }
457 
458   // Save internalized bitcode
459   saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
460 
461   if (!SingleModule) {
462     crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
463 
464     // Save temps: after cross-module import.
465     saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
466   }
467 
468   optimizeModule(TheModule, TM, OptLevel, Freestanding);
469 
470   saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
471 
472   if (DisableCodeGen) {
473     // Configured to stop before CodeGen, serialize the bitcode and return.
474     SmallVector<char, 128> OutputBuffer;
475     {
476       raw_svector_ostream OS(OutputBuffer);
477       ProfileSummaryInfo PSI(TheModule);
478       auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
479       WriteBitcodeToFile(&TheModule, OS, true, &Index);
480     }
481     return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
482   }
483 
484   return codegenModule(TheModule, TM);
485 }
486 
487 /// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
488 /// for caching, and in the \p Index for application during the ThinLTO
489 /// backends. This is needed for correctness for exported symbols (ensure
490 /// at least one copy kept) and a compile-time optimization (to drop duplicate
491 /// copies when possible).
492 static void resolveWeakForLinkerInIndex(
493     ModuleSummaryIndex &Index,
494     StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
495         &ResolvedODR) {
496 
497   DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
498   computePrevailingCopies(Index, PrevailingCopy);
499 
500   auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
501     const auto &Prevailing = PrevailingCopy.find(GUID);
502     // Not in map means that there was only one copy, which must be prevailing.
503     if (Prevailing == PrevailingCopy.end())
504       return true;
505     return Prevailing->second == S;
506   };
507 
508   auto recordNewLinkage = [&](StringRef ModuleIdentifier,
509                               GlobalValue::GUID GUID,
510                               GlobalValue::LinkageTypes NewLinkage) {
511     ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
512   };
513 
514   thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
515 }
516 
517 // Initialize the TargetMachine builder for a given Triple
518 static void initTMBuilder(TargetMachineBuilder &TMBuilder,
519                           const Triple &TheTriple) {
520   // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
521   // FIXME this looks pretty terrible...
522   if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
523     if (TheTriple.getArch() == llvm::Triple::x86_64)
524       TMBuilder.MCpu = "core2";
525     else if (TheTriple.getArch() == llvm::Triple::x86)
526       TMBuilder.MCpu = "yonah";
527     else if (TheTriple.getArch() == llvm::Triple::aarch64)
528       TMBuilder.MCpu = "cyclone";
529   }
530   TMBuilder.TheTriple = std::move(TheTriple);
531 }
532 
533 } // end anonymous namespace
534 
535 void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
536   ThinLTOBuffer Buffer(Data, Identifier);
537   LLVMContext Context;
538   StringRef TripleStr;
539   ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
540       Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
541 
542   if (TripleOrErr)
543     TripleStr = *TripleOrErr;
544 
545   Triple TheTriple(TripleStr);
546 
547   if (Modules.empty())
548     initTMBuilder(TMBuilder, Triple(TheTriple));
549   else if (TMBuilder.TheTriple != TheTriple) {
550     if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
551       report_fatal_error("ThinLTO modules with incompatible triples not "
552                          "supported");
553     initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
554   }
555 
556   Modules.push_back(Buffer);
557 }
558 
559 void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
560   PreservedSymbols.insert(Name);
561 }
562 
563 void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
564   // FIXME: At the moment, we don't take advantage of this extra information,
565   // we're conservatively considering cross-references as preserved.
566   //  CrossReferencedSymbols.insert(Name);
567   PreservedSymbols.insert(Name);
568 }
569 
570 // TargetMachine factory
571 std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
572   std::string ErrMsg;
573   const Target *TheTarget =
574       TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
575   if (!TheTarget) {
576     report_fatal_error("Can't load target for this Triple: " + ErrMsg);
577   }
578 
579   // Use MAttr as the default set of features.
580   SubtargetFeatures Features(MAttr);
581   Features.getDefaultSubtargetFeatures(TheTriple);
582   std::string FeatureStr = Features.getString();
583 
584   return std::unique_ptr<TargetMachine>(
585       TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options,
586                                      RelocModel, None, CGOptLevel));
587 }
588 
589 /**
590  * Produce the combined summary index from all the bitcode files:
591  * "thin-link".
592  */
593 std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
594   std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
595       llvm::make_unique<ModuleSummaryIndex>(/*IsPeformingAnalysis=*/false);
596   uint64_t NextModuleId = 0;
597   for (auto &ModuleBuffer : Modules) {
598     if (Error Err = readModuleSummaryIndex(ModuleBuffer.getMemBuffer(),
599                                            *CombinedIndex, NextModuleId++)) {
600       // FIXME diagnose
601       logAllUnhandledErrors(
602           std::move(Err), errs(),
603           "error: can't create module summary index for buffer: ");
604       return nullptr;
605     }
606   }
607   return CombinedIndex;
608 }
609 
610 static void internalizeAndPromoteInIndex(
611     const StringMap<FunctionImporter::ExportSetTy> &ExportLists,
612     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
613     ModuleSummaryIndex &Index) {
614   auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
615     const auto &ExportList = ExportLists.find(ModuleIdentifier);
616     return (ExportList != ExportLists.end() &&
617             ExportList->second.count(GUID)) ||
618            GUIDPreservedSymbols.count(GUID);
619   };
620 
621   thinLTOInternalizeAndPromoteInIndex(Index, isExported);
622 }
623 
624 /**
625  * Perform promotion and renaming of exported internal functions.
626  * Index is updated to reflect linkage changes from weak resolution.
627  */
628 void ThinLTOCodeGenerator::promote(Module &TheModule,
629                                    ModuleSummaryIndex &Index) {
630   auto ModuleCount = Index.modulePaths().size();
631   auto ModuleIdentifier = TheModule.getModuleIdentifier();
632 
633   // Collect for each module the list of function it defines (GUID -> Summary).
634   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
635   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
636 
637   // Convert the preserved symbols set from string to GUID
638   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
639       PreservedSymbols, Triple(TheModule.getTargetTriple()));
640 
641   // Compute "dead" symbols, we don't want to import/export these!
642   computeDeadSymbols(Index, GUIDPreservedSymbols);
643 
644   // Generate import/export list
645   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
646   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
647   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
648                            ExportLists);
649 
650   // Resolve LinkOnce/Weak symbols.
651   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
652   resolveWeakForLinkerInIndex(Index, ResolvedODR);
653 
654   thinLTOResolveWeakForLinkerModule(
655       TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
656 
657   // Promote the exported values in the index, so that they are promoted
658   // in the module.
659   internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
660 
661   promoteModule(TheModule, Index);
662 }
663 
664 /**
665  * Perform cross-module importing for the module identified by ModuleIdentifier.
666  */
667 void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
668                                              ModuleSummaryIndex &Index) {
669   auto ModuleMap = generateModuleMap(Modules);
670   auto ModuleCount = Index.modulePaths().size();
671 
672   // Collect for each module the list of function it defines (GUID -> Summary).
673   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
674   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
675 
676   // Convert the preserved symbols set from string to GUID
677   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
678       PreservedSymbols, Triple(TheModule.getTargetTriple()));
679 
680   // Compute "dead" symbols, we don't want to import/export these!
681   computeDeadSymbols(Index, GUIDPreservedSymbols);
682 
683   // Generate import/export list
684   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
685   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
686   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
687                            ExportLists);
688   auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
689 
690   crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
691 }
692 
693 /**
694  * Compute the list of summaries needed for importing into module.
695  */
696 void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
697     StringRef ModulePath, ModuleSummaryIndex &Index,
698     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
699   auto ModuleCount = Index.modulePaths().size();
700 
701   // Collect for each module the list of function it defines (GUID -> Summary).
702   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
703   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
704 
705   // Generate import/export list
706   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
707   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
708   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
709                            ExportLists);
710 
711   llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
712                                          ImportLists[ModulePath],
713                                          ModuleToSummariesForIndex);
714 }
715 
716 /**
717  * Emit the list of files needed for importing into module.
718  */
719 void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
720                                        StringRef OutputName,
721                                        ModuleSummaryIndex &Index) {
722   auto ModuleCount = Index.modulePaths().size();
723 
724   // Collect for each module the list of function it defines (GUID -> Summary).
725   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
726   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
727 
728   // Generate import/export list
729   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
730   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
731   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
732                            ExportLists);
733 
734   std::error_code EC;
735   if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
736     report_fatal_error(Twine("Failed to open ") + OutputName +
737                        " to save imports lists\n");
738 }
739 
740 /**
741  * Perform internalization. Index is updated to reflect linkage changes.
742  */
743 void ThinLTOCodeGenerator::internalize(Module &TheModule,
744                                        ModuleSummaryIndex &Index) {
745   initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
746   auto ModuleCount = Index.modulePaths().size();
747   auto ModuleIdentifier = TheModule.getModuleIdentifier();
748 
749   // Convert the preserved symbols set from string to GUID
750   auto GUIDPreservedSymbols =
751       computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
752 
753   // Collect for each module the list of function it defines (GUID -> Summary).
754   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
755   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
756 
757   // Compute "dead" symbols, we don't want to import/export these!
758   computeDeadSymbols(Index, GUIDPreservedSymbols);
759 
760   // Generate import/export list
761   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
762   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
763   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
764                            ExportLists);
765   auto &ExportList = ExportLists[ModuleIdentifier];
766 
767   // Be friendly and don't nuke totally the module when the client didn't
768   // supply anything to preserve.
769   if (ExportList.empty() && GUIDPreservedSymbols.empty())
770     return;
771 
772   // Internalization
773   internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
774   thinLTOInternalizeModule(TheModule,
775                            ModuleToDefinedGVSummaries[ModuleIdentifier]);
776 }
777 
778 /**
779  * Perform post-importing ThinLTO optimizations.
780  */
781 void ThinLTOCodeGenerator::optimize(Module &TheModule) {
782   initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
783 
784   // Optimize now
785   optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
786 }
787 
788 /**
789  * Perform ThinLTO CodeGen.
790  */
791 std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
792   initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
793   return codegenModule(TheModule, *TMBuilder.create());
794 }
795 
796 /// Write out the generated object file, either from CacheEntryPath or from
797 /// OutputBuffer, preferring hard-link when possible.
798 /// Returns the path to the generated file in SavedObjectsDirectoryPath.
799 static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
800                                         StringRef SavedObjectsDirectoryPath,
801                                         const MemoryBuffer &OutputBuffer) {
802   SmallString<128> OutputPath(SavedObjectsDirectoryPath);
803   llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
804   OutputPath.c_str(); // Ensure the string is null terminated.
805   if (sys::fs::exists(OutputPath))
806     sys::fs::remove(OutputPath);
807 
808   // We don't return a memory buffer to the linker, just a list of files.
809   if (!CacheEntryPath.empty()) {
810     // Cache is enabled, hard-link the entry (or copy if hard-link fails).
811     auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
812     if (!Err)
813       return OutputPath.str();
814     // Hard linking failed, try to copy.
815     Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
816     if (!Err)
817       return OutputPath.str();
818     // Copy failed (could be because the CacheEntry was removed from the cache
819     // in the meantime by another process), fall back and try to write down the
820     // buffer to the output.
821     errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
822            << "' to '" << OutputPath << "'\n";
823   }
824   // No cache entry, just write out the buffer.
825   std::error_code Err;
826   raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
827   if (Err)
828     report_fatal_error("Can't open output '" + OutputPath + "'\n");
829   OS << OutputBuffer.getBuffer();
830   return OutputPath.str();
831 }
832 
833 // Main entry point for the ThinLTO processing
834 void ThinLTOCodeGenerator::run() {
835   // Prepare the resulting object vector
836   assert(ProducedBinaries.empty() && "The generator should not be reused");
837   if (SavedObjectsDirectoryPath.empty())
838     ProducedBinaries.resize(Modules.size());
839   else {
840     sys::fs::create_directories(SavedObjectsDirectoryPath);
841     bool IsDir;
842     sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
843     if (!IsDir)
844       report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
845     ProducedBinaryFiles.resize(Modules.size());
846   }
847 
848   if (CodeGenOnly) {
849     // Perform only parallel codegen and return.
850     ThreadPool Pool;
851     int count = 0;
852     for (auto &ModuleBuffer : Modules) {
853       Pool.async([&](int count) {
854         LLVMContext Context;
855         Context.setDiscardValueNames(LTODiscardValueNames);
856 
857         // Parse module now
858         auto TheModule =
859             loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
860                                  /*IsImporting*/ false);
861 
862         // CodeGen
863         auto OutputBuffer = codegen(*TheModule);
864         if (SavedObjectsDirectoryPath.empty())
865           ProducedBinaries[count] = std::move(OutputBuffer);
866         else
867           ProducedBinaryFiles[count] = writeGeneratedObject(
868               count, "", SavedObjectsDirectoryPath, *OutputBuffer);
869       }, count++);
870     }
871 
872     return;
873   }
874 
875   // Sequential linking phase
876   auto Index = linkCombinedIndex();
877 
878   // Save temps: index.
879   if (!SaveTempsDir.empty()) {
880     auto SaveTempPath = SaveTempsDir + "index.bc";
881     std::error_code EC;
882     raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
883     if (EC)
884       report_fatal_error(Twine("Failed to open ") + SaveTempPath +
885                          " to save optimized bitcode\n");
886     WriteIndexToFile(*Index, OS);
887   }
888 
889 
890   // Prepare the module map.
891   auto ModuleMap = generateModuleMap(Modules);
892   auto ModuleCount = Modules.size();
893 
894   // Collect for each module the list of function it defines (GUID -> Summary).
895   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
896   Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
897 
898   // Convert the preserved symbols set from string to GUID, this is needed for
899   // computing the caching hash and the internalization.
900   auto GUIDPreservedSymbols =
901       computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
902 
903   // Compute "dead" symbols, we don't want to import/export these!
904   computeDeadSymbols(*Index, GUIDPreservedSymbols);
905 
906   // 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);
910   ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
911                            ExportLists);
912 
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   // FIXME: we should be able to compute the caching hash for the entry based
916   // on the index, and nuke this map.
917   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
918 
919   // Resolve LinkOnce/Weak symbols, this has to be computed early because it
920   // impacts the caching.
921   resolveWeakForLinkerInIndex(*Index, ResolvedODR);
922 
923   // Use global summary-based analysis to identify symbols that can be
924   // internalized (because they aren't exported or preserved as per callback).
925   // Changes are made in the index, consumed in the ThinLTO backends.
926   internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, *Index);
927 
928   // Make sure that every module has an entry in the ExportLists and
929   // ResolvedODR maps to enable threaded access to these maps below.
930   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
931     ExportLists[DefinedGVSummaries.first()];
932     ResolvedODR[DefinedGVSummaries.first()];
933   }
934 
935   // Compute the ordering we will process the inputs: the rough heuristic here
936   // is to sort them per size so that the largest module get schedule as soon as
937   // possible. This is purely a compile-time optimization.
938   std::vector<int> ModulesOrdering;
939   ModulesOrdering.resize(Modules.size());
940   std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
941   std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
942             [&](int LeftIndex, int RightIndex) {
943               auto LSize = Modules[LeftIndex].getBuffer().size();
944               auto RSize = Modules[RightIndex].getBuffer().size();
945               return LSize > RSize;
946             });
947 
948   // Parallel optimizer + codegen
949   {
950     ThreadPool Pool(ThreadCount);
951     for (auto IndexCount : ModulesOrdering) {
952       auto &ModuleBuffer = Modules[IndexCount];
953       Pool.async([&](int count) {
954         auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
955         auto &ExportList = ExportLists[ModuleIdentifier];
956 
957         auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
958 
959         // The module may be cached, this helps handling it.
960         ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
961                                     ImportLists[ModuleIdentifier], ExportList,
962                                     ResolvedODR[ModuleIdentifier],
963                                     DefinedFunctions, GUIDPreservedSymbols,
964                                     OptLevel, Freestanding, TMBuilder);
965         auto CacheEntryPath = CacheEntry.getEntryPath();
966 
967         {
968           auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
969           DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
970                        << CacheEntryPath << "' for buffer " << count << " "
971                        << ModuleIdentifier << "\n");
972 
973           if (ErrOrBuffer) {
974             // Cache Hit!
975             if (SavedObjectsDirectoryPath.empty())
976               ProducedBinaries[count] = std::move(ErrOrBuffer.get());
977             else
978               ProducedBinaryFiles[count] = writeGeneratedObject(
979                   count, CacheEntryPath, SavedObjectsDirectoryPath,
980                   *ErrOrBuffer.get());
981             return;
982           }
983         }
984 
985         LLVMContext Context;
986         Context.setDiscardValueNames(LTODiscardValueNames);
987         Context.enableDebugTypeODRUniquing();
988         auto DiagFileOrErr = lto::setupOptimizationRemarks(
989             Context, LTORemarksFilename, LTOPassRemarksWithHotness, count);
990         if (!DiagFileOrErr) {
991           errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
992           report_fatal_error("ThinLTO: Can't get an output file for the "
993                              "remarks");
994         }
995 
996         // Parse module now
997         auto TheModule =
998             loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
999                                  /*IsImporting*/ false);
1000 
1001         // Save temps: original file.
1002         saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
1003 
1004         auto &ImportList = ImportLists[ModuleIdentifier];
1005         // Run the main process now, and generates a binary
1006         auto OutputBuffer = ProcessThinLTOModule(
1007             *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
1008             ExportList, GUIDPreservedSymbols,
1009             ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
1010             DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
1011 
1012         // Commit to the cache (if enabled)
1013         CacheEntry.write(*OutputBuffer);
1014 
1015         if (SavedObjectsDirectoryPath.empty()) {
1016           // We need to generated a memory buffer for the linker.
1017           if (!CacheEntryPath.empty()) {
1018             // Cache is enabled, reload from the cache
1019             // We do this to lower memory pressuree: the buffer is on the heap
1020             // and releasing it frees memory that can be used for the next input
1021             // file. The final binary link will read from the VFS cache
1022             // (hopefully!) or from disk if the memory pressure wasn't too high.
1023             auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1024             if (auto EC = ReloadedBufferOrErr.getError()) {
1025               // On error, keeping the preexisting buffer and printing a
1026               // diagnostic is more friendly than just crashing.
1027               errs() << "error: can't reload cached file '" << CacheEntryPath
1028                      << "': " << EC.message() << "\n";
1029             } else {
1030               OutputBuffer = std::move(*ReloadedBufferOrErr);
1031             }
1032           }
1033           ProducedBinaries[count] = std::move(OutputBuffer);
1034           return;
1035         }
1036         ProducedBinaryFiles[count] = writeGeneratedObject(
1037             count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
1038       }, IndexCount);
1039     }
1040   }
1041 
1042   pruneCache(CacheOptions.Path, CacheOptions.Policy);
1043 
1044   // If statistics were requested, print them out now.
1045   if (llvm::AreStatisticsEnabled())
1046     llvm::PrintStatistics();
1047   reportAndResetTimings();
1048 }
1049