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