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