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