1c269ed51SPeter Collingbourne //===-- ParallelCG.cpp ----------------------------------------------------===//
2c269ed51SPeter Collingbourne //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6c269ed51SPeter Collingbourne //
7c269ed51SPeter Collingbourne //===----------------------------------------------------------------------===//
8c269ed51SPeter Collingbourne //
9c269ed51SPeter Collingbourne // This file defines functions that can be used for parallel code generation.
10c269ed51SPeter Collingbourne //
11c269ed51SPeter Collingbourne //===----------------------------------------------------------------------===//
12c269ed51SPeter Collingbourne 
13c269ed51SPeter Collingbourne #include "llvm/CodeGen/ParallelCG.h"
14ad17679aSTeresa Johnson #include "llvm/Bitcode/BitcodeReader.h"
15ad17679aSTeresa Johnson #include "llvm/Bitcode/BitcodeWriter.h"
16c269ed51SPeter Collingbourne #include "llvm/IR/LLVMContext.h"
17c269ed51SPeter Collingbourne #include "llvm/IR/LegacyPassManager.h"
18c269ed51SPeter Collingbourne #include "llvm/IR/Module.h"
19c269ed51SPeter Collingbourne #include "llvm/Support/ErrorOr.h"
20c269ed51SPeter Collingbourne #include "llvm/Support/MemoryBuffer.h"
21d84c7decSTeresa Johnson #include "llvm/Support/ThreadPool.h"
22c269ed51SPeter Collingbourne #include "llvm/Target/TargetMachine.h"
23c269ed51SPeter Collingbourne #include "llvm/Transforms/Utils/SplitModule.h"
24c269ed51SPeter Collingbourne 
25c269ed51SPeter Collingbourne using namespace llvm;
26c269ed51SPeter Collingbourne 
271afc1de4SBenjamin Kramer static void codegen(Module *M, llvm::raw_pwrite_stream &OS,
281afc1de4SBenjamin Kramer                     function_ref<std::unique_ptr<TargetMachine>()> TMFactory,
291dfede31SReid Kleckner                     CodeGenFileType FileType) {
307950b129SDavide Italiano   std::unique_ptr<TargetMachine> TM = TMFactory();
311756d679SElla Ma   assert(TM && "Failed to create target machine!");
321756d679SElla Ma 
33c269ed51SPeter Collingbourne   legacy::PassManager CodeGenPasses;
349a45114bSPeter Collingbourne   if (TM->addPassesToEmitFile(CodeGenPasses, OS, nullptr, FileType))
35c269ed51SPeter Collingbourne     report_fatal_error("Failed to setup codegen");
36c269ed51SPeter Collingbourne   CodeGenPasses.run(*M);
37c269ed51SPeter Collingbourne }
38c269ed51SPeter Collingbourne 
39*f3a710caSFlorian Hahn void llvm::splitCodeGen(
40*f3a710caSFlorian Hahn     Module &M, ArrayRef<llvm::raw_pwrite_stream *> OSs,
417950b129SDavide Italiano     ArrayRef<llvm::raw_pwrite_stream *> BCOSs,
427950b129SDavide Italiano     const std::function<std::unique_ptr<TargetMachine>()> &TMFactory,
431dfede31SReid Kleckner     CodeGenFileType FileType, bool PreserveLocals) {
44268826a2SEvgeniy Stepanov   assert(BCOSs.empty() || BCOSs.size() == OSs.size());
45268826a2SEvgeniy Stepanov 
46c269ed51SPeter Collingbourne   if (OSs.size() == 1) {
47268826a2SEvgeniy Stepanov     if (!BCOSs.empty())
48*f3a710caSFlorian Hahn       WriteBitcodeToFile(M, *BCOSs[0]);
49*f3a710caSFlorian Hahn     codegen(&M, *OSs[0], TMFactory, FileType);
50*f3a710caSFlorian Hahn     return;
51c269ed51SPeter Collingbourne   }
52c269ed51SPeter Collingbourne 
53d84c7decSTeresa Johnson   // Create ThreadPool in nested scope so that threads will be joined
54d84c7decSTeresa Johnson   // on destruction.
55d84c7decSTeresa Johnson   {
568404aeb5SAlexandre Ganea     ThreadPool CodegenThreadPool(hardware_concurrency(OSs.size()));
57d84c7decSTeresa Johnson     int ThreadCount = 0;
58d84c7decSTeresa Johnson 
59d84c7decSTeresa Johnson     SplitModule(
60*f3a710caSFlorian Hahn         M, OSs.size(),
61d84c7decSTeresa Johnson         [&](std::unique_ptr<Module> MPart) {
62d84c7decSTeresa Johnson           // We want to clone the module in a new context to multi-thread the
63d84c7decSTeresa Johnson           // codegen. We do it by serializing partition modules to bitcode
64d84c7decSTeresa Johnson           // (while still on the main thread, in order to avoid data races) and
65d84c7decSTeresa Johnson           // spinning up new threads which deserialize the partitions into
66d84c7decSTeresa Johnson           // separate contexts.
67c269ed51SPeter Collingbourne           // FIXME: Provide a more direct way to do this in LLVM.
68caa11696SDavide Italiano           SmallString<0> BC;
69c269ed51SPeter Collingbourne           raw_svector_ostream BCOS(BC);
706a86e25dSRafael Espindola           WriteBitcodeToFile(*MPart, BCOS);
71c269ed51SPeter Collingbourne 
72268826a2SEvgeniy Stepanov           if (!BCOSs.empty()) {
73268826a2SEvgeniy Stepanov             BCOSs[ThreadCount]->write(BC.begin(), BC.size());
74268826a2SEvgeniy Stepanov             BCOSs[ThreadCount]->flush();
75268826a2SEvgeniy Stepanov           }
76268826a2SEvgeniy Stepanov 
77d84c7decSTeresa Johnson           llvm::raw_pwrite_stream *ThreadOS = OSs[ThreadCount++];
78d84c7decSTeresa Johnson           // Enqueue the task
79d84c7decSTeresa Johnson           CodegenThreadPool.async(
80caa11696SDavide Italiano               [TMFactory, FileType, ThreadOS](const SmallString<0> &BC) {
81c269ed51SPeter Collingbourne                 LLVMContext Ctx;
82d9445c49SPeter Collingbourne                 Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
83d84c7decSTeresa Johnson                     MemoryBufferRef(StringRef(BC.data(), BC.size()),
84c269ed51SPeter Collingbourne                                     "<split-module>"),
85c269ed51SPeter Collingbourne                     Ctx);
86c269ed51SPeter Collingbourne                 if (!MOrErr)
87c269ed51SPeter Collingbourne                   report_fatal_error("Failed to read bitcode");
88c269ed51SPeter Collingbourne                 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
89c269ed51SPeter Collingbourne 
907950b129SDavide Italiano                 codegen(MPartInCtx.get(), *ThreadOS, TMFactory, FileType);
91c269ed51SPeter Collingbourne               },
92c269ed51SPeter Collingbourne               // Pass BC using std::move to ensure that it get moved rather than
93c269ed51SPeter Collingbourne               // copied into the thread's context.
94c269ed51SPeter Collingbourne               std::move(BC));
95d84c7decSTeresa Johnson         },
96d84c7decSTeresa Johnson         PreserveLocals);
97d84c7decSTeresa Johnson   }
98c269ed51SPeter Collingbourne }
99