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