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