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