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 | |
| 15 | #include "llvm/LTO/ThinLTOCodeGenerator.h" |
| 16 | |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame^] | 17 | #ifdef HAVE_LLVM_REVISION |
| 18 | #include "LLVMLTORevision.h" |
| 19 | #endif |
Teresa Johnson | cec0cae | 2016-03-14 21:18:10 +0000 | [diff] [blame] | 20 | #include "llvm/ADT/Statistic.h" |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 21 | #include "llvm/ADT/StringExtras.h" |
Teresa Johnson | 2d5487c | 2016-04-11 13:58:45 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/ModuleSummaryAnalysis.h" |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/TargetLibraryInfo.h" |
| 24 | #include "llvm/Analysis/TargetTransformInfo.h" |
Teresa Johnson | cec0cae | 2016-03-14 21:18:10 +0000 | [diff] [blame] | 25 | #include "llvm/Bitcode/BitcodeWriterPass.h" |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 26 | #include "llvm/Bitcode/ReaderWriter.h" |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 27 | #include "llvm/ExecutionEngine/ObjectMemoryBuffer.h" |
Teresa Johnson | cec0cae | 2016-03-14 21:18:10 +0000 | [diff] [blame] | 28 | #include "llvm/IR/DiagnosticPrinter.h" |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 29 | #include "llvm/IR/LLVMContext.h" |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 30 | #include "llvm/IR/LegacyPassManager.h" |
| 31 | #include "llvm/IR/Mangler.h" |
| 32 | #include "llvm/IRReader/IRReader.h" |
| 33 | #include "llvm/Linker/Linker.h" |
| 34 | #include "llvm/MC/SubtargetFeature.h" |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 35 | #include "llvm/Object/ModuleSummaryIndexObjectFile.h" |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 36 | #include "llvm/Support/Debug.h" |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame^] | 37 | #include "llvm/Support/CachePruning.h" |
| 38 | #include "llvm/Support/Debug.h" |
| 39 | #include "llvm/Support/Path.h" |
| 40 | #include "llvm/Support/SHA1.h" |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 41 | #include "llvm/Support/SourceMgr.h" |
| 42 | #include "llvm/Support/TargetRegistry.h" |
| 43 | #include "llvm/Support/ThreadPool.h" |
| 44 | #include "llvm/Target/TargetMachine.h" |
| 45 | #include "llvm/Transforms/IPO.h" |
| 46 | #include "llvm/Transforms/IPO/FunctionImport.h" |
| 47 | #include "llvm/Transforms/IPO/PassManagerBuilder.h" |
| 48 | #include "llvm/Transforms/ObjCARC.h" |
| 49 | #include "llvm/Transforms/Utils/FunctionImportUtils.h" |
| 50 | |
| 51 | using namespace llvm; |
| 52 | |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 53 | #define DEBUG_TYPE "thinlto" |
| 54 | |
Mehdi Amini | 09b4a8d | 2016-03-10 01:28:54 +0000 | [diff] [blame] | 55 | namespace llvm { |
| 56 | // Flags -discard-value-names, defined in LTOCodeGenerator.cpp |
| 57 | extern cl::opt<bool> LTODiscardValueNames; |
| 58 | } |
| 59 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 60 | namespace { |
| 61 | |
| 62 | static cl::opt<int> ThreadCount("threads", |
| 63 | cl::init(std::thread::hardware_concurrency())); |
| 64 | |
| 65 | static void diagnosticHandler(const DiagnosticInfo &DI) { |
| 66 | DiagnosticPrinterRawOStream DP(errs()); |
| 67 | DI.print(DP); |
| 68 | errs() << '\n'; |
| 69 | } |
| 70 | |
| 71 | // Simple helper to load a module from bitcode |
| 72 | static std::unique_ptr<Module> |
| 73 | loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context, |
| 74 | bool Lazy) { |
| 75 | SMDiagnostic Err; |
| 76 | ErrorOr<std::unique_ptr<Module>> ModuleOrErr(nullptr); |
| 77 | if (Lazy) { |
| 78 | ModuleOrErr = |
| 79 | getLazyBitcodeModule(MemoryBuffer::getMemBuffer(Buffer, false), Context, |
| 80 | /* ShouldLazyLoadMetadata */ Lazy); |
| 81 | } else { |
| 82 | ModuleOrErr = parseBitcodeFile(Buffer, Context); |
| 83 | } |
| 84 | if (std::error_code EC = ModuleOrErr.getError()) { |
| 85 | Err = SMDiagnostic(Buffer.getBufferIdentifier(), SourceMgr::DK_Error, |
| 86 | EC.message()); |
| 87 | Err.print("ThinLTO", errs()); |
| 88 | report_fatal_error("Can't load module, abort."); |
| 89 | } |
| 90 | return std::move(ModuleOrErr.get()); |
| 91 | } |
| 92 | |
| 93 | // Simple helper to save temporary files for debug. |
| 94 | static void saveTempBitcode(const Module &TheModule, StringRef TempDir, |
| 95 | unsigned count, StringRef Suffix) { |
| 96 | if (TempDir.empty()) |
| 97 | return; |
| 98 | // User asked to save temps, let dump the bitcode file after import. |
| 99 | auto SaveTempPath = TempDir + llvm::utostr(count) + Suffix; |
| 100 | std::error_code EC; |
| 101 | raw_fd_ostream OS(SaveTempPath.str(), EC, sys::fs::F_None); |
| 102 | if (EC) |
| 103 | report_fatal_error(Twine("Failed to open ") + SaveTempPath + |
| 104 | " to save optimized bitcode\n"); |
Teresa Johnson | 3c35e09 | 2016-04-04 21:19:31 +0000 | [diff] [blame] | 105 | WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 106 | } |
| 107 | |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 108 | bool IsFirstDefinitionForLinker(const GlobalValueInfoList &GVInfo, |
| 109 | const ModuleSummaryIndex &Index, |
| 110 | StringRef ModulePath) { |
| 111 | // Get the first *linker visible* definition for this global in the summary |
| 112 | // list. |
| 113 | auto FirstDefForLinker = llvm::find_if( |
| 114 | GVInfo, [](const std::unique_ptr<GlobalValueInfo> &FuncInfo) { |
| 115 | auto Linkage = FuncInfo->summary()->linkage(); |
| 116 | return !GlobalValue::isAvailableExternallyLinkage(Linkage); |
| 117 | }); |
| 118 | // If \p GV is not the first definition, give up... |
| 119 | if ((*FirstDefForLinker)->summary()->modulePath() != ModulePath) |
| 120 | return false; |
| 121 | // If there is any strong definition anywhere, do not bother emitting this. |
| 122 | if (llvm::any_of( |
| 123 | GVInfo, [](const std::unique_ptr<GlobalValueInfo> &FuncInfo) { |
| 124 | auto Linkage = FuncInfo->summary()->linkage(); |
| 125 | return !GlobalValue::isAvailableExternallyLinkage(Linkage) && |
| 126 | !GlobalValue::isWeakForLinker(Linkage); |
| 127 | })) |
| 128 | return false; |
| 129 | return true; |
Hans Wennborg | fa6e414 | 2016-04-02 01:03:41 +0000 | [diff] [blame] | 130 | } |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 131 | |
Mehdi Amini | a71a5a6 | 2016-04-21 05:47:17 +0000 | [diff] [blame] | 132 | static GlobalValue::LinkageTypes |
| 133 | ResolveODR(const ModuleSummaryIndex &Index, |
| 134 | const FunctionImporter::ExportSetTy &ExportList, |
| 135 | StringRef ModuleIdentifier, GlobalValue::GUID GUID, |
| 136 | const GlobalValueSummary &GV) { |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 137 | auto HasMultipleCopies = |
| 138 | [&](const GlobalValueInfoList &GVInfo) { return GVInfo.size() > 1; }; |
| 139 | |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 140 | auto OriginalLinkage = GV.linkage(); |
| 141 | switch (OriginalLinkage) { |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 142 | case GlobalValue::ExternalLinkage: |
| 143 | case GlobalValue::AvailableExternallyLinkage: |
| 144 | case GlobalValue::AppendingLinkage: |
| 145 | case GlobalValue::InternalLinkage: |
| 146 | case GlobalValue::PrivateLinkage: |
| 147 | case GlobalValue::ExternalWeakLinkage: |
| 148 | case GlobalValue::CommonLinkage: |
| 149 | case GlobalValue::LinkOnceAnyLinkage: |
| 150 | case GlobalValue::WeakAnyLinkage: |
| 151 | break; |
| 152 | case GlobalValue::LinkOnceODRLinkage: |
| 153 | case GlobalValue::WeakODRLinkage: { |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 154 | auto &GVInfo = Index.findGlobalValueInfoList(GUID)->second; |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 155 | // We need to emit only one of these, the first module will keep |
| 156 | // it, but turned into a weak while the others will drop it. |
Mehdi Amini | a71a5a6 | 2016-04-21 05:47:17 +0000 | [diff] [blame] | 157 | if (!HasMultipleCopies(GVInfo)) { |
| 158 | // Exported LinkonceODR needs to be promoted to not be discarded |
| 159 | if (GlobalValue::isDiscardableIfUnused(OriginalLinkage) && |
| 160 | ExportList.count(GUID)) |
| 161 | return GlobalValue::WeakODRLinkage; |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 162 | break; |
Mehdi Amini | a71a5a6 | 2016-04-21 05:47:17 +0000 | [diff] [blame] | 163 | } |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 164 | if (IsFirstDefinitionForLinker(GVInfo, Index, ModuleIdentifier)) |
| 165 | return GlobalValue::WeakODRLinkage; |
Mehdi Amini | a71a5a6 | 2016-04-21 05:47:17 +0000 | [diff] [blame] | 166 | else if (isa<AliasSummary>(&GV)) |
| 167 | // Alias can't be turned into available_externally. |
| 168 | return OriginalLinkage; |
| 169 | return GlobalValue::AvailableExternallyLinkage; |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 170 | } |
| 171 | } |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 172 | return OriginalLinkage; |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 173 | } |
| 174 | |
| 175 | /// Resolve LinkOnceODR and WeakODR. |
| 176 | /// |
| 177 | /// We'd like to drop these function if they are no longer referenced in the |
| 178 | /// current module. However there is a chance that another module is still |
| 179 | /// referencing them because of the import. We make sure we always emit at least |
| 180 | /// one copy. |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 181 | static void ResolveODR( |
| 182 | const ModuleSummaryIndex &Index, |
Mehdi Amini | a71a5a6 | 2016-04-21 05:47:17 +0000 | [diff] [blame] | 183 | const FunctionImporter::ExportSetTy &ExportList, |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 184 | const std::map<GlobalValue::GUID, GlobalValueSummary *> &DefinedGlobals, |
| 185 | StringRef ModuleIdentifier, |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame^] | 186 | std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR) { |
Mehdi Amini | 8dcc808 | 2016-04-14 08:46:22 +0000 | [diff] [blame] | 187 | if (Index.modulePaths().size() == 1) |
| 188 | // Nothing to do if we don't have multiple modules |
| 189 | return; |
| 190 | |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 191 | // We won't optimize the globals that are referenced by an alias for now |
| 192 | // Ideally we should turn the alias into a global and duplicate the definition |
| 193 | // when needed. |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 194 | DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias; |
| 195 | for (auto &GA : DefinedGlobals) { |
| 196 | if (auto AS = dyn_cast<AliasSummary>(GA.second)) |
| 197 | GlobalInvolvedWithAlias.insert(&AS->getAliasee()); |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 198 | } |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 199 | |
| 200 | for (auto &GV : DefinedGlobals) { |
| 201 | if (GlobalInvolvedWithAlias.count(GV.second)) |
| 202 | continue; |
Mehdi Amini | a71a5a6 | 2016-04-21 05:47:17 +0000 | [diff] [blame] | 203 | auto NewLinkage = |
| 204 | ResolveODR(Index, ExportList, ModuleIdentifier, GV.first, *GV.second); |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 205 | if (NewLinkage != GV.second->linkage()) { |
| 206 | ResolvedODR[GV.first] = NewLinkage; |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | /// Fixup linkage, see ResolveODR() above. |
| 212 | void fixupODR( |
| 213 | Module &TheModule, |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame^] | 214 | const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR) { |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 215 | // Process functions and global now |
| 216 | for (auto &GV : TheModule) { |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 217 | auto NewLinkage = ResolvedODR.find(GV.getGUID()); |
| 218 | if (NewLinkage == ResolvedODR.end()) |
| 219 | continue; |
| 220 | DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from " |
| 221 | << GV.getLinkage() << " to " << NewLinkage->second << "\n"); |
| 222 | GV.setLinkage(NewLinkage->second); |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 223 | } |
| 224 | for (auto &GV : TheModule.globals()) { |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 225 | auto NewLinkage = ResolvedODR.find(GV.getGUID()); |
| 226 | if (NewLinkage == ResolvedODR.end()) |
| 227 | continue; |
| 228 | DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from " |
| 229 | << GV.getLinkage() << " to " << NewLinkage->second << "\n"); |
| 230 | GV.setLinkage(NewLinkage->second); |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 231 | } |
Mehdi Amini | a71a5a6 | 2016-04-21 05:47:17 +0000 | [diff] [blame] | 232 | for (auto &GV : TheModule.aliases()) { |
| 233 | auto NewLinkage = ResolvedODR.find(GV.getGUID()); |
| 234 | if (NewLinkage == ResolvedODR.end()) |
| 235 | continue; |
| 236 | DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from " |
| 237 | << GV.getLinkage() << " to " << NewLinkage->second << "\n"); |
| 238 | GV.setLinkage(NewLinkage->second); |
| 239 | } |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 240 | } |
| 241 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 242 | static StringMap<MemoryBufferRef> |
| 243 | generateModuleMap(const std::vector<MemoryBufferRef> &Modules) { |
| 244 | StringMap<MemoryBufferRef> ModuleMap; |
| 245 | for (auto &ModuleBuffer : Modules) { |
| 246 | assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) == |
| 247 | ModuleMap.end() && |
| 248 | "Expect unique Buffer Identifier"); |
| 249 | ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer; |
| 250 | } |
| 251 | return ModuleMap; |
| 252 | } |
| 253 | |
| 254 | /// Provide a "loader" for the FunctionImporter to access function from other |
| 255 | /// modules. |
| 256 | class ModuleLoader { |
| 257 | /// The context that will be used for importing. |
| 258 | LLVMContext &Context; |
| 259 | |
| 260 | /// Map from Module identifier to MemoryBuffer. Used by clients like the |
| 261 | /// FunctionImported to request loading a Module. |
| 262 | StringMap<MemoryBufferRef> &ModuleMap; |
| 263 | |
| 264 | public: |
| 265 | ModuleLoader(LLVMContext &Context, StringMap<MemoryBufferRef> &ModuleMap) |
| 266 | : Context(Context), ModuleMap(ModuleMap) {} |
| 267 | |
| 268 | /// Load a module on demand. |
| 269 | std::unique_ptr<Module> operator()(StringRef Identifier) { |
| 270 | return loadModuleFromBuffer(ModuleMap[Identifier], Context, /*Lazy*/ true); |
| 271 | } |
| 272 | }; |
| 273 | |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 274 | static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) { |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 275 | if (renameModuleForThinLTO(TheModule, Index)) |
| 276 | report_fatal_error("renameModuleForThinLTO failed"); |
| 277 | } |
| 278 | |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 279 | static void |
| 280 | crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index, |
| 281 | StringMap<MemoryBufferRef> &ModuleMap, |
| 282 | const FunctionImporter::ImportMapTy &ImportList) { |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 283 | ModuleLoader Loader(TheModule.getContext(), ModuleMap); |
| 284 | FunctionImporter Importer(Index, Loader); |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 285 | Importer.importFunctions(TheModule, ImportList); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 286 | } |
| 287 | |
| 288 | static void optimizeModule(Module &TheModule, TargetMachine &TM) { |
| 289 | // Populate the PassManager |
| 290 | PassManagerBuilder PMB; |
| 291 | PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple()); |
| 292 | PMB.Inliner = createFunctionInliningPass(); |
| 293 | // FIXME: should get it from the bitcode? |
| 294 | PMB.OptLevel = 3; |
| 295 | PMB.LoopVectorize = true; |
| 296 | PMB.SLPVectorize = true; |
| 297 | PMB.VerifyInput = true; |
| 298 | PMB.VerifyOutput = false; |
| 299 | |
| 300 | legacy::PassManager PM; |
| 301 | |
| 302 | // Add the TTI (required to inform the vectorizer about register size for |
| 303 | // instance) |
| 304 | PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis())); |
| 305 | |
| 306 | // Add optimizations |
| 307 | PMB.populateThinLTOPassManager(PM); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 308 | |
| 309 | PM.run(TheModule); |
| 310 | } |
| 311 | |
| 312 | std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule, |
| 313 | TargetMachine &TM) { |
| 314 | SmallVector<char, 128> OutputBuffer; |
| 315 | |
| 316 | // CodeGen |
| 317 | { |
| 318 | raw_svector_ostream OS(OutputBuffer); |
| 319 | legacy::PassManager PM; |
Mehdi Amini | 215d59e | 2016-04-01 08:22:59 +0000 | [diff] [blame] | 320 | |
| 321 | // If the bitcode files contain ARC code and were compiled with optimization, |
| 322 | // the ObjCARCContractPass must be run, so do it unconditionally here. |
| 323 | PM.add(createObjCARCContractPass()); |
| 324 | |
| 325 | // Setup the codegen now. |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 326 | if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile, |
| 327 | /* DisableVerify */ true)) |
| 328 | report_fatal_error("Failed to setup codegen"); |
| 329 | |
| 330 | // Run codegen now. resulting binary is in OutputBuffer. |
| 331 | PM.run(TheModule); |
| 332 | } |
| 333 | return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer)); |
| 334 | } |
| 335 | |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame^] | 336 | /// Manage caching for a single Module. |
| 337 | class ModuleCacheEntry { |
| 338 | SmallString<128> EntryPath; |
| 339 | |
| 340 | public: |
| 341 | // Create a cache entry. This compute a unique hash for the Module considering |
| 342 | // the current list of export/import, and offer an interface to query to |
| 343 | // access the content in the cache. |
| 344 | ModuleCacheEntry( |
| 345 | StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID, |
| 346 | const FunctionImporter::ImportMapTy &ImportList, |
| 347 | const FunctionImporter::ExportSetTy &ExportList, |
| 348 | const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR, |
| 349 | const std::map<GlobalValue::GUID, GlobalValueSummary *> &DefinedFunctions, |
| 350 | const DenseSet<GlobalValue::GUID> &PreservedSymbols) { |
| 351 | if (CachePath.empty()) |
| 352 | return; |
| 353 | |
| 354 | // Compute the unique hash for this entry |
| 355 | // This is based on the current compiler version, the module itself, the |
| 356 | // export list, the hash for every single module in the import list, the |
| 357 | // list of ResolvedODR for the module, and the list of preserved symbols. |
| 358 | |
| 359 | SHA1 Hasher; |
| 360 | |
| 361 | // Start with the compiler revision |
| 362 | Hasher.update(LLVM_VERSION_STRING); |
| 363 | #ifdef HAVE_LLVM_REVISION |
| 364 | Hasher.update(LLVM_REVISION); |
| 365 | #endif |
| 366 | |
| 367 | // Include the hash for the current module |
| 368 | auto ModHash = Index.getModuleHash(ModuleID); |
| 369 | Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash))); |
| 370 | for (auto F : ExportList) |
| 371 | // The export list can impact the internalization, be conservative here |
| 372 | Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F))); |
| 373 | |
| 374 | // Include the hash for every module we import functions from |
| 375 | for (auto &Entry : ImportList) { |
| 376 | auto ModHash = Index.getModuleHash(Entry.first()); |
| 377 | Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash))); |
| 378 | } |
| 379 | |
| 380 | // Include the hash for the resolved ODR. |
| 381 | for (auto &Entry : ResolvedODR) { |
| 382 | Hasher.update(ArrayRef<uint8_t>((uint8_t *)&Entry.first, |
| 383 | sizeof(GlobalValue::GUID))); |
| 384 | Hasher.update(ArrayRef<uint8_t>((uint8_t *)&Entry.second, |
| 385 | sizeof(GlobalValue::LinkageTypes))); |
| 386 | } |
| 387 | |
| 388 | // Include the hash for the preserved symbols. |
| 389 | for (auto &Entry : PreservedSymbols) { |
| 390 | if (DefinedFunctions.count(Entry)) |
| 391 | Hasher.update( |
| 392 | ArrayRef<uint8_t>((uint8_t *)&Entry, sizeof(GlobalValue::GUID))); |
| 393 | } |
| 394 | |
| 395 | sys::path::append(EntryPath, CachePath, toHex(Hasher.result())); |
| 396 | } |
| 397 | |
| 398 | // Try loading the buffer for this cache entry. |
| 399 | ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() { |
| 400 | if (EntryPath.empty()) |
| 401 | return std::error_code(); |
| 402 | return MemoryBuffer::getFile(EntryPath); |
| 403 | } |
| 404 | |
| 405 | // Cache the Produced object file |
| 406 | void write(MemoryBufferRef OutputBuffer) { |
| 407 | if (EntryPath.empty()) |
| 408 | return; |
| 409 | |
| 410 | // Write to a temporary to avoid race condition |
| 411 | SmallString<128> TempFilename; |
| 412 | int TempFD; |
| 413 | std::error_code EC = |
| 414 | sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename); |
| 415 | if (EC) { |
| 416 | errs() << "Error: " << EC.message() << "\n"; |
| 417 | report_fatal_error("ThinLTO: Can't get a temporary file"); |
| 418 | } |
| 419 | { |
| 420 | raw_fd_ostream OS(TempFD, /* ShouldClose */ true); |
| 421 | OS << OutputBuffer.getBuffer(); |
| 422 | } |
| 423 | // Rename to final destination (hopefully race condition won't matter here) |
| 424 | sys::fs::rename(TempFilename, EntryPath); |
| 425 | } |
| 426 | }; |
| 427 | |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 428 | static std::unique_ptr<MemoryBuffer> ProcessThinLTOModule( |
| 429 | Module &TheModule, const ModuleSummaryIndex &Index, |
| 430 | StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM, |
| 431 | const FunctionImporter::ImportMapTy &ImportList, |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame^] | 432 | std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR, |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 433 | ThinLTOCodeGenerator::CachingOptions CacheOptions, bool DisableCodeGen, |
| 434 | StringRef SaveTempsDir, unsigned count) { |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 435 | |
| 436 | // Save temps: after IPO. |
| 437 | saveTempBitcode(TheModule, SaveTempsDir, count, ".1.IPO.bc"); |
| 438 | |
| 439 | // "Benchmark"-like optimization: single-source case |
| 440 | bool SingleModule = (ModuleMap.size() == 1); |
| 441 | |
| 442 | if (!SingleModule) { |
| 443 | promoteModule(TheModule, Index); |
| 444 | |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 445 | // Resolve the LinkOnce/Weak ODR, trying to turn them into |
| 446 | // "available_externally" when possible. |
| 447 | // This is a compile-time optimization. |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 448 | fixupODR(TheModule, ResolvedODR); |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 449 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 450 | // Save temps: after promotion. |
| 451 | saveTempBitcode(TheModule, SaveTempsDir, count, ".2.promoted.bc"); |
| 452 | |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 453 | crossImportIntoModule(TheModule, Index, ModuleMap, ImportList); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 454 | |
| 455 | // Save temps: after cross-module import. |
| 456 | saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc"); |
| 457 | } |
| 458 | |
| 459 | optimizeModule(TheModule, TM); |
| 460 | |
| 461 | saveTempBitcode(TheModule, SaveTempsDir, count, ".3.opt.bc"); |
| 462 | |
Mehdi Amini | 43b657b | 2016-04-01 06:47:02 +0000 | [diff] [blame] | 463 | if (DisableCodeGen) { |
| 464 | // Configured to stop before CodeGen, serialize the bitcode and return. |
| 465 | SmallVector<char, 128> OutputBuffer; |
| 466 | { |
| 467 | raw_svector_ostream OS(OutputBuffer); |
Teresa Johnson | 2d5487c | 2016-04-11 13:58:45 +0000 | [diff] [blame] | 468 | ModuleSummaryIndexBuilder IndexBuilder(&TheModule); |
| 469 | WriteBitcodeToFile(&TheModule, OS, true, &IndexBuilder.getIndex()); |
Mehdi Amini | 43b657b | 2016-04-01 06:47:02 +0000 | [diff] [blame] | 470 | } |
| 471 | return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer)); |
| 472 | } |
| 473 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 474 | return codegenModule(TheModule, TM); |
| 475 | } |
| 476 | |
| 477 | // Initialize the TargetMachine builder for a given Triple |
| 478 | static void initTMBuilder(TargetMachineBuilder &TMBuilder, |
| 479 | const Triple &TheTriple) { |
| 480 | // Set a default CPU for Darwin triples (copied from LTOCodeGenerator). |
| 481 | // FIXME this looks pretty terrible... |
| 482 | if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) { |
| 483 | if (TheTriple.getArch() == llvm::Triple::x86_64) |
| 484 | TMBuilder.MCpu = "core2"; |
| 485 | else if (TheTriple.getArch() == llvm::Triple::x86) |
| 486 | TMBuilder.MCpu = "yonah"; |
| 487 | else if (TheTriple.getArch() == llvm::Triple::aarch64) |
| 488 | TMBuilder.MCpu = "cyclone"; |
| 489 | } |
| 490 | TMBuilder.TheTriple = std::move(TheTriple); |
| 491 | } |
| 492 | |
| 493 | } // end anonymous namespace |
| 494 | |
| 495 | void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) { |
| 496 | MemoryBufferRef Buffer(Data, Identifier); |
| 497 | if (Modules.empty()) { |
| 498 | // First module added, so initialize the triple and some options |
| 499 | LLVMContext Context; |
| 500 | Triple TheTriple(getBitcodeTargetTriple(Buffer, Context)); |
| 501 | initTMBuilder(TMBuilder, Triple(TheTriple)); |
| 502 | } |
| 503 | #ifndef NDEBUG |
| 504 | else { |
| 505 | LLVMContext Context; |
| 506 | assert(TMBuilder.TheTriple.str() == |
| 507 | getBitcodeTargetTriple(Buffer, Context) && |
| 508 | "ThinLTO modules with different triple not supported"); |
| 509 | } |
| 510 | #endif |
| 511 | Modules.push_back(Buffer); |
| 512 | } |
| 513 | |
| 514 | void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) { |
| 515 | PreservedSymbols.insert(Name); |
| 516 | } |
| 517 | |
| 518 | void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) { |
| 519 | CrossReferencedSymbols.insert(Name); |
| 520 | } |
| 521 | |
| 522 | // TargetMachine factory |
| 523 | std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const { |
| 524 | std::string ErrMsg; |
| 525 | const Target *TheTarget = |
| 526 | TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg); |
| 527 | if (!TheTarget) { |
| 528 | report_fatal_error("Can't load target for this Triple: " + ErrMsg); |
| 529 | } |
| 530 | |
| 531 | // Use MAttr as the default set of features. |
| 532 | SubtargetFeatures Features(MAttr); |
| 533 | Features.getDefaultSubtargetFeatures(TheTriple); |
| 534 | std::string FeatureStr = Features.getString(); |
| 535 | return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine( |
| 536 | TheTriple.str(), MCpu, FeatureStr, Options, RelocModel, |
| 537 | CodeModel::Default, CGOptLevel)); |
| 538 | } |
| 539 | |
| 540 | /** |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 541 | * Produce the combined summary index from all the bitcode files: |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 542 | * "thin-link". |
| 543 | */ |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 544 | std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() { |
| 545 | std::unique_ptr<ModuleSummaryIndex> CombinedIndex; |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 546 | uint64_t NextModuleId = 0; |
| 547 | for (auto &ModuleBuffer : Modules) { |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 548 | ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr = |
| 549 | object::ModuleSummaryIndexObjectFile::create(ModuleBuffer, |
| 550 | diagnosticHandler, false); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 551 | if (std::error_code EC = ObjOrErr.getError()) { |
| 552 | // FIXME diagnose |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 553 | errs() << "error: can't create ModuleSummaryIndexObjectFile for buffer: " |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 554 | << EC.message() << "\n"; |
| 555 | return nullptr; |
| 556 | } |
| 557 | auto Index = (*ObjOrErr)->takeIndex(); |
| 558 | if (CombinedIndex) { |
| 559 | CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId); |
| 560 | } else { |
| 561 | CombinedIndex = std::move(Index); |
| 562 | } |
| 563 | } |
| 564 | return CombinedIndex; |
| 565 | } |
| 566 | |
| 567 | /** |
| 568 | * Perform promotion and renaming of exported internal functions. |
| 569 | */ |
| 570 | void ThinLTOCodeGenerator::promote(Module &TheModule, |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 571 | ModuleSummaryIndex &Index) { |
Mehdi Amini | a71a5a6 | 2016-04-21 05:47:17 +0000 | [diff] [blame] | 572 | auto ModuleCount = Index.modulePaths().size(); |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 573 | auto ModuleIdentifier = TheModule.getModuleIdentifier(); |
| 574 | // Collect for each module the list of function it defines (GUID -> Summary). |
| 575 | StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>> |
| 576 | ModuleToDefinedGVSummaries; |
| 577 | Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 578 | |
Mehdi Amini | a71a5a6 | 2016-04-21 05:47:17 +0000 | [diff] [blame] | 579 | // Generate import/export list |
| 580 | StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); |
| 581 | StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); |
| 582 | ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, |
| 583 | ExportLists); |
| 584 | auto &ExportList = ExportLists[ModuleIdentifier]; |
| 585 | |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 586 | // Resolve the LinkOnceODR, trying to turn them into "available_externally" |
| 587 | // where possible. |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 588 | // This is a compile-time optimization. |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame^] | 589 | // We use a std::map here to be able to have a defined ordering when |
| 590 | // producing a hash for the cache entry. |
| 591 | std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> ResolvedODR; |
Mehdi Amini | a71a5a6 | 2016-04-21 05:47:17 +0000 | [diff] [blame] | 592 | ResolveODR(Index, ExportList, ModuleToDefinedGVSummaries[ModuleIdentifier], |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 593 | ModuleIdentifier, ResolvedODR); |
| 594 | fixupODR(TheModule, ResolvedODR); |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 595 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 596 | promoteModule(TheModule, Index); |
| 597 | } |
| 598 | |
| 599 | /** |
| 600 | * Perform cross-module importing for the module identified by ModuleIdentifier. |
| 601 | */ |
| 602 | void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule, |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 603 | ModuleSummaryIndex &Index) { |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 604 | auto ModuleMap = generateModuleMap(Modules); |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 605 | auto ModuleCount = Index.modulePaths().size(); |
| 606 | |
| 607 | // Collect for each module the list of function it defines (GUID -> Summary). |
| 608 | StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>> |
| 609 | ModuleToDefinedGVSummaries(ModuleCount); |
| 610 | Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 611 | |
| 612 | // Generate import/export list |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 613 | StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); |
| 614 | StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 615 | ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, |
| 616 | ExportLists); |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 617 | auto &ImportList = ImportLists[TheModule.getModuleIdentifier()]; |
| 618 | |
| 619 | crossImportIntoModule(TheModule, Index, ModuleMap, ImportList); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 620 | } |
| 621 | |
| 622 | /** |
| 623 | * Perform post-importing ThinLTO optimizations. |
| 624 | */ |
| 625 | void ThinLTOCodeGenerator::optimize(Module &TheModule) { |
| 626 | initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple())); |
| 627 | optimizeModule(TheModule, *TMBuilder.create()); |
| 628 | } |
| 629 | |
| 630 | /** |
| 631 | * Perform ThinLTO CodeGen. |
| 632 | */ |
| 633 | std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) { |
| 634 | initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple())); |
| 635 | return codegenModule(TheModule, *TMBuilder.create()); |
| 636 | } |
| 637 | |
| 638 | // Main entry point for the ThinLTO processing |
| 639 | void ThinLTOCodeGenerator::run() { |
Mehdi Amini | 43b657b | 2016-04-01 06:47:02 +0000 | [diff] [blame] | 640 | if (CodeGenOnly) { |
| 641 | // Perform only parallel codegen and return. |
| 642 | ThreadPool Pool; |
| 643 | assert(ProducedBinaries.empty() && "The generator should not be reused"); |
| 644 | ProducedBinaries.resize(Modules.size()); |
| 645 | int count = 0; |
| 646 | for (auto &ModuleBuffer : Modules) { |
| 647 | Pool.async([&](int count) { |
| 648 | LLVMContext Context; |
| 649 | Context.setDiscardValueNames(LTODiscardValueNames); |
| 650 | |
| 651 | // Parse module now |
| 652 | auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false); |
| 653 | |
| 654 | // CodeGen |
| 655 | ProducedBinaries[count] = codegen(*TheModule); |
| 656 | }, count++); |
| 657 | } |
| 658 | |
| 659 | return; |
| 660 | } |
| 661 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 662 | // Sequential linking phase |
| 663 | auto Index = linkCombinedIndex(); |
| 664 | |
| 665 | // Save temps: index. |
| 666 | if (!SaveTempsDir.empty()) { |
| 667 | auto SaveTempPath = SaveTempsDir + "index.bc"; |
| 668 | std::error_code EC; |
| 669 | raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None); |
| 670 | if (EC) |
| 671 | report_fatal_error(Twine("Failed to open ") + SaveTempPath + |
| 672 | " to save optimized bitcode\n"); |
Teresa Johnson | 76a1c1d | 2016-03-11 18:52:24 +0000 | [diff] [blame] | 673 | WriteIndexToFile(*Index, OS); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 674 | } |
| 675 | |
| 676 | // Prepare the resulting object vector |
| 677 | assert(ProducedBinaries.empty() && "The generator should not be reused"); |
| 678 | ProducedBinaries.resize(Modules.size()); |
| 679 | |
| 680 | // Prepare the module map. |
| 681 | auto ModuleMap = generateModuleMap(Modules); |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 682 | auto ModuleCount = Modules.size(); |
| 683 | |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 684 | // Collect for each module the list of function it defines (GUID -> Summary). |
| 685 | StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>> |
| 686 | ModuleToDefinedGVSummaries(ModuleCount); |
| 687 | Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); |
| 688 | |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 689 | // Collect the import/export lists for all modules from the call-graph in the |
| 690 | // combined index. |
| 691 | StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); |
| 692 | StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 693 | ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists, |
| 694 | ExportLists); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 695 | |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame^] | 696 | // Convert the preserved symbols set from string to GUID, this is needed for |
| 697 | // computing the caching. |
| 698 | DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size()); |
| 699 | for (auto &Entry : PreservedSymbols) |
| 700 | GUIDPreservedSymbols.insert(GlobalValue::getGUID(Entry.first())); |
| 701 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 702 | // Parallel optimizer + codegen |
| 703 | { |
| 704 | ThreadPool Pool(ThreadCount); |
| 705 | int count = 0; |
| 706 | for (auto &ModuleBuffer : Modules) { |
| 707 | Pool.async([&](int count) { |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 708 | auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier(); |
Mehdi Amini | a71a5a6 | 2016-04-21 05:47:17 +0000 | [diff] [blame] | 709 | auto &ExportList = ExportLists[ModuleIdentifier]; |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 710 | |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame^] | 711 | auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier]; |
| 712 | |
| 713 | // Resolve ODR, this has to be done early because it impacts the caching |
| 714 | // We use a std::map here to be able to have a defined ordering when |
| 715 | // producing a hash for the cache entry. |
| 716 | std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> ResolvedODR; |
| 717 | ResolveODR(*Index, ExportList, DefinedFunctions, |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 718 | ModuleIdentifier, ResolvedODR); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 719 | |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame^] | 720 | // The module may be cached, this helps handling it. |
| 721 | ModuleCacheEntry CacheEntry( |
| 722 | CacheOptions.Path, *Index, ModuleBuffer.getBufferIdentifier(), |
| 723 | ImportLists[ModuleBuffer.getBufferIdentifier()], |
| 724 | ExportLists[ModuleBuffer.getBufferIdentifier()], ResolvedODR, |
| 725 | DefinedFunctions, GUIDPreservedSymbols); |
| 726 | |
| 727 | { |
| 728 | auto ErrOrBuffer = CacheEntry.tryLoadingBuffer(); |
| 729 | if (ErrOrBuffer) { |
| 730 | // Cache Hit! |
| 731 | ProducedBinaries[count] = std::move(ErrOrBuffer.get()); |
| 732 | return; |
| 733 | } |
| 734 | } |
| 735 | |
| 736 | LLVMContext Context; |
| 737 | Context.setDiscardValueNames(LTODiscardValueNames); |
| 738 | Context.enableDebugTypeODRUniquing(); |
| 739 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 740 | // Parse module now |
| 741 | auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false); |
| 742 | |
| 743 | // Save temps: original file. |
| 744 | if (!SaveTempsDir.empty()) { |
| 745 | saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc"); |
| 746 | } |
| 747 | |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 748 | auto &ImportList = ImportLists[ModuleIdentifier]; |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame^] | 749 | auto OutputBuffer = ProcessThinLTOModule( |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 750 | *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList, |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 751 | ResolvedODR, CacheOptions, DisableCodeGen, SaveTempsDir, count); |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame^] | 752 | |
| 753 | CacheEntry.write(*OutputBuffer); |
| 754 | ProducedBinaries[count] = std::move(OutputBuffer); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 755 | }, count); |
| 756 | count++; |
| 757 | } |
| 758 | } |
| 759 | |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame^] | 760 | CachePruning(CacheOptions.Path) |
| 761 | .setPruningInterval(CacheOptions.PruningInterval) |
| 762 | .setEntryExpiration(CacheOptions.Expiration) |
| 763 | .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace) |
| 764 | .prune(); |
| 765 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 766 | // If statistics were requested, print them out now. |
| 767 | if (llvm::AreStatisticsEnabled()) |
| 768 | llvm::PrintStatistics(); |
| 769 | } |