Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 1 | //===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===// |
| 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 "backend" phase of LTO, i.e. it performs |
| 11 | // optimization and code generation on a loaded module. It is generally used |
| 12 | // internally by the LTO class but can also be used independently, for example |
| 13 | // to implement a standalone ThinLTO backend. |
| 14 | // |
| 15 | //===----------------------------------------------------------------------===// |
| 16 | |
| 17 | #include "llvm/LTO/LTOBackend.h" |
| 18 | #include "llvm/Analysis/TargetLibraryInfo.h" |
| 19 | #include "llvm/Analysis/TargetTransformInfo.h" |
| 20 | #include "llvm/Bitcode/ReaderWriter.h" |
| 21 | #include "llvm/IR/LegacyPassManager.h" |
Mehdi Amini | 970800e | 2016-08-17 06:23:09 +0000 | [diff] [blame] | 22 | #include "llvm/LTO/LTO.h" |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 23 | #include "llvm/MC/SubtargetFeature.h" |
| 24 | #include "llvm/Support/Error.h" |
| 25 | #include "llvm/Support/FileSystem.h" |
| 26 | #include "llvm/Support/TargetRegistry.h" |
| 27 | #include "llvm/Support/ThreadPool.h" |
| 28 | #include "llvm/Target/TargetMachine.h" |
| 29 | #include "llvm/Transforms/IPO.h" |
| 30 | #include "llvm/Transforms/IPO/PassManagerBuilder.h" |
| 31 | #include "llvm/Transforms/Utils/FunctionImportUtils.h" |
| 32 | #include "llvm/Transforms/Utils/SplitModule.h" |
| 33 | |
| 34 | using namespace llvm; |
| 35 | using namespace lto; |
| 36 | |
| 37 | Error Config::addSaveTemps(std::string OutputFileName, |
| 38 | bool UseInputModulePath) { |
| 39 | ShouldDiscardValueNames = false; |
| 40 | |
| 41 | std::error_code EC; |
| 42 | ResolutionFile = llvm::make_unique<raw_fd_ostream>( |
Mehdi Amini | eccffad | 2016-08-18 00:12:33 +0000 | [diff] [blame] | 43 | OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text); |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 44 | if (EC) |
| 45 | return errorCodeToError(EC); |
| 46 | |
| 47 | auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) { |
| 48 | // Keep track of the hook provided by the linker, which also needs to run. |
| 49 | ModuleHookFn LinkerHook = Hook; |
Mehdi Amini | f8c2f08 | 2016-08-22 16:17:40 +0000 | [diff] [blame] | 50 | Hook = [=](unsigned Task, const Module &M) { |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 51 | // If the linker's hook returned false, we need to pass that result |
| 52 | // through. |
| 53 | if (LinkerHook && !LinkerHook(Task, M)) |
| 54 | return false; |
| 55 | |
| 56 | std::string PathPrefix; |
| 57 | // If this is the combined module (not a ThinLTO backend compile) or the |
| 58 | // user hasn't requested using the input module's path, emit to a file |
| 59 | // named from the provided OutputFileName with the Task ID appended. |
| 60 | if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) { |
Mehdi Amini | eccffad | 2016-08-18 00:12:33 +0000 | [diff] [blame] | 61 | PathPrefix = OutputFileName + utostr(Task); |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 62 | } else |
| 63 | PathPrefix = M.getModuleIdentifier(); |
| 64 | std::string Path = PathPrefix + "." + PathSuffix + ".bc"; |
| 65 | std::error_code EC; |
| 66 | raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None); |
| 67 | if (EC) { |
| 68 | // Because -save-temps is a debugging feature, we report the error |
| 69 | // directly and exit. |
| 70 | llvm::errs() << "failed to open " << Path << ": " << EC.message() |
| 71 | << '\n'; |
| 72 | exit(1); |
| 73 | } |
| 74 | WriteBitcodeToFile(&M, OS, /*ShouldPreserveUseListOrder=*/false); |
| 75 | return true; |
| 76 | }; |
| 77 | }; |
| 78 | |
| 79 | setHook("0.preopt", PreOptModuleHook); |
| 80 | setHook("1.promote", PostPromoteModuleHook); |
| 81 | setHook("2.internalize", PostInternalizeModuleHook); |
| 82 | setHook("3.import", PostImportModuleHook); |
| 83 | setHook("4.opt", PostOptModuleHook); |
| 84 | setHook("5.precodegen", PreCodeGenModuleHook); |
| 85 | |
| 86 | CombinedIndexHook = [=](const ModuleSummaryIndex &Index) { |
Mehdi Amini | eccffad | 2016-08-18 00:12:33 +0000 | [diff] [blame] | 87 | std::string Path = OutputFileName + "index.bc"; |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 88 | std::error_code EC; |
| 89 | raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None); |
| 90 | if (EC) { |
| 91 | // Because -save-temps is a debugging feature, we report the error |
| 92 | // directly and exit. |
| 93 | llvm::errs() << "failed to open " << Path << ": " << EC.message() << '\n'; |
| 94 | exit(1); |
| 95 | } |
| 96 | WriteIndexToFile(Index, OS); |
| 97 | return true; |
| 98 | }; |
| 99 | |
| 100 | return Error(); |
| 101 | } |
| 102 | |
| 103 | namespace { |
| 104 | |
| 105 | std::unique_ptr<TargetMachine> |
| 106 | createTargetMachine(Config &C, StringRef TheTriple, const Target *TheTarget) { |
| 107 | SubtargetFeatures Features; |
| 108 | Features.getDefaultSubtargetFeatures(Triple(TheTriple)); |
| 109 | for (const std::string &A : C.MAttrs) |
| 110 | Features.AddFeature(A); |
| 111 | |
| 112 | return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine( |
| 113 | TheTriple, C.CPU, Features.getString(), C.Options, C.RelocModel, |
| 114 | C.CodeModel, C.CGOptLevel)); |
| 115 | } |
| 116 | |
Davide Italiano | 1e9d3d3 | 2016-08-31 17:02:44 +0000 | [diff] [blame^] | 117 | static void runOldPMPasses(Config &C, Module &M, TargetMachine *TM, |
| 118 | bool IsThinLto) { |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 119 | legacy::PassManager passes; |
| 120 | passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis())); |
| 121 | |
| 122 | PassManagerBuilder PMB; |
| 123 | PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())); |
| 124 | PMB.Inliner = createFunctionInliningPass(); |
| 125 | // Unconditionally verify input since it is not verified before this |
| 126 | // point and has unknown origin. |
| 127 | PMB.VerifyInput = true; |
| 128 | PMB.VerifyOutput = !C.DisableVerify; |
| 129 | PMB.LoopVectorize = true; |
| 130 | PMB.SLPVectorize = true; |
| 131 | PMB.OptLevel = C.OptLevel; |
| 132 | if (IsThinLto) |
| 133 | PMB.populateThinLTOPassManager(passes); |
| 134 | else |
| 135 | PMB.populateLTOPassManager(passes); |
| 136 | passes.run(M); |
Davide Italiano | 1e9d3d3 | 2016-08-31 17:02:44 +0000 | [diff] [blame^] | 137 | } |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 138 | |
Davide Italiano | 1e9d3d3 | 2016-08-31 17:02:44 +0000 | [diff] [blame^] | 139 | bool opt(Config &C, TargetMachine *TM, unsigned Task, Module &M, |
| 140 | bool IsThinLto) { |
| 141 | M.setDataLayout(TM->createDataLayout()); |
| 142 | runOldPMPasses(C, M, TM, IsThinLto); |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 143 | if (C.PostOptModuleHook && !C.PostOptModuleHook(Task, M)) |
| 144 | return false; |
| 145 | |
| 146 | return true; |
| 147 | } |
| 148 | |
Mehdi Amini | adc0e26 | 2016-08-23 21:30:12 +0000 | [diff] [blame] | 149 | /// Monolithic LTO does not support caching (yet), this is a convenient wrapper |
| 150 | /// around AddOutput to workaround this. |
| 151 | static AddOutputFn getUncachedOutputWrapper(AddOutputFn &AddOutput, |
| 152 | unsigned Task) { |
| 153 | return [Task, &AddOutput](unsigned TaskId) { |
| 154 | auto Output = AddOutput(Task); |
| 155 | if (Output->isCachingEnabled() && Output->tryLoadFromCache("")) |
| 156 | report_fatal_error("Cache hit without a valid key?"); |
Mehdi Amini | adc0e26 | 2016-08-23 21:30:12 +0000 | [diff] [blame] | 157 | assert(Task == TaskId && "Unexpexted TaskId mismatch"); |
| 158 | return Output; |
| 159 | }; |
| 160 | } |
| 161 | |
Mehdi Amini | 970800e | 2016-08-17 06:23:09 +0000 | [diff] [blame] | 162 | void codegen(Config &C, TargetMachine *TM, AddOutputFn AddOutput, unsigned Task, |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 163 | Module &M) { |
| 164 | if (C.PreCodeGenModuleHook && !C.PreCodeGenModuleHook(Task, M)) |
| 165 | return; |
| 166 | |
Mehdi Amini | 970800e | 2016-08-17 06:23:09 +0000 | [diff] [blame] | 167 | auto Output = AddOutput(Task); |
| 168 | std::unique_ptr<raw_pwrite_stream> OS = Output->getStream(); |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 169 | legacy::PassManager CodeGenPasses; |
| 170 | if (TM->addPassesToEmitFile(CodeGenPasses, *OS, |
| 171 | TargetMachine::CGFT_ObjectFile)) |
| 172 | report_fatal_error("Failed to setup codegen"); |
| 173 | CodeGenPasses.run(M); |
| 174 | } |
| 175 | |
Mehdi Amini | 970800e | 2016-08-17 06:23:09 +0000 | [diff] [blame] | 176 | void splitCodeGen(Config &C, TargetMachine *TM, AddOutputFn AddOutput, |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 177 | unsigned ParallelCodeGenParallelismLevel, |
| 178 | std::unique_ptr<Module> M) { |
| 179 | ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel); |
| 180 | unsigned ThreadCount = 0; |
| 181 | const Target *T = &TM->getTarget(); |
| 182 | |
| 183 | SplitModule( |
| 184 | std::move(M), ParallelCodeGenParallelismLevel, |
| 185 | [&](std::unique_ptr<Module> MPart) { |
| 186 | // We want to clone the module in a new context to multi-thread the |
| 187 | // codegen. We do it by serializing partition modules to bitcode |
| 188 | // (while still on the main thread, in order to avoid data races) and |
| 189 | // spinning up new threads which deserialize the partitions into |
| 190 | // separate contexts. |
| 191 | // FIXME: Provide a more direct way to do this in LLVM. |
| 192 | SmallString<0> BC; |
| 193 | raw_svector_ostream BCOS(BC); |
| 194 | WriteBitcodeToFile(MPart.get(), BCOS); |
| 195 | |
| 196 | // Enqueue the task |
| 197 | CodegenThreadPool.async( |
| 198 | [&](const SmallString<0> &BC, unsigned ThreadId) { |
| 199 | LTOLLVMContext Ctx(C); |
| 200 | ErrorOr<std::unique_ptr<Module>> MOrErr = parseBitcodeFile( |
| 201 | MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"), |
| 202 | Ctx); |
| 203 | if (!MOrErr) |
| 204 | report_fatal_error("Failed to read bitcode"); |
| 205 | std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get()); |
| 206 | |
| 207 | std::unique_ptr<TargetMachine> TM = |
| 208 | createTargetMachine(C, MPartInCtx->getTargetTriple(), T); |
Mehdi Amini | adc0e26 | 2016-08-23 21:30:12 +0000 | [diff] [blame] | 209 | |
| 210 | codegen(C, TM.get(), |
| 211 | getUncachedOutputWrapper(AddOutput, ThreadId), ThreadId, |
| 212 | *MPartInCtx); |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 213 | }, |
| 214 | // Pass BC using std::move to ensure that it get moved rather than |
| 215 | // copied into the thread's context. |
| 216 | std::move(BC), ThreadCount++); |
| 217 | }, |
| 218 | false); |
| 219 | } |
| 220 | |
| 221 | Expected<const Target *> initAndLookupTarget(Config &C, Module &M) { |
| 222 | if (!C.OverrideTriple.empty()) |
| 223 | M.setTargetTriple(C.OverrideTriple); |
| 224 | else if (M.getTargetTriple().empty()) |
| 225 | M.setTargetTriple(C.DefaultTriple); |
| 226 | |
| 227 | std::string Msg; |
| 228 | const Target *T = TargetRegistry::lookupTarget(M.getTargetTriple(), Msg); |
| 229 | if (!T) |
| 230 | return make_error<StringError>(Msg, inconvertibleErrorCode()); |
| 231 | return T; |
| 232 | } |
| 233 | |
| 234 | } |
| 235 | |
Mehdi Amini | 970800e | 2016-08-17 06:23:09 +0000 | [diff] [blame] | 236 | Error lto::backend(Config &C, AddOutputFn AddOutput, |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 237 | unsigned ParallelCodeGenParallelismLevel, |
| 238 | std::unique_ptr<Module> M) { |
| 239 | Expected<const Target *> TOrErr = initAndLookupTarget(C, *M); |
| 240 | if (!TOrErr) |
| 241 | return TOrErr.takeError(); |
| 242 | |
| 243 | std::unique_ptr<TargetMachine> TM = |
| 244 | createTargetMachine(C, M->getTargetTriple(), *TOrErr); |
| 245 | |
Mehdi Amini | d310b47 | 2016-08-22 06:25:41 +0000 | [diff] [blame] | 246 | if (!C.CodeGenOnly) |
| 247 | if (!opt(C, TM.get(), 0, *M, /*IsThinLto=*/false)) |
| 248 | return Error(); |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 249 | |
Mehdi Amini | adc0e26 | 2016-08-23 21:30:12 +0000 | [diff] [blame] | 250 | if (ParallelCodeGenParallelismLevel == 1) { |
| 251 | codegen(C, TM.get(), getUncachedOutputWrapper(AddOutput, 0), 0, *M); |
| 252 | } else { |
Mehdi Amini | 970800e | 2016-08-17 06:23:09 +0000 | [diff] [blame] | 253 | splitCodeGen(C, TM.get(), AddOutput, ParallelCodeGenParallelismLevel, |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 254 | std::move(M)); |
Mehdi Amini | adc0e26 | 2016-08-23 21:30:12 +0000 | [diff] [blame] | 255 | } |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 256 | return Error(); |
| 257 | } |
| 258 | |
Mehdi Amini | 970800e | 2016-08-17 06:23:09 +0000 | [diff] [blame] | 259 | Error lto::thinBackend(Config &Conf, unsigned Task, AddOutputFn AddOutput, |
Mehdi Amini | acc50c4 | 2016-08-16 00:44:46 +0000 | [diff] [blame] | 260 | Module &Mod, ModuleSummaryIndex &CombinedIndex, |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 261 | const FunctionImporter::ImportMapTy &ImportList, |
| 262 | const GVSummaryMapTy &DefinedGlobals, |
| 263 | MapVector<StringRef, MemoryBufferRef> &ModuleMap) { |
Mehdi Amini | acc50c4 | 2016-08-16 00:44:46 +0000 | [diff] [blame] | 264 | Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod); |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 265 | if (!TOrErr) |
| 266 | return TOrErr.takeError(); |
| 267 | |
| 268 | std::unique_ptr<TargetMachine> TM = |
Mehdi Amini | acc50c4 | 2016-08-16 00:44:46 +0000 | [diff] [blame] | 269 | createTargetMachine(Conf, Mod.getTargetTriple(), *TOrErr); |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 270 | |
Mehdi Amini | d310b47 | 2016-08-22 06:25:41 +0000 | [diff] [blame] | 271 | if (Conf.CodeGenOnly) { |
| 272 | codegen(Conf, TM.get(), AddOutput, Task, Mod); |
| 273 | return Error(); |
| 274 | } |
| 275 | |
Mehdi Amini | acc50c4 | 2016-08-16 00:44:46 +0000 | [diff] [blame] | 276 | if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod)) |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 277 | return Error(); |
| 278 | |
Mehdi Amini | acc50c4 | 2016-08-16 00:44:46 +0000 | [diff] [blame] | 279 | renameModuleForThinLTO(Mod, CombinedIndex); |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 280 | |
Mehdi Amini | 8ac7b32 | 2016-08-18 00:59:24 +0000 | [diff] [blame] | 281 | thinLTOResolveWeakForLinkerModule(Mod, DefinedGlobals); |
| 282 | |
Mehdi Amini | acc50c4 | 2016-08-16 00:44:46 +0000 | [diff] [blame] | 283 | if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod)) |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 284 | return Error(); |
| 285 | |
| 286 | if (!DefinedGlobals.empty()) |
Mehdi Amini | acc50c4 | 2016-08-16 00:44:46 +0000 | [diff] [blame] | 287 | thinLTOInternalizeModule(Mod, DefinedGlobals); |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 288 | |
Mehdi Amini | acc50c4 | 2016-08-16 00:44:46 +0000 | [diff] [blame] | 289 | if (Conf.PostInternalizeModuleHook && |
| 290 | !Conf.PostInternalizeModuleHook(Task, Mod)) |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 291 | return Error(); |
| 292 | |
| 293 | auto ModuleLoader = [&](StringRef Identifier) { |
Mehdi Amini | 9ec5a61 | 2016-08-23 16:53:34 +0000 | [diff] [blame] | 294 | assert(Mod.getContext().isODRUniquingDebugTypes() && |
| 295 | "ODR Type uniquing shoudl be enabled on the context"); |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 296 | return std::move(getLazyBitcodeModule(MemoryBuffer::getMemBuffer( |
| 297 | ModuleMap[Identifier], false), |
Mehdi Amini | acc50c4 | 2016-08-16 00:44:46 +0000 | [diff] [blame] | 298 | Mod.getContext(), |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 299 | /*ShouldLazyLoadMetadata=*/true) |
| 300 | .get()); |
| 301 | }; |
| 302 | |
| 303 | FunctionImporter Importer(CombinedIndex, ModuleLoader); |
Mehdi Amini | acc50c4 | 2016-08-16 00:44:46 +0000 | [diff] [blame] | 304 | Importer.importFunctions(Mod, ImportList); |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 305 | |
Mehdi Amini | acc50c4 | 2016-08-16 00:44:46 +0000 | [diff] [blame] | 306 | if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod)) |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 307 | return Error(); |
| 308 | |
Mehdi Amini | acc50c4 | 2016-08-16 00:44:46 +0000 | [diff] [blame] | 309 | if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLto=*/true)) |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 310 | return Error(); |
| 311 | |
Mehdi Amini | 970800e | 2016-08-17 06:23:09 +0000 | [diff] [blame] | 312 | codegen(Conf, TM.get(), AddOutput, Task, Mod); |
Teresa Johnson | 9ba95f9 | 2016-08-11 14:58:12 +0000 | [diff] [blame] | 313 | return Error(); |
| 314 | } |