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