xref: /aosp_15_r20/external/llvm/tools/gold/gold-plugin.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization  ------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This is a gold plugin for LLVM. It provides an LLVM implementation of the
11*9880d681SAndroid Build Coastguard Worker // interface described in http://gcc.gnu.org/wiki/whopr/driver .
12*9880d681SAndroid Build Coastguard Worker //
13*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
14*9880d681SAndroid Build Coastguard Worker 
15*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/StringSet.h"
16*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetLibraryInfo.h"
17*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetTransformInfo.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/Bitcode/ReaderWriter.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/Analysis.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/CommandFlags.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/CodeGen/ParallelCG.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
23*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/AutoUpgrade.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Constants.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DiagnosticInfo.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DiagnosticPrinter.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LLVMContext.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LegacyPassManager.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Module.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Verifier.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/LTO/LTO.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/Linker/IRMover.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/MC/SubtargetFeature.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/Object/IRObjectFile.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
36*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Host.h"
37*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/ManagedStatic.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/MemoryBuffer.h"
39*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Path.h"
40*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/TargetRegistry.h"
41*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/TargetSelect.h"
42*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/ThreadPool.h"
43*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
44*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/thread.h"
45*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/IPO.h"
46*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/IPO/FunctionImport.h"
47*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/IPO/PassManagerBuilder.h"
48*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/FunctionImportUtils.h"
49*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/GlobalStatus.h"
50*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/ValueMapper.h"
51*9880d681SAndroid Build Coastguard Worker #include <list>
52*9880d681SAndroid Build Coastguard Worker #include <plugin-api.h>
53*9880d681SAndroid Build Coastguard Worker #include <system_error>
54*9880d681SAndroid Build Coastguard Worker #include <utility>
55*9880d681SAndroid Build Coastguard Worker #include <vector>
56*9880d681SAndroid Build Coastguard Worker 
57*9880d681SAndroid Build Coastguard Worker // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
58*9880d681SAndroid Build Coastguard Worker // Precise and Debian Wheezy (binutils 2.23 is required)
59*9880d681SAndroid Build Coastguard Worker #define LDPO_PIE 3
60*9880d681SAndroid Build Coastguard Worker 
61*9880d681SAndroid Build Coastguard Worker #define LDPT_GET_SYMBOLS_V3 28
62*9880d681SAndroid Build Coastguard Worker 
63*9880d681SAndroid Build Coastguard Worker using namespace llvm;
64*9880d681SAndroid Build Coastguard Worker 
discard_message(int level,const char * format,...)65*9880d681SAndroid Build Coastguard Worker static ld_plugin_status discard_message(int level, const char *format, ...) {
66*9880d681SAndroid Build Coastguard Worker   // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
67*9880d681SAndroid Build Coastguard Worker   // callback in the transfer vector. This should never be called.
68*9880d681SAndroid Build Coastguard Worker   abort();
69*9880d681SAndroid Build Coastguard Worker }
70*9880d681SAndroid Build Coastguard Worker 
71*9880d681SAndroid Build Coastguard Worker static ld_plugin_release_input_file release_input_file = nullptr;
72*9880d681SAndroid Build Coastguard Worker static ld_plugin_get_input_file get_input_file = nullptr;
73*9880d681SAndroid Build Coastguard Worker static ld_plugin_message message = discard_message;
74*9880d681SAndroid Build Coastguard Worker 
75*9880d681SAndroid Build Coastguard Worker namespace {
76*9880d681SAndroid Build Coastguard Worker struct claimed_file {
77*9880d681SAndroid Build Coastguard Worker   void *handle;
78*9880d681SAndroid Build Coastguard Worker   void *leader_handle;
79*9880d681SAndroid Build Coastguard Worker   std::vector<ld_plugin_symbol> syms;
80*9880d681SAndroid Build Coastguard Worker   off_t filesize;
81*9880d681SAndroid Build Coastguard Worker   std::string name;
82*9880d681SAndroid Build Coastguard Worker };
83*9880d681SAndroid Build Coastguard Worker 
84*9880d681SAndroid Build Coastguard Worker /// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
85*9880d681SAndroid Build Coastguard Worker struct PluginInputFile {
86*9880d681SAndroid Build Coastguard Worker   void *Handle;
87*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<ld_plugin_input_file> File;
88*9880d681SAndroid Build Coastguard Worker 
PluginInputFile__anon910d33990111::PluginInputFile89*9880d681SAndroid Build Coastguard Worker   PluginInputFile(void *Handle) : Handle(Handle) {
90*9880d681SAndroid Build Coastguard Worker     File = llvm::make_unique<ld_plugin_input_file>();
91*9880d681SAndroid Build Coastguard Worker     if (get_input_file(Handle, File.get()) != LDPS_OK)
92*9880d681SAndroid Build Coastguard Worker       message(LDPL_FATAL, "Failed to get file information");
93*9880d681SAndroid Build Coastguard Worker   }
~PluginInputFile__anon910d33990111::PluginInputFile94*9880d681SAndroid Build Coastguard Worker   ~PluginInputFile() {
95*9880d681SAndroid Build Coastguard Worker     // File would have been reset to nullptr if we moved this object
96*9880d681SAndroid Build Coastguard Worker     // to a new owner.
97*9880d681SAndroid Build Coastguard Worker     if (File)
98*9880d681SAndroid Build Coastguard Worker       if (release_input_file(Handle) != LDPS_OK)
99*9880d681SAndroid Build Coastguard Worker         message(LDPL_FATAL, "Failed to release file information");
100*9880d681SAndroid Build Coastguard Worker   }
101*9880d681SAndroid Build Coastguard Worker 
file__anon910d33990111::PluginInputFile102*9880d681SAndroid Build Coastguard Worker   ld_plugin_input_file &file() { return *File; }
103*9880d681SAndroid Build Coastguard Worker 
104*9880d681SAndroid Build Coastguard Worker   PluginInputFile(PluginInputFile &&RHS) = default;
105*9880d681SAndroid Build Coastguard Worker   PluginInputFile &operator=(PluginInputFile &&RHS) = default;
106*9880d681SAndroid Build Coastguard Worker };
107*9880d681SAndroid Build Coastguard Worker 
108*9880d681SAndroid Build Coastguard Worker struct ResolutionInfo {
109*9880d681SAndroid Build Coastguard Worker   uint64_t CommonSize = 0;
110*9880d681SAndroid Build Coastguard Worker   unsigned CommonAlign = 0;
111*9880d681SAndroid Build Coastguard Worker   bool IsLinkonceOdr = true;
112*9880d681SAndroid Build Coastguard Worker   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::Global;
113*9880d681SAndroid Build Coastguard Worker   GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
114*9880d681SAndroid Build Coastguard Worker   bool CommonInternal = false;
115*9880d681SAndroid Build Coastguard Worker   bool UseCommon = false;
116*9880d681SAndroid Build Coastguard Worker };
117*9880d681SAndroid Build Coastguard Worker 
118*9880d681SAndroid Build Coastguard Worker /// Class to own information used by a task or during its cleanup for a
119*9880d681SAndroid Build Coastguard Worker /// ThinLTO backend instantiation.
120*9880d681SAndroid Build Coastguard Worker class ThinLTOTaskInfo {
121*9880d681SAndroid Build Coastguard Worker   /// The output stream the task will codegen into.
122*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<raw_fd_ostream> OS;
123*9880d681SAndroid Build Coastguard Worker 
124*9880d681SAndroid Build Coastguard Worker   /// The file name corresponding to the output stream, used during cleanup.
125*9880d681SAndroid Build Coastguard Worker   std::string Filename;
126*9880d681SAndroid Build Coastguard Worker 
127*9880d681SAndroid Build Coastguard Worker   /// Flag indicating whether the output file is a temp file that must be
128*9880d681SAndroid Build Coastguard Worker   /// added to the cleanup list during cleanup.
129*9880d681SAndroid Build Coastguard Worker   bool TempOutFile;
130*9880d681SAndroid Build Coastguard Worker 
131*9880d681SAndroid Build Coastguard Worker public:
ThinLTOTaskInfo(std::unique_ptr<raw_fd_ostream> OS,std::string Filename,bool TempOutFile)132*9880d681SAndroid Build Coastguard Worker   ThinLTOTaskInfo(std::unique_ptr<raw_fd_ostream> OS, std::string Filename,
133*9880d681SAndroid Build Coastguard Worker                   bool TempOutFile)
134*9880d681SAndroid Build Coastguard Worker       : OS(std::move(OS)), Filename(std::move(Filename)),
135*9880d681SAndroid Build Coastguard Worker         TempOutFile(TempOutFile) {}
136*9880d681SAndroid Build Coastguard Worker 
137*9880d681SAndroid Build Coastguard Worker   /// Performs task related cleanup activities that must be done
138*9880d681SAndroid Build Coastguard Worker   /// single-threaded (i.e. call backs to gold).
139*9880d681SAndroid Build Coastguard Worker   void cleanup();
140*9880d681SAndroid Build Coastguard Worker };
141*9880d681SAndroid Build Coastguard Worker }
142*9880d681SAndroid Build Coastguard Worker 
143*9880d681SAndroid Build Coastguard Worker static ld_plugin_add_symbols add_symbols = nullptr;
144*9880d681SAndroid Build Coastguard Worker static ld_plugin_get_symbols get_symbols = nullptr;
145*9880d681SAndroid Build Coastguard Worker static ld_plugin_add_input_file add_input_file = nullptr;
146*9880d681SAndroid Build Coastguard Worker static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
147*9880d681SAndroid Build Coastguard Worker static ld_plugin_get_view get_view = nullptr;
148*9880d681SAndroid Build Coastguard Worker static Optional<Reloc::Model> RelocationModel;
149*9880d681SAndroid Build Coastguard Worker static std::string output_name = "";
150*9880d681SAndroid Build Coastguard Worker static std::list<claimed_file> Modules;
151*9880d681SAndroid Build Coastguard Worker static DenseMap<int, void *> FDToLeaderHandle;
152*9880d681SAndroid Build Coastguard Worker static StringMap<ResolutionInfo> ResInfo;
153*9880d681SAndroid Build Coastguard Worker static std::vector<std::string> Cleanup;
154*9880d681SAndroid Build Coastguard Worker static llvm::TargetOptions TargetOpts;
155*9880d681SAndroid Build Coastguard Worker static std::string DefaultTriple = sys::getDefaultTargetTriple();
156*9880d681SAndroid Build Coastguard Worker 
157*9880d681SAndroid Build Coastguard Worker namespace options {
158*9880d681SAndroid Build Coastguard Worker   enum OutputType {
159*9880d681SAndroid Build Coastguard Worker     OT_NORMAL,
160*9880d681SAndroid Build Coastguard Worker     OT_DISABLE,
161*9880d681SAndroid Build Coastguard Worker     OT_BC_ONLY,
162*9880d681SAndroid Build Coastguard Worker     OT_SAVE_TEMPS
163*9880d681SAndroid Build Coastguard Worker   };
164*9880d681SAndroid Build Coastguard Worker   static bool generate_api_file = false;
165*9880d681SAndroid Build Coastguard Worker   static OutputType TheOutputType = OT_NORMAL;
166*9880d681SAndroid Build Coastguard Worker   static unsigned OptLevel = 2;
167*9880d681SAndroid Build Coastguard Worker   // Default parallelism of 0 used to indicate that user did not specify.
168*9880d681SAndroid Build Coastguard Worker   // Actual parallelism default value depends on implementation.
169*9880d681SAndroid Build Coastguard Worker   // Currently, code generation defaults to no parallelism, whereas
170*9880d681SAndroid Build Coastguard Worker   // ThinLTO uses the hardware_concurrency as the default.
171*9880d681SAndroid Build Coastguard Worker   static unsigned Parallelism = 0;
172*9880d681SAndroid Build Coastguard Worker #ifdef NDEBUG
173*9880d681SAndroid Build Coastguard Worker   static bool DisableVerify = true;
174*9880d681SAndroid Build Coastguard Worker #else
175*9880d681SAndroid Build Coastguard Worker   static bool DisableVerify = false;
176*9880d681SAndroid Build Coastguard Worker #endif
177*9880d681SAndroid Build Coastguard Worker   static std::string obj_path;
178*9880d681SAndroid Build Coastguard Worker   static std::string extra_library_path;
179*9880d681SAndroid Build Coastguard Worker   static std::string triple;
180*9880d681SAndroid Build Coastguard Worker   static std::string mcpu;
181*9880d681SAndroid Build Coastguard Worker   // When the thinlto plugin option is specified, only read the function
182*9880d681SAndroid Build Coastguard Worker   // the information from intermediate files and write a combined
183*9880d681SAndroid Build Coastguard Worker   // global index for the ThinLTO backends.
184*9880d681SAndroid Build Coastguard Worker   static bool thinlto = false;
185*9880d681SAndroid Build Coastguard Worker   // If false, all ThinLTO backend compilations through code gen are performed
186*9880d681SAndroid Build Coastguard Worker   // using multiple threads in the gold-plugin, before handing control back to
187*9880d681SAndroid Build Coastguard Worker   // gold. If true, write individual backend index files which reflect
188*9880d681SAndroid Build Coastguard Worker   // the import decisions, and exit afterwards. The assumption is
189*9880d681SAndroid Build Coastguard Worker   // that the build system will launch the backend processes.
190*9880d681SAndroid Build Coastguard Worker   static bool thinlto_index_only = false;
191*9880d681SAndroid Build Coastguard Worker   // If true, when generating individual index files for distributed backends,
192*9880d681SAndroid Build Coastguard Worker   // also generate a "${bitcodefile}.imports" file at the same location for each
193*9880d681SAndroid Build Coastguard Worker   // bitcode file, listing the files it imports from in plain text. This is to
194*9880d681SAndroid Build Coastguard Worker   // support distributed build file staging.
195*9880d681SAndroid Build Coastguard Worker   static bool thinlto_emit_imports_files = false;
196*9880d681SAndroid Build Coastguard Worker   // Option to control where files for a distributed backend (the individual
197*9880d681SAndroid Build Coastguard Worker   // index files and optional imports files) are created.
198*9880d681SAndroid Build Coastguard Worker   // If specified, expects a string of the form "oldprefix:newprefix", and
199*9880d681SAndroid Build Coastguard Worker   // instead of generating these files in the same directory path as the
200*9880d681SAndroid Build Coastguard Worker   // corresponding bitcode file, will use a path formed by replacing the
201*9880d681SAndroid Build Coastguard Worker   // bitcode file's path prefix matching oldprefix with newprefix.
202*9880d681SAndroid Build Coastguard Worker   static std::string thinlto_prefix_replace;
203*9880d681SAndroid Build Coastguard Worker   // Additional options to pass into the code generator.
204*9880d681SAndroid Build Coastguard Worker   // Note: This array will contain all plugin options which are not claimed
205*9880d681SAndroid Build Coastguard Worker   // as plugin exclusive to pass to the code generator.
206*9880d681SAndroid Build Coastguard Worker   // For example, "generate-api-file" and "as"options are for the plugin
207*9880d681SAndroid Build Coastguard Worker   // use only and will not be passed.
208*9880d681SAndroid Build Coastguard Worker   static std::vector<const char *> extra;
209*9880d681SAndroid Build Coastguard Worker 
process_plugin_option(const char * opt_)210*9880d681SAndroid Build Coastguard Worker   static void process_plugin_option(const char *opt_)
211*9880d681SAndroid Build Coastguard Worker   {
212*9880d681SAndroid Build Coastguard Worker     if (opt_ == nullptr)
213*9880d681SAndroid Build Coastguard Worker       return;
214*9880d681SAndroid Build Coastguard Worker     llvm::StringRef opt = opt_;
215*9880d681SAndroid Build Coastguard Worker 
216*9880d681SAndroid Build Coastguard Worker     if (opt == "generate-api-file") {
217*9880d681SAndroid Build Coastguard Worker       generate_api_file = true;
218*9880d681SAndroid Build Coastguard Worker     } else if (opt.startswith("mcpu=")) {
219*9880d681SAndroid Build Coastguard Worker       mcpu = opt.substr(strlen("mcpu="));
220*9880d681SAndroid Build Coastguard Worker     } else if (opt.startswith("extra-library-path=")) {
221*9880d681SAndroid Build Coastguard Worker       extra_library_path = opt.substr(strlen("extra_library_path="));
222*9880d681SAndroid Build Coastguard Worker     } else if (opt.startswith("mtriple=")) {
223*9880d681SAndroid Build Coastguard Worker       triple = opt.substr(strlen("mtriple="));
224*9880d681SAndroid Build Coastguard Worker     } else if (opt.startswith("obj-path=")) {
225*9880d681SAndroid Build Coastguard Worker       obj_path = opt.substr(strlen("obj-path="));
226*9880d681SAndroid Build Coastguard Worker     } else if (opt == "emit-llvm") {
227*9880d681SAndroid Build Coastguard Worker       TheOutputType = OT_BC_ONLY;
228*9880d681SAndroid Build Coastguard Worker     } else if (opt == "save-temps") {
229*9880d681SAndroid Build Coastguard Worker       TheOutputType = OT_SAVE_TEMPS;
230*9880d681SAndroid Build Coastguard Worker     } else if (opt == "disable-output") {
231*9880d681SAndroid Build Coastguard Worker       TheOutputType = OT_DISABLE;
232*9880d681SAndroid Build Coastguard Worker     } else if (opt == "thinlto") {
233*9880d681SAndroid Build Coastguard Worker       thinlto = true;
234*9880d681SAndroid Build Coastguard Worker     } else if (opt == "thinlto-index-only") {
235*9880d681SAndroid Build Coastguard Worker       thinlto_index_only = true;
236*9880d681SAndroid Build Coastguard Worker     } else if (opt == "thinlto-emit-imports-files") {
237*9880d681SAndroid Build Coastguard Worker       thinlto_emit_imports_files = true;
238*9880d681SAndroid Build Coastguard Worker     } else if (opt.startswith("thinlto-prefix-replace=")) {
239*9880d681SAndroid Build Coastguard Worker       thinlto_prefix_replace = opt.substr(strlen("thinlto-prefix-replace="));
240*9880d681SAndroid Build Coastguard Worker       if (thinlto_prefix_replace.find(";") == std::string::npos)
241*9880d681SAndroid Build Coastguard Worker         message(LDPL_FATAL, "thinlto-prefix-replace expects 'old;new' format");
242*9880d681SAndroid Build Coastguard Worker     } else if (opt.size() == 2 && opt[0] == 'O') {
243*9880d681SAndroid Build Coastguard Worker       if (opt[1] < '0' || opt[1] > '3')
244*9880d681SAndroid Build Coastguard Worker         message(LDPL_FATAL, "Optimization level must be between 0 and 3");
245*9880d681SAndroid Build Coastguard Worker       OptLevel = opt[1] - '0';
246*9880d681SAndroid Build Coastguard Worker     } else if (opt.startswith("jobs=")) {
247*9880d681SAndroid Build Coastguard Worker       if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
248*9880d681SAndroid Build Coastguard Worker         message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
249*9880d681SAndroid Build Coastguard Worker     } else if (opt == "disable-verify") {
250*9880d681SAndroid Build Coastguard Worker       DisableVerify = true;
251*9880d681SAndroid Build Coastguard Worker     } else {
252*9880d681SAndroid Build Coastguard Worker       // Save this option to pass to the code generator.
253*9880d681SAndroid Build Coastguard Worker       // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
254*9880d681SAndroid Build Coastguard Worker       // add that.
255*9880d681SAndroid Build Coastguard Worker       if (extra.empty())
256*9880d681SAndroid Build Coastguard Worker         extra.push_back("LLVMgold");
257*9880d681SAndroid Build Coastguard Worker 
258*9880d681SAndroid Build Coastguard Worker       extra.push_back(opt_);
259*9880d681SAndroid Build Coastguard Worker     }
260*9880d681SAndroid Build Coastguard Worker   }
261*9880d681SAndroid Build Coastguard Worker }
262*9880d681SAndroid Build Coastguard Worker 
263*9880d681SAndroid Build Coastguard Worker static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
264*9880d681SAndroid Build Coastguard Worker                                         int *claimed);
265*9880d681SAndroid Build Coastguard Worker static ld_plugin_status all_symbols_read_hook(void);
266*9880d681SAndroid Build Coastguard Worker static ld_plugin_status cleanup_hook(void);
267*9880d681SAndroid Build Coastguard Worker 
268*9880d681SAndroid Build Coastguard Worker extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
onload(ld_plugin_tv * tv)269*9880d681SAndroid Build Coastguard Worker ld_plugin_status onload(ld_plugin_tv *tv) {
270*9880d681SAndroid Build Coastguard Worker   InitializeAllTargetInfos();
271*9880d681SAndroid Build Coastguard Worker   InitializeAllTargets();
272*9880d681SAndroid Build Coastguard Worker   InitializeAllTargetMCs();
273*9880d681SAndroid Build Coastguard Worker   InitializeAllAsmParsers();
274*9880d681SAndroid Build Coastguard Worker   InitializeAllAsmPrinters();
275*9880d681SAndroid Build Coastguard Worker 
276*9880d681SAndroid Build Coastguard Worker   // We're given a pointer to the first transfer vector. We read through them
277*9880d681SAndroid Build Coastguard Worker   // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
278*9880d681SAndroid Build Coastguard Worker   // contain pointers to functions that we need to call to register our own
279*9880d681SAndroid Build Coastguard Worker   // hooks. The others are addresses of functions we can use to call into gold
280*9880d681SAndroid Build Coastguard Worker   // for services.
281*9880d681SAndroid Build Coastguard Worker 
282*9880d681SAndroid Build Coastguard Worker   bool registeredClaimFile = false;
283*9880d681SAndroid Build Coastguard Worker   bool RegisteredAllSymbolsRead = false;
284*9880d681SAndroid Build Coastguard Worker 
285*9880d681SAndroid Build Coastguard Worker   for (; tv->tv_tag != LDPT_NULL; ++tv) {
286*9880d681SAndroid Build Coastguard Worker     // Cast tv_tag to int to allow values not in "enum ld_plugin_tag", like, for
287*9880d681SAndroid Build Coastguard Worker     // example, LDPT_GET_SYMBOLS_V3 when building against an older plugin-api.h
288*9880d681SAndroid Build Coastguard Worker     // header.
289*9880d681SAndroid Build Coastguard Worker     switch (static_cast<int>(tv->tv_tag)) {
290*9880d681SAndroid Build Coastguard Worker     case LDPT_OUTPUT_NAME:
291*9880d681SAndroid Build Coastguard Worker       output_name = tv->tv_u.tv_string;
292*9880d681SAndroid Build Coastguard Worker       break;
293*9880d681SAndroid Build Coastguard Worker     case LDPT_LINKER_OUTPUT:
294*9880d681SAndroid Build Coastguard Worker       switch (tv->tv_u.tv_val) {
295*9880d681SAndroid Build Coastguard Worker       case LDPO_REL: // .o
296*9880d681SAndroid Build Coastguard Worker       case LDPO_DYN: // .so
297*9880d681SAndroid Build Coastguard Worker       case LDPO_PIE: // position independent executable
298*9880d681SAndroid Build Coastguard Worker         RelocationModel = Reloc::PIC_;
299*9880d681SAndroid Build Coastguard Worker         break;
300*9880d681SAndroid Build Coastguard Worker       case LDPO_EXEC: // .exe
301*9880d681SAndroid Build Coastguard Worker         RelocationModel = Reloc::Static;
302*9880d681SAndroid Build Coastguard Worker         break;
303*9880d681SAndroid Build Coastguard Worker       default:
304*9880d681SAndroid Build Coastguard Worker         message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
305*9880d681SAndroid Build Coastguard Worker         return LDPS_ERR;
306*9880d681SAndroid Build Coastguard Worker       }
307*9880d681SAndroid Build Coastguard Worker       break;
308*9880d681SAndroid Build Coastguard Worker     case LDPT_OPTION:
309*9880d681SAndroid Build Coastguard Worker       options::process_plugin_option(tv->tv_u.tv_string);
310*9880d681SAndroid Build Coastguard Worker       break;
311*9880d681SAndroid Build Coastguard Worker     case LDPT_REGISTER_CLAIM_FILE_HOOK: {
312*9880d681SAndroid Build Coastguard Worker       ld_plugin_register_claim_file callback;
313*9880d681SAndroid Build Coastguard Worker       callback = tv->tv_u.tv_register_claim_file;
314*9880d681SAndroid Build Coastguard Worker 
315*9880d681SAndroid Build Coastguard Worker       if (callback(claim_file_hook) != LDPS_OK)
316*9880d681SAndroid Build Coastguard Worker         return LDPS_ERR;
317*9880d681SAndroid Build Coastguard Worker 
318*9880d681SAndroid Build Coastguard Worker       registeredClaimFile = true;
319*9880d681SAndroid Build Coastguard Worker     } break;
320*9880d681SAndroid Build Coastguard Worker     case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
321*9880d681SAndroid Build Coastguard Worker       ld_plugin_register_all_symbols_read callback;
322*9880d681SAndroid Build Coastguard Worker       callback = tv->tv_u.tv_register_all_symbols_read;
323*9880d681SAndroid Build Coastguard Worker 
324*9880d681SAndroid Build Coastguard Worker       if (callback(all_symbols_read_hook) != LDPS_OK)
325*9880d681SAndroid Build Coastguard Worker         return LDPS_ERR;
326*9880d681SAndroid Build Coastguard Worker 
327*9880d681SAndroid Build Coastguard Worker       RegisteredAllSymbolsRead = true;
328*9880d681SAndroid Build Coastguard Worker     } break;
329*9880d681SAndroid Build Coastguard Worker     case LDPT_REGISTER_CLEANUP_HOOK: {
330*9880d681SAndroid Build Coastguard Worker       ld_plugin_register_cleanup callback;
331*9880d681SAndroid Build Coastguard Worker       callback = tv->tv_u.tv_register_cleanup;
332*9880d681SAndroid Build Coastguard Worker 
333*9880d681SAndroid Build Coastguard Worker       if (callback(cleanup_hook) != LDPS_OK)
334*9880d681SAndroid Build Coastguard Worker         return LDPS_ERR;
335*9880d681SAndroid Build Coastguard Worker     } break;
336*9880d681SAndroid Build Coastguard Worker     case LDPT_GET_INPUT_FILE:
337*9880d681SAndroid Build Coastguard Worker       get_input_file = tv->tv_u.tv_get_input_file;
338*9880d681SAndroid Build Coastguard Worker       break;
339*9880d681SAndroid Build Coastguard Worker     case LDPT_RELEASE_INPUT_FILE:
340*9880d681SAndroid Build Coastguard Worker       release_input_file = tv->tv_u.tv_release_input_file;
341*9880d681SAndroid Build Coastguard Worker       break;
342*9880d681SAndroid Build Coastguard Worker     case LDPT_ADD_SYMBOLS:
343*9880d681SAndroid Build Coastguard Worker       add_symbols = tv->tv_u.tv_add_symbols;
344*9880d681SAndroid Build Coastguard Worker       break;
345*9880d681SAndroid Build Coastguard Worker     case LDPT_GET_SYMBOLS_V2:
346*9880d681SAndroid Build Coastguard Worker       // Do not override get_symbols_v3 with get_symbols_v2.
347*9880d681SAndroid Build Coastguard Worker       if (!get_symbols)
348*9880d681SAndroid Build Coastguard Worker         get_symbols = tv->tv_u.tv_get_symbols;
349*9880d681SAndroid Build Coastguard Worker       break;
350*9880d681SAndroid Build Coastguard Worker     case LDPT_GET_SYMBOLS_V3:
351*9880d681SAndroid Build Coastguard Worker       get_symbols = tv->tv_u.tv_get_symbols;
352*9880d681SAndroid Build Coastguard Worker       break;
353*9880d681SAndroid Build Coastguard Worker     case LDPT_ADD_INPUT_FILE:
354*9880d681SAndroid Build Coastguard Worker       add_input_file = tv->tv_u.tv_add_input_file;
355*9880d681SAndroid Build Coastguard Worker       break;
356*9880d681SAndroid Build Coastguard Worker     case LDPT_SET_EXTRA_LIBRARY_PATH:
357*9880d681SAndroid Build Coastguard Worker       set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
358*9880d681SAndroid Build Coastguard Worker       break;
359*9880d681SAndroid Build Coastguard Worker     case LDPT_GET_VIEW:
360*9880d681SAndroid Build Coastguard Worker       get_view = tv->tv_u.tv_get_view;
361*9880d681SAndroid Build Coastguard Worker       break;
362*9880d681SAndroid Build Coastguard Worker     case LDPT_MESSAGE:
363*9880d681SAndroid Build Coastguard Worker       message = tv->tv_u.tv_message;
364*9880d681SAndroid Build Coastguard Worker       break;
365*9880d681SAndroid Build Coastguard Worker     default:
366*9880d681SAndroid Build Coastguard Worker       break;
367*9880d681SAndroid Build Coastguard Worker     }
368*9880d681SAndroid Build Coastguard Worker   }
369*9880d681SAndroid Build Coastguard Worker 
370*9880d681SAndroid Build Coastguard Worker   if (!registeredClaimFile) {
371*9880d681SAndroid Build Coastguard Worker     message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
372*9880d681SAndroid Build Coastguard Worker     return LDPS_ERR;
373*9880d681SAndroid Build Coastguard Worker   }
374*9880d681SAndroid Build Coastguard Worker   if (!add_symbols) {
375*9880d681SAndroid Build Coastguard Worker     message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
376*9880d681SAndroid Build Coastguard Worker     return LDPS_ERR;
377*9880d681SAndroid Build Coastguard Worker   }
378*9880d681SAndroid Build Coastguard Worker 
379*9880d681SAndroid Build Coastguard Worker   if (!RegisteredAllSymbolsRead)
380*9880d681SAndroid Build Coastguard Worker     return LDPS_OK;
381*9880d681SAndroid Build Coastguard Worker 
382*9880d681SAndroid Build Coastguard Worker   if (!get_input_file) {
383*9880d681SAndroid Build Coastguard Worker     message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
384*9880d681SAndroid Build Coastguard Worker     return LDPS_ERR;
385*9880d681SAndroid Build Coastguard Worker   }
386*9880d681SAndroid Build Coastguard Worker   if (!release_input_file) {
387*9880d681SAndroid Build Coastguard Worker     message(LDPL_ERROR, "release_input_file not passed to LLVMgold.");
388*9880d681SAndroid Build Coastguard Worker     return LDPS_ERR;
389*9880d681SAndroid Build Coastguard Worker   }
390*9880d681SAndroid Build Coastguard Worker 
391*9880d681SAndroid Build Coastguard Worker   return LDPS_OK;
392*9880d681SAndroid Build Coastguard Worker }
393*9880d681SAndroid Build Coastguard Worker 
getBaseObject(const GlobalValue & GV)394*9880d681SAndroid Build Coastguard Worker static const GlobalObject *getBaseObject(const GlobalValue &GV) {
395*9880d681SAndroid Build Coastguard Worker   if (auto *GA = dyn_cast<GlobalAlias>(&GV))
396*9880d681SAndroid Build Coastguard Worker     return GA->getBaseObject();
397*9880d681SAndroid Build Coastguard Worker   return cast<GlobalObject>(&GV);
398*9880d681SAndroid Build Coastguard Worker }
399*9880d681SAndroid Build Coastguard Worker 
shouldSkip(uint32_t Symflags)400*9880d681SAndroid Build Coastguard Worker static bool shouldSkip(uint32_t Symflags) {
401*9880d681SAndroid Build Coastguard Worker   if (!(Symflags & object::BasicSymbolRef::SF_Global))
402*9880d681SAndroid Build Coastguard Worker     return true;
403*9880d681SAndroid Build Coastguard Worker   if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
404*9880d681SAndroid Build Coastguard Worker     return true;
405*9880d681SAndroid Build Coastguard Worker   return false;
406*9880d681SAndroid Build Coastguard Worker }
407*9880d681SAndroid Build Coastguard Worker 
diagnosticHandler(const DiagnosticInfo & DI)408*9880d681SAndroid Build Coastguard Worker static void diagnosticHandler(const DiagnosticInfo &DI) {
409*9880d681SAndroid Build Coastguard Worker   if (const auto *BDI = dyn_cast<BitcodeDiagnosticInfo>(&DI)) {
410*9880d681SAndroid Build Coastguard Worker     std::error_code EC = BDI->getError();
411*9880d681SAndroid Build Coastguard Worker     if (EC == BitcodeError::InvalidBitcodeSignature)
412*9880d681SAndroid Build Coastguard Worker       return;
413*9880d681SAndroid Build Coastguard Worker   }
414*9880d681SAndroid Build Coastguard Worker 
415*9880d681SAndroid Build Coastguard Worker   std::string ErrStorage;
416*9880d681SAndroid Build Coastguard Worker   {
417*9880d681SAndroid Build Coastguard Worker     raw_string_ostream OS(ErrStorage);
418*9880d681SAndroid Build Coastguard Worker     DiagnosticPrinterRawOStream DP(OS);
419*9880d681SAndroid Build Coastguard Worker     DI.print(DP);
420*9880d681SAndroid Build Coastguard Worker   }
421*9880d681SAndroid Build Coastguard Worker   ld_plugin_level Level;
422*9880d681SAndroid Build Coastguard Worker   switch (DI.getSeverity()) {
423*9880d681SAndroid Build Coastguard Worker   case DS_Error:
424*9880d681SAndroid Build Coastguard Worker     message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
425*9880d681SAndroid Build Coastguard Worker             ErrStorage.c_str());
426*9880d681SAndroid Build Coastguard Worker   case DS_Warning:
427*9880d681SAndroid Build Coastguard Worker     Level = LDPL_WARNING;
428*9880d681SAndroid Build Coastguard Worker     break;
429*9880d681SAndroid Build Coastguard Worker   case DS_Note:
430*9880d681SAndroid Build Coastguard Worker   case DS_Remark:
431*9880d681SAndroid Build Coastguard Worker     Level = LDPL_INFO;
432*9880d681SAndroid Build Coastguard Worker     break;
433*9880d681SAndroid Build Coastguard Worker   }
434*9880d681SAndroid Build Coastguard Worker   message(Level, "LLVM gold plugin: %s",  ErrStorage.c_str());
435*9880d681SAndroid Build Coastguard Worker }
436*9880d681SAndroid Build Coastguard Worker 
diagnosticHandlerForContext(const DiagnosticInfo & DI,void * Context)437*9880d681SAndroid Build Coastguard Worker static void diagnosticHandlerForContext(const DiagnosticInfo &DI,
438*9880d681SAndroid Build Coastguard Worker                                         void *Context) {
439*9880d681SAndroid Build Coastguard Worker   diagnosticHandler(DI);
440*9880d681SAndroid Build Coastguard Worker }
441*9880d681SAndroid Build Coastguard Worker 
442*9880d681SAndroid Build Coastguard Worker static GlobalValue::VisibilityTypes
getMinVisibility(GlobalValue::VisibilityTypes A,GlobalValue::VisibilityTypes B)443*9880d681SAndroid Build Coastguard Worker getMinVisibility(GlobalValue::VisibilityTypes A,
444*9880d681SAndroid Build Coastguard Worker                  GlobalValue::VisibilityTypes B) {
445*9880d681SAndroid Build Coastguard Worker   if (A == GlobalValue::HiddenVisibility)
446*9880d681SAndroid Build Coastguard Worker     return A;
447*9880d681SAndroid Build Coastguard Worker   if (B == GlobalValue::HiddenVisibility)
448*9880d681SAndroid Build Coastguard Worker     return B;
449*9880d681SAndroid Build Coastguard Worker   if (A == GlobalValue::ProtectedVisibility)
450*9880d681SAndroid Build Coastguard Worker     return A;
451*9880d681SAndroid Build Coastguard Worker   return B;
452*9880d681SAndroid Build Coastguard Worker }
453*9880d681SAndroid Build Coastguard Worker 
454*9880d681SAndroid Build Coastguard Worker /// Called by gold to see whether this file is one that our plugin can handle.
455*9880d681SAndroid Build Coastguard Worker /// We'll try to open it and register all the symbols with add_symbol if
456*9880d681SAndroid Build Coastguard Worker /// possible.
claim_file_hook(const ld_plugin_input_file * file,int * claimed)457*9880d681SAndroid Build Coastguard Worker static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
458*9880d681SAndroid Build Coastguard Worker                                         int *claimed) {
459*9880d681SAndroid Build Coastguard Worker   LLVMContext Context;
460*9880d681SAndroid Build Coastguard Worker   MemoryBufferRef BufferRef;
461*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<MemoryBuffer> Buffer;
462*9880d681SAndroid Build Coastguard Worker   if (get_view) {
463*9880d681SAndroid Build Coastguard Worker     const void *view;
464*9880d681SAndroid Build Coastguard Worker     if (get_view(file->handle, &view) != LDPS_OK) {
465*9880d681SAndroid Build Coastguard Worker       message(LDPL_ERROR, "Failed to get a view of %s", file->name);
466*9880d681SAndroid Build Coastguard Worker       return LDPS_ERR;
467*9880d681SAndroid Build Coastguard Worker     }
468*9880d681SAndroid Build Coastguard Worker     BufferRef =
469*9880d681SAndroid Build Coastguard Worker         MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
470*9880d681SAndroid Build Coastguard Worker   } else {
471*9880d681SAndroid Build Coastguard Worker     int64_t offset = 0;
472*9880d681SAndroid Build Coastguard Worker     // Gold has found what might be IR part-way inside of a file, such as
473*9880d681SAndroid Build Coastguard Worker     // an .a archive.
474*9880d681SAndroid Build Coastguard Worker     if (file->offset) {
475*9880d681SAndroid Build Coastguard Worker       offset = file->offset;
476*9880d681SAndroid Build Coastguard Worker     }
477*9880d681SAndroid Build Coastguard Worker     ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
478*9880d681SAndroid Build Coastguard Worker         MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
479*9880d681SAndroid Build Coastguard Worker                                        offset);
480*9880d681SAndroid Build Coastguard Worker     if (std::error_code EC = BufferOrErr.getError()) {
481*9880d681SAndroid Build Coastguard Worker       message(LDPL_ERROR, EC.message().c_str());
482*9880d681SAndroid Build Coastguard Worker       return LDPS_ERR;
483*9880d681SAndroid Build Coastguard Worker     }
484*9880d681SAndroid Build Coastguard Worker     Buffer = std::move(BufferOrErr.get());
485*9880d681SAndroid Build Coastguard Worker     BufferRef = Buffer->getMemBufferRef();
486*9880d681SAndroid Build Coastguard Worker   }
487*9880d681SAndroid Build Coastguard Worker 
488*9880d681SAndroid Build Coastguard Worker   Context.setDiagnosticHandler(diagnosticHandlerForContext);
489*9880d681SAndroid Build Coastguard Worker   ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
490*9880d681SAndroid Build Coastguard Worker       object::IRObjectFile::create(BufferRef, Context);
491*9880d681SAndroid Build Coastguard Worker   std::error_code EC = ObjOrErr.getError();
492*9880d681SAndroid Build Coastguard Worker   if (EC == object::object_error::invalid_file_type ||
493*9880d681SAndroid Build Coastguard Worker       EC == object::object_error::bitcode_section_not_found)
494*9880d681SAndroid Build Coastguard Worker     return LDPS_OK;
495*9880d681SAndroid Build Coastguard Worker 
496*9880d681SAndroid Build Coastguard Worker   *claimed = 1;
497*9880d681SAndroid Build Coastguard Worker 
498*9880d681SAndroid Build Coastguard Worker   if (EC) {
499*9880d681SAndroid Build Coastguard Worker     message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
500*9880d681SAndroid Build Coastguard Worker             EC.message().c_str());
501*9880d681SAndroid Build Coastguard Worker     return LDPS_ERR;
502*9880d681SAndroid Build Coastguard Worker   }
503*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
504*9880d681SAndroid Build Coastguard Worker 
505*9880d681SAndroid Build Coastguard Worker   Modules.resize(Modules.size() + 1);
506*9880d681SAndroid Build Coastguard Worker   claimed_file &cf = Modules.back();
507*9880d681SAndroid Build Coastguard Worker 
508*9880d681SAndroid Build Coastguard Worker   cf.handle = file->handle;
509*9880d681SAndroid Build Coastguard Worker   // Keep track of the first handle for each file descriptor, since there are
510*9880d681SAndroid Build Coastguard Worker   // multiple in the case of an archive. This is used later in the case of
511*9880d681SAndroid Build Coastguard Worker   // ThinLTO parallel backends to ensure that each file is only opened and
512*9880d681SAndroid Build Coastguard Worker   // released once.
513*9880d681SAndroid Build Coastguard Worker   auto LeaderHandle =
514*9880d681SAndroid Build Coastguard Worker       FDToLeaderHandle.insert(std::make_pair(file->fd, file->handle)).first;
515*9880d681SAndroid Build Coastguard Worker   cf.leader_handle = LeaderHandle->second;
516*9880d681SAndroid Build Coastguard Worker   // Save the filesize since for parallel ThinLTO backends we can only
517*9880d681SAndroid Build Coastguard Worker   // invoke get_input_file once per archive (only for the leader handle).
518*9880d681SAndroid Build Coastguard Worker   cf.filesize = file->filesize;
519*9880d681SAndroid Build Coastguard Worker   // In the case of an archive library, all but the first member must have a
520*9880d681SAndroid Build Coastguard Worker   // non-zero offset, which we can append to the file name to obtain a
521*9880d681SAndroid Build Coastguard Worker   // unique name.
522*9880d681SAndroid Build Coastguard Worker   cf.name = file->name;
523*9880d681SAndroid Build Coastguard Worker   if (file->offset)
524*9880d681SAndroid Build Coastguard Worker     cf.name += ".llvm." + std::to_string(file->offset) + "." +
525*9880d681SAndroid Build Coastguard Worker                sys::path::filename(Obj->getModule().getSourceFileName()).str();
526*9880d681SAndroid Build Coastguard Worker 
527*9880d681SAndroid Build Coastguard Worker   for (auto &Sym : Obj->symbols()) {
528*9880d681SAndroid Build Coastguard Worker     uint32_t Symflags = Sym.getFlags();
529*9880d681SAndroid Build Coastguard Worker     if (shouldSkip(Symflags))
530*9880d681SAndroid Build Coastguard Worker       continue;
531*9880d681SAndroid Build Coastguard Worker 
532*9880d681SAndroid Build Coastguard Worker     cf.syms.push_back(ld_plugin_symbol());
533*9880d681SAndroid Build Coastguard Worker     ld_plugin_symbol &sym = cf.syms.back();
534*9880d681SAndroid Build Coastguard Worker     sym.version = nullptr;
535*9880d681SAndroid Build Coastguard Worker 
536*9880d681SAndroid Build Coastguard Worker     SmallString<64> Name;
537*9880d681SAndroid Build Coastguard Worker     {
538*9880d681SAndroid Build Coastguard Worker       raw_svector_ostream OS(Name);
539*9880d681SAndroid Build Coastguard Worker       Sym.printName(OS);
540*9880d681SAndroid Build Coastguard Worker     }
541*9880d681SAndroid Build Coastguard Worker     sym.name = strdup(Name.c_str());
542*9880d681SAndroid Build Coastguard Worker 
543*9880d681SAndroid Build Coastguard Worker     const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
544*9880d681SAndroid Build Coastguard Worker 
545*9880d681SAndroid Build Coastguard Worker     ResolutionInfo &Res = ResInfo[sym.name];
546*9880d681SAndroid Build Coastguard Worker 
547*9880d681SAndroid Build Coastguard Worker     sym.visibility = LDPV_DEFAULT;
548*9880d681SAndroid Build Coastguard Worker     if (GV) {
549*9880d681SAndroid Build Coastguard Worker       Res.UnnamedAddr =
550*9880d681SAndroid Build Coastguard Worker           GlobalValue::getMinUnnamedAddr(Res.UnnamedAddr, GV->getUnnamedAddr());
551*9880d681SAndroid Build Coastguard Worker       Res.IsLinkonceOdr &= GV->hasLinkOnceLinkage();
552*9880d681SAndroid Build Coastguard Worker       Res.Visibility = getMinVisibility(Res.Visibility, GV->getVisibility());
553*9880d681SAndroid Build Coastguard Worker       switch (GV->getVisibility()) {
554*9880d681SAndroid Build Coastguard Worker       case GlobalValue::DefaultVisibility:
555*9880d681SAndroid Build Coastguard Worker         break;
556*9880d681SAndroid Build Coastguard Worker       case GlobalValue::HiddenVisibility:
557*9880d681SAndroid Build Coastguard Worker         sym.visibility = LDPV_HIDDEN;
558*9880d681SAndroid Build Coastguard Worker         break;
559*9880d681SAndroid Build Coastguard Worker       case GlobalValue::ProtectedVisibility:
560*9880d681SAndroid Build Coastguard Worker         sym.visibility = LDPV_PROTECTED;
561*9880d681SAndroid Build Coastguard Worker         break;
562*9880d681SAndroid Build Coastguard Worker       }
563*9880d681SAndroid Build Coastguard Worker     }
564*9880d681SAndroid Build Coastguard Worker 
565*9880d681SAndroid Build Coastguard Worker     if (Symflags & object::BasicSymbolRef::SF_Undefined) {
566*9880d681SAndroid Build Coastguard Worker       sym.def = LDPK_UNDEF;
567*9880d681SAndroid Build Coastguard Worker       if (GV && GV->hasExternalWeakLinkage())
568*9880d681SAndroid Build Coastguard Worker         sym.def = LDPK_WEAKUNDEF;
569*9880d681SAndroid Build Coastguard Worker     } else {
570*9880d681SAndroid Build Coastguard Worker       sym.def = LDPK_DEF;
571*9880d681SAndroid Build Coastguard Worker       if (GV) {
572*9880d681SAndroid Build Coastguard Worker         assert(!GV->hasExternalWeakLinkage() &&
573*9880d681SAndroid Build Coastguard Worker                !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
574*9880d681SAndroid Build Coastguard Worker         if (GV->hasCommonLinkage())
575*9880d681SAndroid Build Coastguard Worker           sym.def = LDPK_COMMON;
576*9880d681SAndroid Build Coastguard Worker         else if (GV->isWeakForLinker())
577*9880d681SAndroid Build Coastguard Worker           sym.def = LDPK_WEAKDEF;
578*9880d681SAndroid Build Coastguard Worker       }
579*9880d681SAndroid Build Coastguard Worker     }
580*9880d681SAndroid Build Coastguard Worker 
581*9880d681SAndroid Build Coastguard Worker     sym.size = 0;
582*9880d681SAndroid Build Coastguard Worker     sym.comdat_key = nullptr;
583*9880d681SAndroid Build Coastguard Worker     if (GV) {
584*9880d681SAndroid Build Coastguard Worker       const GlobalObject *Base = getBaseObject(*GV);
585*9880d681SAndroid Build Coastguard Worker       if (!Base)
586*9880d681SAndroid Build Coastguard Worker         message(LDPL_FATAL, "Unable to determine comdat of alias!");
587*9880d681SAndroid Build Coastguard Worker       const Comdat *C = Base->getComdat();
588*9880d681SAndroid Build Coastguard Worker       if (C)
589*9880d681SAndroid Build Coastguard Worker         sym.comdat_key = strdup(C->getName().str().c_str());
590*9880d681SAndroid Build Coastguard Worker     }
591*9880d681SAndroid Build Coastguard Worker 
592*9880d681SAndroid Build Coastguard Worker     sym.resolution = LDPR_UNKNOWN;
593*9880d681SAndroid Build Coastguard Worker   }
594*9880d681SAndroid Build Coastguard Worker 
595*9880d681SAndroid Build Coastguard Worker   if (!cf.syms.empty()) {
596*9880d681SAndroid Build Coastguard Worker     if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
597*9880d681SAndroid Build Coastguard Worker       message(LDPL_ERROR, "Unable to add symbols!");
598*9880d681SAndroid Build Coastguard Worker       return LDPS_ERR;
599*9880d681SAndroid Build Coastguard Worker     }
600*9880d681SAndroid Build Coastguard Worker   }
601*9880d681SAndroid Build Coastguard Worker 
602*9880d681SAndroid Build Coastguard Worker   return LDPS_OK;
603*9880d681SAndroid Build Coastguard Worker }
604*9880d681SAndroid Build Coastguard Worker 
internalize(GlobalValue & GV)605*9880d681SAndroid Build Coastguard Worker static void internalize(GlobalValue &GV) {
606*9880d681SAndroid Build Coastguard Worker   if (GV.isDeclarationForLinker())
607*9880d681SAndroid Build Coastguard Worker     return; // We get here if there is a matching asm definition.
608*9880d681SAndroid Build Coastguard Worker   if (!GV.hasLocalLinkage())
609*9880d681SAndroid Build Coastguard Worker     GV.setLinkage(GlobalValue::InternalLinkage);
610*9880d681SAndroid Build Coastguard Worker }
611*9880d681SAndroid Build Coastguard Worker 
getResolutionName(ld_plugin_symbol_resolution R)612*9880d681SAndroid Build Coastguard Worker static const char *getResolutionName(ld_plugin_symbol_resolution R) {
613*9880d681SAndroid Build Coastguard Worker   switch (R) {
614*9880d681SAndroid Build Coastguard Worker   case LDPR_UNKNOWN:
615*9880d681SAndroid Build Coastguard Worker     return "UNKNOWN";
616*9880d681SAndroid Build Coastguard Worker   case LDPR_UNDEF:
617*9880d681SAndroid Build Coastguard Worker     return "UNDEF";
618*9880d681SAndroid Build Coastguard Worker   case LDPR_PREVAILING_DEF:
619*9880d681SAndroid Build Coastguard Worker     return "PREVAILING_DEF";
620*9880d681SAndroid Build Coastguard Worker   case LDPR_PREVAILING_DEF_IRONLY:
621*9880d681SAndroid Build Coastguard Worker     return "PREVAILING_DEF_IRONLY";
622*9880d681SAndroid Build Coastguard Worker   case LDPR_PREEMPTED_REG:
623*9880d681SAndroid Build Coastguard Worker     return "PREEMPTED_REG";
624*9880d681SAndroid Build Coastguard Worker   case LDPR_PREEMPTED_IR:
625*9880d681SAndroid Build Coastguard Worker     return "PREEMPTED_IR";
626*9880d681SAndroid Build Coastguard Worker   case LDPR_RESOLVED_IR:
627*9880d681SAndroid Build Coastguard Worker     return "RESOLVED_IR";
628*9880d681SAndroid Build Coastguard Worker   case LDPR_RESOLVED_EXEC:
629*9880d681SAndroid Build Coastguard Worker     return "RESOLVED_EXEC";
630*9880d681SAndroid Build Coastguard Worker   case LDPR_RESOLVED_DYN:
631*9880d681SAndroid Build Coastguard Worker     return "RESOLVED_DYN";
632*9880d681SAndroid Build Coastguard Worker   case LDPR_PREVAILING_DEF_IRONLY_EXP:
633*9880d681SAndroid Build Coastguard Worker     return "PREVAILING_DEF_IRONLY_EXP";
634*9880d681SAndroid Build Coastguard Worker   }
635*9880d681SAndroid Build Coastguard Worker   llvm_unreachable("Unknown resolution");
636*9880d681SAndroid Build Coastguard Worker }
637*9880d681SAndroid Build Coastguard Worker 
freeSymName(ld_plugin_symbol & Sym)638*9880d681SAndroid Build Coastguard Worker static void freeSymName(ld_plugin_symbol &Sym) {
639*9880d681SAndroid Build Coastguard Worker   free(Sym.name);
640*9880d681SAndroid Build Coastguard Worker   free(Sym.comdat_key);
641*9880d681SAndroid Build Coastguard Worker   Sym.name = nullptr;
642*9880d681SAndroid Build Coastguard Worker   Sym.comdat_key = nullptr;
643*9880d681SAndroid Build Coastguard Worker }
644*9880d681SAndroid Build Coastguard Worker 
645*9880d681SAndroid Build Coastguard Worker /// Helper to get a file's symbols and a view into it via gold callbacks.
getSymbolsAndView(claimed_file & F)646*9880d681SAndroid Build Coastguard Worker static const void *getSymbolsAndView(claimed_file &F) {
647*9880d681SAndroid Build Coastguard Worker   ld_plugin_status status = get_symbols(F.handle, F.syms.size(), F.syms.data());
648*9880d681SAndroid Build Coastguard Worker   if (status == LDPS_NO_SYMS)
649*9880d681SAndroid Build Coastguard Worker     return nullptr;
650*9880d681SAndroid Build Coastguard Worker 
651*9880d681SAndroid Build Coastguard Worker   if (status != LDPS_OK)
652*9880d681SAndroid Build Coastguard Worker     message(LDPL_FATAL, "Failed to get symbol information");
653*9880d681SAndroid Build Coastguard Worker 
654*9880d681SAndroid Build Coastguard Worker   const void *View;
655*9880d681SAndroid Build Coastguard Worker   if (get_view(F.handle, &View) != LDPS_OK)
656*9880d681SAndroid Build Coastguard Worker     message(LDPL_FATAL, "Failed to get a view of file");
657*9880d681SAndroid Build Coastguard Worker 
658*9880d681SAndroid Build Coastguard Worker   return View;
659*9880d681SAndroid Build Coastguard Worker }
660*9880d681SAndroid Build Coastguard Worker 
661*9880d681SAndroid Build Coastguard Worker static std::unique_ptr<ModuleSummaryIndex>
getModuleSummaryIndexForFile(claimed_file & F)662*9880d681SAndroid Build Coastguard Worker getModuleSummaryIndexForFile(claimed_file &F) {
663*9880d681SAndroid Build Coastguard Worker   const void *View = getSymbolsAndView(F);
664*9880d681SAndroid Build Coastguard Worker   if (!View)
665*9880d681SAndroid Build Coastguard Worker     return nullptr;
666*9880d681SAndroid Build Coastguard Worker 
667*9880d681SAndroid Build Coastguard Worker   MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize), F.name);
668*9880d681SAndroid Build Coastguard Worker 
669*9880d681SAndroid Build Coastguard Worker   // Don't bother trying to build an index if there is no summary information
670*9880d681SAndroid Build Coastguard Worker   // in this bitcode file.
671*9880d681SAndroid Build Coastguard Worker   if (!object::ModuleSummaryIndexObjectFile::hasGlobalValueSummaryInMemBuffer(
672*9880d681SAndroid Build Coastguard Worker           BufferRef, diagnosticHandler))
673*9880d681SAndroid Build Coastguard Worker     return std::unique_ptr<ModuleSummaryIndex>(nullptr);
674*9880d681SAndroid Build Coastguard Worker 
675*9880d681SAndroid Build Coastguard Worker   ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
676*9880d681SAndroid Build Coastguard Worker       object::ModuleSummaryIndexObjectFile::create(BufferRef,
677*9880d681SAndroid Build Coastguard Worker                                                    diagnosticHandler);
678*9880d681SAndroid Build Coastguard Worker 
679*9880d681SAndroid Build Coastguard Worker   if (std::error_code EC = ObjOrErr.getError())
680*9880d681SAndroid Build Coastguard Worker     message(LDPL_FATAL,
681*9880d681SAndroid Build Coastguard Worker             "Could not read module summary index bitcode from file : %s",
682*9880d681SAndroid Build Coastguard Worker             EC.message().c_str());
683*9880d681SAndroid Build Coastguard Worker 
684*9880d681SAndroid Build Coastguard Worker   object::ModuleSummaryIndexObjectFile &Obj = **ObjOrErr;
685*9880d681SAndroid Build Coastguard Worker 
686*9880d681SAndroid Build Coastguard Worker   return Obj.takeIndex();
687*9880d681SAndroid Build Coastguard Worker }
688*9880d681SAndroid Build Coastguard Worker 
689*9880d681SAndroid Build Coastguard Worker static std::unique_ptr<Module>
getModuleForFile(LLVMContext & Context,claimed_file & F,const void * View,StringRef Name,raw_fd_ostream * ApiFile,StringSet<> & Internalize,std::vector<GlobalValue * > & Keep,StringMap<unsigned> & Realign)690*9880d681SAndroid Build Coastguard Worker getModuleForFile(LLVMContext &Context, claimed_file &F, const void *View,
691*9880d681SAndroid Build Coastguard Worker                  StringRef Name, raw_fd_ostream *ApiFile,
692*9880d681SAndroid Build Coastguard Worker                  StringSet<> &Internalize, std::vector<GlobalValue *> &Keep,
693*9880d681SAndroid Build Coastguard Worker                  StringMap<unsigned> &Realign) {
694*9880d681SAndroid Build Coastguard Worker   MemoryBufferRef BufferRef(StringRef((const char *)View, F.filesize), Name);
695*9880d681SAndroid Build Coastguard Worker   ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
696*9880d681SAndroid Build Coastguard Worker       object::IRObjectFile::create(BufferRef, Context);
697*9880d681SAndroid Build Coastguard Worker 
698*9880d681SAndroid Build Coastguard Worker   if (std::error_code EC = ObjOrErr.getError())
699*9880d681SAndroid Build Coastguard Worker     message(LDPL_FATAL, "Could not read bitcode from file : %s",
700*9880d681SAndroid Build Coastguard Worker             EC.message().c_str());
701*9880d681SAndroid Build Coastguard Worker 
702*9880d681SAndroid Build Coastguard Worker   object::IRObjectFile &Obj = **ObjOrErr;
703*9880d681SAndroid Build Coastguard Worker 
704*9880d681SAndroid Build Coastguard Worker   Module &M = Obj.getModule();
705*9880d681SAndroid Build Coastguard Worker 
706*9880d681SAndroid Build Coastguard Worker   M.materializeMetadata();
707*9880d681SAndroid Build Coastguard Worker   UpgradeDebugInfo(M);
708*9880d681SAndroid Build Coastguard Worker 
709*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<GlobalValue *, 8> Used;
710*9880d681SAndroid Build Coastguard Worker   collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
711*9880d681SAndroid Build Coastguard Worker 
712*9880d681SAndroid Build Coastguard Worker   unsigned SymNum = 0;
713*9880d681SAndroid Build Coastguard Worker   for (auto &ObjSym : Obj.symbols()) {
714*9880d681SAndroid Build Coastguard Worker     GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
715*9880d681SAndroid Build Coastguard Worker     if (GV && GV->hasAppendingLinkage())
716*9880d681SAndroid Build Coastguard Worker       Keep.push_back(GV);
717*9880d681SAndroid Build Coastguard Worker 
718*9880d681SAndroid Build Coastguard Worker     if (shouldSkip(ObjSym.getFlags()))
719*9880d681SAndroid Build Coastguard Worker       continue;
720*9880d681SAndroid Build Coastguard Worker     ld_plugin_symbol &Sym = F.syms[SymNum];
721*9880d681SAndroid Build Coastguard Worker     ++SymNum;
722*9880d681SAndroid Build Coastguard Worker 
723*9880d681SAndroid Build Coastguard Worker     ld_plugin_symbol_resolution Resolution =
724*9880d681SAndroid Build Coastguard Worker         (ld_plugin_symbol_resolution)Sym.resolution;
725*9880d681SAndroid Build Coastguard Worker 
726*9880d681SAndroid Build Coastguard Worker     if (options::generate_api_file)
727*9880d681SAndroid Build Coastguard Worker       *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
728*9880d681SAndroid Build Coastguard Worker 
729*9880d681SAndroid Build Coastguard Worker     if (!GV) {
730*9880d681SAndroid Build Coastguard Worker       freeSymName(Sym);
731*9880d681SAndroid Build Coastguard Worker       continue; // Asm symbol.
732*9880d681SAndroid Build Coastguard Worker     }
733*9880d681SAndroid Build Coastguard Worker 
734*9880d681SAndroid Build Coastguard Worker     ResolutionInfo &Res = ResInfo[Sym.name];
735*9880d681SAndroid Build Coastguard Worker     if (Resolution == LDPR_PREVAILING_DEF_IRONLY_EXP && !Res.IsLinkonceOdr)
736*9880d681SAndroid Build Coastguard Worker       Resolution = LDPR_PREVAILING_DEF;
737*9880d681SAndroid Build Coastguard Worker 
738*9880d681SAndroid Build Coastguard Worker     GV->setUnnamedAddr(Res.UnnamedAddr);
739*9880d681SAndroid Build Coastguard Worker     GV->setVisibility(Res.Visibility);
740*9880d681SAndroid Build Coastguard Worker 
741*9880d681SAndroid Build Coastguard Worker     // Override gold's resolution for common symbols. We want the largest
742*9880d681SAndroid Build Coastguard Worker     // one to win.
743*9880d681SAndroid Build Coastguard Worker     if (GV->hasCommonLinkage()) {
744*9880d681SAndroid Build Coastguard Worker       if (Resolution == LDPR_PREVAILING_DEF_IRONLY)
745*9880d681SAndroid Build Coastguard Worker         Res.CommonInternal = true;
746*9880d681SAndroid Build Coastguard Worker 
747*9880d681SAndroid Build Coastguard Worker       if (Resolution == LDPR_PREVAILING_DEF_IRONLY ||
748*9880d681SAndroid Build Coastguard Worker           Resolution == LDPR_PREVAILING_DEF)
749*9880d681SAndroid Build Coastguard Worker         Res.UseCommon = true;
750*9880d681SAndroid Build Coastguard Worker 
751*9880d681SAndroid Build Coastguard Worker       const DataLayout &DL = GV->getParent()->getDataLayout();
752*9880d681SAndroid Build Coastguard Worker       uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
753*9880d681SAndroid Build Coastguard Worker       unsigned Align = GV->getAlignment();
754*9880d681SAndroid Build Coastguard Worker 
755*9880d681SAndroid Build Coastguard Worker       if (Res.UseCommon && Size >= Res.CommonSize) {
756*9880d681SAndroid Build Coastguard Worker         // Take GV.
757*9880d681SAndroid Build Coastguard Worker         if (Res.CommonInternal)
758*9880d681SAndroid Build Coastguard Worker           Resolution = LDPR_PREVAILING_DEF_IRONLY;
759*9880d681SAndroid Build Coastguard Worker         else
760*9880d681SAndroid Build Coastguard Worker           Resolution = LDPR_PREVAILING_DEF;
761*9880d681SAndroid Build Coastguard Worker         cast<GlobalVariable>(GV)->setAlignment(
762*9880d681SAndroid Build Coastguard Worker             std::max(Res.CommonAlign, Align));
763*9880d681SAndroid Build Coastguard Worker       } else {
764*9880d681SAndroid Build Coastguard Worker         // Do not take GV, it's smaller than what we already have in the
765*9880d681SAndroid Build Coastguard Worker         // combined module.
766*9880d681SAndroid Build Coastguard Worker         Resolution = LDPR_PREEMPTED_IR;
767*9880d681SAndroid Build Coastguard Worker         if (Align > Res.CommonAlign)
768*9880d681SAndroid Build Coastguard Worker           // Need to raise the alignment though.
769*9880d681SAndroid Build Coastguard Worker           Realign[Sym.name] = Align;
770*9880d681SAndroid Build Coastguard Worker       }
771*9880d681SAndroid Build Coastguard Worker 
772*9880d681SAndroid Build Coastguard Worker       Res.CommonSize = std::max(Res.CommonSize, Size);
773*9880d681SAndroid Build Coastguard Worker       Res.CommonAlign = std::max(Res.CommonAlign, Align);
774*9880d681SAndroid Build Coastguard Worker     }
775*9880d681SAndroid Build Coastguard Worker 
776*9880d681SAndroid Build Coastguard Worker     switch (Resolution) {
777*9880d681SAndroid Build Coastguard Worker     case LDPR_UNKNOWN:
778*9880d681SAndroid Build Coastguard Worker       llvm_unreachable("Unexpected resolution");
779*9880d681SAndroid Build Coastguard Worker 
780*9880d681SAndroid Build Coastguard Worker     case LDPR_RESOLVED_IR:
781*9880d681SAndroid Build Coastguard Worker     case LDPR_RESOLVED_EXEC:
782*9880d681SAndroid Build Coastguard Worker     case LDPR_RESOLVED_DYN:
783*9880d681SAndroid Build Coastguard Worker     case LDPR_PREEMPTED_IR:
784*9880d681SAndroid Build Coastguard Worker     case LDPR_PREEMPTED_REG:
785*9880d681SAndroid Build Coastguard Worker       break;
786*9880d681SAndroid Build Coastguard Worker 
787*9880d681SAndroid Build Coastguard Worker     case LDPR_UNDEF:
788*9880d681SAndroid Build Coastguard Worker       if (!GV->isDeclarationForLinker())
789*9880d681SAndroid Build Coastguard Worker         assert(GV->hasComdat());
790*9880d681SAndroid Build Coastguard Worker       break;
791*9880d681SAndroid Build Coastguard Worker 
792*9880d681SAndroid Build Coastguard Worker     case LDPR_PREVAILING_DEF_IRONLY: {
793*9880d681SAndroid Build Coastguard Worker       Keep.push_back(GV);
794*9880d681SAndroid Build Coastguard Worker       // The IR linker has to be able to map this value to a declaration,
795*9880d681SAndroid Build Coastguard Worker       // so we can only internalize after linking.
796*9880d681SAndroid Build Coastguard Worker       if (!Used.count(GV))
797*9880d681SAndroid Build Coastguard Worker         Internalize.insert(GV->getName());
798*9880d681SAndroid Build Coastguard Worker       break;
799*9880d681SAndroid Build Coastguard Worker     }
800*9880d681SAndroid Build Coastguard Worker 
801*9880d681SAndroid Build Coastguard Worker     case LDPR_PREVAILING_DEF:
802*9880d681SAndroid Build Coastguard Worker       Keep.push_back(GV);
803*9880d681SAndroid Build Coastguard Worker       // There is a non IR use, so we have to force optimizations to keep this.
804*9880d681SAndroid Build Coastguard Worker       switch (GV->getLinkage()) {
805*9880d681SAndroid Build Coastguard Worker       default:
806*9880d681SAndroid Build Coastguard Worker         break;
807*9880d681SAndroid Build Coastguard Worker       case GlobalValue::LinkOnceAnyLinkage:
808*9880d681SAndroid Build Coastguard Worker         GV->setLinkage(GlobalValue::WeakAnyLinkage);
809*9880d681SAndroid Build Coastguard Worker         break;
810*9880d681SAndroid Build Coastguard Worker       case GlobalValue::LinkOnceODRLinkage:
811*9880d681SAndroid Build Coastguard Worker         GV->setLinkage(GlobalValue::WeakODRLinkage);
812*9880d681SAndroid Build Coastguard Worker         break;
813*9880d681SAndroid Build Coastguard Worker       }
814*9880d681SAndroid Build Coastguard Worker       break;
815*9880d681SAndroid Build Coastguard Worker 
816*9880d681SAndroid Build Coastguard Worker     case LDPR_PREVAILING_DEF_IRONLY_EXP: {
817*9880d681SAndroid Build Coastguard Worker       Keep.push_back(GV);
818*9880d681SAndroid Build Coastguard Worker       if (canBeOmittedFromSymbolTable(GV))
819*9880d681SAndroid Build Coastguard Worker         Internalize.insert(GV->getName());
820*9880d681SAndroid Build Coastguard Worker       break;
821*9880d681SAndroid Build Coastguard Worker     }
822*9880d681SAndroid Build Coastguard Worker     }
823*9880d681SAndroid Build Coastguard Worker 
824*9880d681SAndroid Build Coastguard Worker     freeSymName(Sym);
825*9880d681SAndroid Build Coastguard Worker   }
826*9880d681SAndroid Build Coastguard Worker 
827*9880d681SAndroid Build Coastguard Worker   return Obj.takeModule();
828*9880d681SAndroid Build Coastguard Worker }
829*9880d681SAndroid Build Coastguard Worker 
saveBCFile(StringRef Path,Module & M)830*9880d681SAndroid Build Coastguard Worker static void saveBCFile(StringRef Path, Module &M) {
831*9880d681SAndroid Build Coastguard Worker   std::error_code EC;
832*9880d681SAndroid Build Coastguard Worker   raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
833*9880d681SAndroid Build Coastguard Worker   if (EC)
834*9880d681SAndroid Build Coastguard Worker     message(LDPL_FATAL, "Failed to write the output file.");
835*9880d681SAndroid Build Coastguard Worker   WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ false);
836*9880d681SAndroid Build Coastguard Worker }
837*9880d681SAndroid Build Coastguard Worker 
recordFile(std::string Filename,bool TempOutFile)838*9880d681SAndroid Build Coastguard Worker static void recordFile(std::string Filename, bool TempOutFile) {
839*9880d681SAndroid Build Coastguard Worker   if (add_input_file(Filename.c_str()) != LDPS_OK)
840*9880d681SAndroid Build Coastguard Worker     message(LDPL_FATAL,
841*9880d681SAndroid Build Coastguard Worker             "Unable to add .o file to the link. File left behind in: %s",
842*9880d681SAndroid Build Coastguard Worker             Filename.c_str());
843*9880d681SAndroid Build Coastguard Worker   if (TempOutFile)
844*9880d681SAndroid Build Coastguard Worker     Cleanup.push_back(Filename.c_str());
845*9880d681SAndroid Build Coastguard Worker }
846*9880d681SAndroid Build Coastguard Worker 
cleanup()847*9880d681SAndroid Build Coastguard Worker void ThinLTOTaskInfo::cleanup() {
848*9880d681SAndroid Build Coastguard Worker   // Close the output file descriptor before we pass it to gold.
849*9880d681SAndroid Build Coastguard Worker   OS->close();
850*9880d681SAndroid Build Coastguard Worker 
851*9880d681SAndroid Build Coastguard Worker   recordFile(Filename, TempOutFile);
852*9880d681SAndroid Build Coastguard Worker }
853*9880d681SAndroid Build Coastguard Worker 
854*9880d681SAndroid Build Coastguard Worker namespace {
855*9880d681SAndroid Build Coastguard Worker /// Class to manage optimization and code generation for a module, possibly
856*9880d681SAndroid Build Coastguard Worker /// in a thread (ThinLTO).
857*9880d681SAndroid Build Coastguard Worker class CodeGen {
858*9880d681SAndroid Build Coastguard Worker   /// The module for which this will generate code.
859*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<llvm::Module> M;
860*9880d681SAndroid Build Coastguard Worker 
861*9880d681SAndroid Build Coastguard Worker   /// The output stream to generate code into.
862*9880d681SAndroid Build Coastguard Worker   raw_fd_ostream *OS;
863*9880d681SAndroid Build Coastguard Worker 
864*9880d681SAndroid Build Coastguard Worker   /// The task ID when this was invoked in a thread (ThinLTO).
865*9880d681SAndroid Build Coastguard Worker   int TaskID;
866*9880d681SAndroid Build Coastguard Worker 
867*9880d681SAndroid Build Coastguard Worker   /// The module summary index for ThinLTO tasks.
868*9880d681SAndroid Build Coastguard Worker   const ModuleSummaryIndex *CombinedIndex;
869*9880d681SAndroid Build Coastguard Worker 
870*9880d681SAndroid Build Coastguard Worker   /// The target machine for generating code for this module.
871*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<TargetMachine> TM;
872*9880d681SAndroid Build Coastguard Worker 
873*9880d681SAndroid Build Coastguard Worker   /// Filename to use as base when save-temps is enabled, used to get
874*9880d681SAndroid Build Coastguard Worker   /// a unique and identifiable save-temps output file for each ThinLTO backend.
875*9880d681SAndroid Build Coastguard Worker   std::string SaveTempsFilename;
876*9880d681SAndroid Build Coastguard Worker 
877*9880d681SAndroid Build Coastguard Worker   /// Map from a module name to the corresponding buffer holding a view of the
878*9880d681SAndroid Build Coastguard Worker   /// bitcode provided via the get_view gold callback.
879*9880d681SAndroid Build Coastguard Worker   StringMap<MemoryBufferRef> *ModuleMap;
880*9880d681SAndroid Build Coastguard Worker 
881*9880d681SAndroid Build Coastguard Worker   // Functions to import into this module.
882*9880d681SAndroid Build Coastguard Worker   FunctionImporter::ImportMapTy *ImportList;
883*9880d681SAndroid Build Coastguard Worker 
884*9880d681SAndroid Build Coastguard Worker   // Map of globals defined in this module to their summary.
885*9880d681SAndroid Build Coastguard Worker   std::map<GlobalValue::GUID, GlobalValueSummary *> *DefinedGlobals;
886*9880d681SAndroid Build Coastguard Worker 
887*9880d681SAndroid Build Coastguard Worker public:
888*9880d681SAndroid Build Coastguard Worker   /// Constructor used by full LTO.
CodeGen(std::unique_ptr<llvm::Module> M)889*9880d681SAndroid Build Coastguard Worker   CodeGen(std::unique_ptr<llvm::Module> M)
890*9880d681SAndroid Build Coastguard Worker       : M(std::move(M)), OS(nullptr), TaskID(-1), CombinedIndex(nullptr),
891*9880d681SAndroid Build Coastguard Worker         ModuleMap(nullptr) {
892*9880d681SAndroid Build Coastguard Worker     initTargetMachine();
893*9880d681SAndroid Build Coastguard Worker   }
894*9880d681SAndroid Build Coastguard Worker   /// Constructor used by ThinLTO.
CodeGen(std::unique_ptr<llvm::Module> M,raw_fd_ostream * OS,int TaskID,const ModuleSummaryIndex * CombinedIndex,std::string Filename,StringMap<MemoryBufferRef> * ModuleMap,FunctionImporter::ImportMapTy * ImportList,std::map<GlobalValue::GUID,GlobalValueSummary * > * DefinedGlobals)895*9880d681SAndroid Build Coastguard Worker   CodeGen(std::unique_ptr<llvm::Module> M, raw_fd_ostream *OS, int TaskID,
896*9880d681SAndroid Build Coastguard Worker           const ModuleSummaryIndex *CombinedIndex, std::string Filename,
897*9880d681SAndroid Build Coastguard Worker           StringMap<MemoryBufferRef> *ModuleMap,
898*9880d681SAndroid Build Coastguard Worker           FunctionImporter::ImportMapTy *ImportList,
899*9880d681SAndroid Build Coastguard Worker           std::map<GlobalValue::GUID, GlobalValueSummary *> *DefinedGlobals)
900*9880d681SAndroid Build Coastguard Worker       : M(std::move(M)), OS(OS), TaskID(TaskID), CombinedIndex(CombinedIndex),
901*9880d681SAndroid Build Coastguard Worker         SaveTempsFilename(std::move(Filename)), ModuleMap(ModuleMap),
902*9880d681SAndroid Build Coastguard Worker         ImportList(ImportList), DefinedGlobals(DefinedGlobals) {
903*9880d681SAndroid Build Coastguard Worker     assert(options::thinlto == !!CombinedIndex &&
904*9880d681SAndroid Build Coastguard Worker            "Expected module summary index iff performing ThinLTO");
905*9880d681SAndroid Build Coastguard Worker     initTargetMachine();
906*9880d681SAndroid Build Coastguard Worker   }
907*9880d681SAndroid Build Coastguard Worker 
908*9880d681SAndroid Build Coastguard Worker   /// Invoke LTO passes and the code generator for the module.
909*9880d681SAndroid Build Coastguard Worker   void runAll();
910*9880d681SAndroid Build Coastguard Worker 
911*9880d681SAndroid Build Coastguard Worker   /// Invoke the actual code generation to emit Module's object to file.
912*9880d681SAndroid Build Coastguard Worker   void runCodegenPasses();
913*9880d681SAndroid Build Coastguard Worker 
914*9880d681SAndroid Build Coastguard Worker private:
915*9880d681SAndroid Build Coastguard Worker   const Target *TheTarget;
916*9880d681SAndroid Build Coastguard Worker   std::string TripleStr;
917*9880d681SAndroid Build Coastguard Worker   std::string FeaturesString;
918*9880d681SAndroid Build Coastguard Worker   TargetOptions Options;
919*9880d681SAndroid Build Coastguard Worker 
920*9880d681SAndroid Build Coastguard Worker   /// Create a target machine for the module. Must be unique for each
921*9880d681SAndroid Build Coastguard Worker   /// module/task.
922*9880d681SAndroid Build Coastguard Worker   void initTargetMachine();
923*9880d681SAndroid Build Coastguard Worker 
924*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<TargetMachine> createTargetMachine();
925*9880d681SAndroid Build Coastguard Worker 
926*9880d681SAndroid Build Coastguard Worker   /// Run all LTO passes on the module.
927*9880d681SAndroid Build Coastguard Worker   void runLTOPasses();
928*9880d681SAndroid Build Coastguard Worker 
929*9880d681SAndroid Build Coastguard Worker   /// Sets up output files necessary to perform optional multi-threaded
930*9880d681SAndroid Build Coastguard Worker   /// split code generation, and invokes the code generation implementation.
931*9880d681SAndroid Build Coastguard Worker   /// If BCFileName is not empty, saves bitcode for module partitions into
932*9880d681SAndroid Build Coastguard Worker   /// {BCFileName}0 .. {BCFileName}N.
933*9880d681SAndroid Build Coastguard Worker   void runSplitCodeGen(const SmallString<128> &BCFilename);
934*9880d681SAndroid Build Coastguard Worker };
935*9880d681SAndroid Build Coastguard Worker }
936*9880d681SAndroid Build Coastguard Worker 
getFeatures(Triple & TheTriple)937*9880d681SAndroid Build Coastguard Worker static SubtargetFeatures getFeatures(Triple &TheTriple) {
938*9880d681SAndroid Build Coastguard Worker   SubtargetFeatures Features;
939*9880d681SAndroid Build Coastguard Worker   Features.getDefaultSubtargetFeatures(TheTriple);
940*9880d681SAndroid Build Coastguard Worker   for (const std::string &A : MAttrs)
941*9880d681SAndroid Build Coastguard Worker     Features.AddFeature(A);
942*9880d681SAndroid Build Coastguard Worker   return Features;
943*9880d681SAndroid Build Coastguard Worker }
944*9880d681SAndroid Build Coastguard Worker 
getCGOptLevel()945*9880d681SAndroid Build Coastguard Worker static CodeGenOpt::Level getCGOptLevel() {
946*9880d681SAndroid Build Coastguard Worker   switch (options::OptLevel) {
947*9880d681SAndroid Build Coastguard Worker   case 0:
948*9880d681SAndroid Build Coastguard Worker     return CodeGenOpt::None;
949*9880d681SAndroid Build Coastguard Worker   case 1:
950*9880d681SAndroid Build Coastguard Worker     return CodeGenOpt::Less;
951*9880d681SAndroid Build Coastguard Worker   case 2:
952*9880d681SAndroid Build Coastguard Worker     return CodeGenOpt::Default;
953*9880d681SAndroid Build Coastguard Worker   case 3:
954*9880d681SAndroid Build Coastguard Worker     return CodeGenOpt::Aggressive;
955*9880d681SAndroid Build Coastguard Worker   }
956*9880d681SAndroid Build Coastguard Worker   llvm_unreachable("Invalid optimization level");
957*9880d681SAndroid Build Coastguard Worker }
958*9880d681SAndroid Build Coastguard Worker 
initTargetMachine()959*9880d681SAndroid Build Coastguard Worker void CodeGen::initTargetMachine() {
960*9880d681SAndroid Build Coastguard Worker   TripleStr = M->getTargetTriple();
961*9880d681SAndroid Build Coastguard Worker   Triple TheTriple(TripleStr);
962*9880d681SAndroid Build Coastguard Worker 
963*9880d681SAndroid Build Coastguard Worker   std::string ErrMsg;
964*9880d681SAndroid Build Coastguard Worker   TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
965*9880d681SAndroid Build Coastguard Worker   if (!TheTarget)
966*9880d681SAndroid Build Coastguard Worker     message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
967*9880d681SAndroid Build Coastguard Worker 
968*9880d681SAndroid Build Coastguard Worker   SubtargetFeatures Features = getFeatures(TheTriple);
969*9880d681SAndroid Build Coastguard Worker   FeaturesString = Features.getString();
970*9880d681SAndroid Build Coastguard Worker   Options = InitTargetOptionsFromCodeGenFlags();
971*9880d681SAndroid Build Coastguard Worker 
972*9880d681SAndroid Build Coastguard Worker   // Disable the new X86 relax relocations since gold might not support them.
973*9880d681SAndroid Build Coastguard Worker   // FIXME: Check the gold version or add a new option to enable them.
974*9880d681SAndroid Build Coastguard Worker   Options.RelaxELFRelocations = false;
975*9880d681SAndroid Build Coastguard Worker 
976*9880d681SAndroid Build Coastguard Worker   TM = createTargetMachine();
977*9880d681SAndroid Build Coastguard Worker }
978*9880d681SAndroid Build Coastguard Worker 
createTargetMachine()979*9880d681SAndroid Build Coastguard Worker std::unique_ptr<TargetMachine> CodeGen::createTargetMachine() {
980*9880d681SAndroid Build Coastguard Worker   CodeGenOpt::Level CGOptLevel = getCGOptLevel();
981*9880d681SAndroid Build Coastguard Worker 
982*9880d681SAndroid Build Coastguard Worker   return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
983*9880d681SAndroid Build Coastguard Worker       TripleStr, options::mcpu, FeaturesString, Options, RelocationModel,
984*9880d681SAndroid Build Coastguard Worker       CodeModel::Default, CGOptLevel));
985*9880d681SAndroid Build Coastguard Worker }
986*9880d681SAndroid Build Coastguard Worker 
runLTOPasses()987*9880d681SAndroid Build Coastguard Worker void CodeGen::runLTOPasses() {
988*9880d681SAndroid Build Coastguard Worker   M->setDataLayout(TM->createDataLayout());
989*9880d681SAndroid Build Coastguard Worker 
990*9880d681SAndroid Build Coastguard Worker   if (CombinedIndex) {
991*9880d681SAndroid Build Coastguard Worker     // Apply summary-based LinkOnce/Weak resolution decisions.
992*9880d681SAndroid Build Coastguard Worker     thinLTOResolveWeakForLinkerModule(*M, *DefinedGlobals);
993*9880d681SAndroid Build Coastguard Worker 
994*9880d681SAndroid Build Coastguard Worker     // Apply summary-based internalization decisions. Skip if there are no
995*9880d681SAndroid Build Coastguard Worker     // defined globals from the summary since not only is it unnecessary, but
996*9880d681SAndroid Build Coastguard Worker     // if this module did not have a summary section the internalizer will
997*9880d681SAndroid Build Coastguard Worker     // assert if it finds any definitions in this module that aren't in the
998*9880d681SAndroid Build Coastguard Worker     // DefinedGlobals set.
999*9880d681SAndroid Build Coastguard Worker     if (!DefinedGlobals->empty())
1000*9880d681SAndroid Build Coastguard Worker       thinLTOInternalizeModule(*M, *DefinedGlobals);
1001*9880d681SAndroid Build Coastguard Worker 
1002*9880d681SAndroid Build Coastguard Worker     // Create a loader that will parse the bitcode from the buffers
1003*9880d681SAndroid Build Coastguard Worker     // in the ModuleMap.
1004*9880d681SAndroid Build Coastguard Worker     ModuleLoader Loader(M->getContext(), *ModuleMap);
1005*9880d681SAndroid Build Coastguard Worker 
1006*9880d681SAndroid Build Coastguard Worker     // Perform function importing.
1007*9880d681SAndroid Build Coastguard Worker     FunctionImporter Importer(*CombinedIndex, Loader);
1008*9880d681SAndroid Build Coastguard Worker     Importer.importFunctions(*M, *ImportList);
1009*9880d681SAndroid Build Coastguard Worker   }
1010*9880d681SAndroid Build Coastguard Worker 
1011*9880d681SAndroid Build Coastguard Worker   legacy::PassManager passes;
1012*9880d681SAndroid Build Coastguard Worker   passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
1013*9880d681SAndroid Build Coastguard Worker 
1014*9880d681SAndroid Build Coastguard Worker   PassManagerBuilder PMB;
1015*9880d681SAndroid Build Coastguard Worker   PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
1016*9880d681SAndroid Build Coastguard Worker   PMB.Inliner = createFunctionInliningPass();
1017*9880d681SAndroid Build Coastguard Worker   // Unconditionally verify input since it is not verified before this
1018*9880d681SAndroid Build Coastguard Worker   // point and has unknown origin.
1019*9880d681SAndroid Build Coastguard Worker   PMB.VerifyInput = true;
1020*9880d681SAndroid Build Coastguard Worker   PMB.VerifyOutput = !options::DisableVerify;
1021*9880d681SAndroid Build Coastguard Worker   PMB.LoopVectorize = true;
1022*9880d681SAndroid Build Coastguard Worker   PMB.SLPVectorize = true;
1023*9880d681SAndroid Build Coastguard Worker   PMB.OptLevel = options::OptLevel;
1024*9880d681SAndroid Build Coastguard Worker   if (options::thinlto)
1025*9880d681SAndroid Build Coastguard Worker     PMB.populateThinLTOPassManager(passes);
1026*9880d681SAndroid Build Coastguard Worker   else
1027*9880d681SAndroid Build Coastguard Worker     PMB.populateLTOPassManager(passes);
1028*9880d681SAndroid Build Coastguard Worker   passes.run(*M);
1029*9880d681SAndroid Build Coastguard Worker }
1030*9880d681SAndroid Build Coastguard Worker 
1031*9880d681SAndroid Build Coastguard Worker /// Open a file and return the new file descriptor given a base input
1032*9880d681SAndroid Build Coastguard Worker /// file name, a flag indicating whether a temp file should be generated,
1033*9880d681SAndroid Build Coastguard Worker /// and an optional task id. The new filename generated is
1034*9880d681SAndroid Build Coastguard Worker /// returned in \p NewFilename.
openOutputFile(SmallString<128> InFilename,bool TempOutFile,SmallString<128> & NewFilename,int TaskID=-1)1035*9880d681SAndroid Build Coastguard Worker static int openOutputFile(SmallString<128> InFilename, bool TempOutFile,
1036*9880d681SAndroid Build Coastguard Worker                           SmallString<128> &NewFilename, int TaskID = -1) {
1037*9880d681SAndroid Build Coastguard Worker   int FD;
1038*9880d681SAndroid Build Coastguard Worker   if (TempOutFile) {
1039*9880d681SAndroid Build Coastguard Worker     std::error_code EC =
1040*9880d681SAndroid Build Coastguard Worker         sys::fs::createTemporaryFile("lto-llvm", "o", FD, NewFilename);
1041*9880d681SAndroid Build Coastguard Worker     if (EC)
1042*9880d681SAndroid Build Coastguard Worker       message(LDPL_FATAL, "Could not create temporary file: %s",
1043*9880d681SAndroid Build Coastguard Worker               EC.message().c_str());
1044*9880d681SAndroid Build Coastguard Worker   } else {
1045*9880d681SAndroid Build Coastguard Worker     NewFilename = InFilename;
1046*9880d681SAndroid Build Coastguard Worker     if (TaskID >= 0)
1047*9880d681SAndroid Build Coastguard Worker       NewFilename += utostr(TaskID);
1048*9880d681SAndroid Build Coastguard Worker     std::error_code EC =
1049*9880d681SAndroid Build Coastguard Worker         sys::fs::openFileForWrite(NewFilename, FD, sys::fs::F_None);
1050*9880d681SAndroid Build Coastguard Worker     if (EC)
1051*9880d681SAndroid Build Coastguard Worker       message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
1052*9880d681SAndroid Build Coastguard Worker   }
1053*9880d681SAndroid Build Coastguard Worker   return FD;
1054*9880d681SAndroid Build Coastguard Worker }
1055*9880d681SAndroid Build Coastguard Worker 
runCodegenPasses()1056*9880d681SAndroid Build Coastguard Worker void CodeGen::runCodegenPasses() {
1057*9880d681SAndroid Build Coastguard Worker   assert(OS && "Output stream must be set before emitting to file");
1058*9880d681SAndroid Build Coastguard Worker   legacy::PassManager CodeGenPasses;
1059*9880d681SAndroid Build Coastguard Worker   if (TM->addPassesToEmitFile(CodeGenPasses, *OS,
1060*9880d681SAndroid Build Coastguard Worker                               TargetMachine::CGFT_ObjectFile))
1061*9880d681SAndroid Build Coastguard Worker     report_fatal_error("Failed to setup codegen");
1062*9880d681SAndroid Build Coastguard Worker   CodeGenPasses.run(*M);
1063*9880d681SAndroid Build Coastguard Worker }
1064*9880d681SAndroid Build Coastguard Worker 
runSplitCodeGen(const SmallString<128> & BCFilename)1065*9880d681SAndroid Build Coastguard Worker void CodeGen::runSplitCodeGen(const SmallString<128> &BCFilename) {
1066*9880d681SAndroid Build Coastguard Worker   SmallString<128> Filename;
1067*9880d681SAndroid Build Coastguard Worker   // Note that openOutputFile will append a unique ID for each task
1068*9880d681SAndroid Build Coastguard Worker   if (!options::obj_path.empty())
1069*9880d681SAndroid Build Coastguard Worker     Filename = options::obj_path;
1070*9880d681SAndroid Build Coastguard Worker   else if (options::TheOutputType == options::OT_SAVE_TEMPS)
1071*9880d681SAndroid Build Coastguard Worker     Filename = output_name + ".o";
1072*9880d681SAndroid Build Coastguard Worker 
1073*9880d681SAndroid Build Coastguard Worker   // Note that the default parallelism is 1 instead of the
1074*9880d681SAndroid Build Coastguard Worker   // hardware_concurrency, as there are behavioral differences between
1075*9880d681SAndroid Build Coastguard Worker   // parallelism levels (e.g. symbol ordering will be different, and some uses
1076*9880d681SAndroid Build Coastguard Worker   // of inline asm currently have issues with parallelism >1).
1077*9880d681SAndroid Build Coastguard Worker   unsigned int MaxThreads = options::Parallelism ? options::Parallelism : 1;
1078*9880d681SAndroid Build Coastguard Worker 
1079*9880d681SAndroid Build Coastguard Worker   std::vector<SmallString<128>> Filenames(MaxThreads);
1080*9880d681SAndroid Build Coastguard Worker   std::vector<SmallString<128>> BCFilenames(MaxThreads);
1081*9880d681SAndroid Build Coastguard Worker   bool TempOutFile = Filename.empty();
1082*9880d681SAndroid Build Coastguard Worker   {
1083*9880d681SAndroid Build Coastguard Worker     // Open a file descriptor for each backend task. This is done in a block
1084*9880d681SAndroid Build Coastguard Worker     // so that the output file descriptors are closed before gold opens them.
1085*9880d681SAndroid Build Coastguard Worker     std::list<llvm::raw_fd_ostream> OSs;
1086*9880d681SAndroid Build Coastguard Worker     std::vector<llvm::raw_pwrite_stream *> OSPtrs(MaxThreads);
1087*9880d681SAndroid Build Coastguard Worker     for (unsigned I = 0; I != MaxThreads; ++I) {
1088*9880d681SAndroid Build Coastguard Worker       int FD = openOutputFile(Filename, TempOutFile, Filenames[I],
1089*9880d681SAndroid Build Coastguard Worker                               // Only append ID if there are multiple tasks.
1090*9880d681SAndroid Build Coastguard Worker                               MaxThreads > 1 ? I : -1);
1091*9880d681SAndroid Build Coastguard Worker       OSs.emplace_back(FD, true);
1092*9880d681SAndroid Build Coastguard Worker       OSPtrs[I] = &OSs.back();
1093*9880d681SAndroid Build Coastguard Worker     }
1094*9880d681SAndroid Build Coastguard Worker 
1095*9880d681SAndroid Build Coastguard Worker     std::list<llvm::raw_fd_ostream> BCOSs;
1096*9880d681SAndroid Build Coastguard Worker     std::vector<llvm::raw_pwrite_stream *> BCOSPtrs;
1097*9880d681SAndroid Build Coastguard Worker     if (!BCFilename.empty() && MaxThreads > 1) {
1098*9880d681SAndroid Build Coastguard Worker       for (unsigned I = 0; I != MaxThreads; ++I) {
1099*9880d681SAndroid Build Coastguard Worker         int FD = openOutputFile(BCFilename, false, BCFilenames[I], I);
1100*9880d681SAndroid Build Coastguard Worker         BCOSs.emplace_back(FD, true);
1101*9880d681SAndroid Build Coastguard Worker         BCOSPtrs.push_back(&BCOSs.back());
1102*9880d681SAndroid Build Coastguard Worker       }
1103*9880d681SAndroid Build Coastguard Worker     }
1104*9880d681SAndroid Build Coastguard Worker 
1105*9880d681SAndroid Build Coastguard Worker     // Run backend tasks.
1106*9880d681SAndroid Build Coastguard Worker     splitCodeGen(std::move(M), OSPtrs, BCOSPtrs,
1107*9880d681SAndroid Build Coastguard Worker                  [&]() { return createTargetMachine(); });
1108*9880d681SAndroid Build Coastguard Worker   }
1109*9880d681SAndroid Build Coastguard Worker 
1110*9880d681SAndroid Build Coastguard Worker   for (auto &Filename : Filenames)
1111*9880d681SAndroid Build Coastguard Worker     recordFile(Filename.c_str(), TempOutFile);
1112*9880d681SAndroid Build Coastguard Worker }
1113*9880d681SAndroid Build Coastguard Worker 
runAll()1114*9880d681SAndroid Build Coastguard Worker void CodeGen::runAll() {
1115*9880d681SAndroid Build Coastguard Worker   runLTOPasses();
1116*9880d681SAndroid Build Coastguard Worker 
1117*9880d681SAndroid Build Coastguard Worker   SmallString<128> OptFilename;
1118*9880d681SAndroid Build Coastguard Worker   if (options::TheOutputType == options::OT_SAVE_TEMPS) {
1119*9880d681SAndroid Build Coastguard Worker     OptFilename = output_name;
1120*9880d681SAndroid Build Coastguard Worker     // If the CodeGen client provided a filename, use it. Always expect
1121*9880d681SAndroid Build Coastguard Worker     // a provided filename if we are in a task (i.e. ThinLTO backend).
1122*9880d681SAndroid Build Coastguard Worker     assert(!SaveTempsFilename.empty() || TaskID == -1);
1123*9880d681SAndroid Build Coastguard Worker     if (!SaveTempsFilename.empty())
1124*9880d681SAndroid Build Coastguard Worker       OptFilename = SaveTempsFilename;
1125*9880d681SAndroid Build Coastguard Worker     OptFilename += ".opt.bc";
1126*9880d681SAndroid Build Coastguard Worker     saveBCFile(OptFilename, *M);
1127*9880d681SAndroid Build Coastguard Worker   }
1128*9880d681SAndroid Build Coastguard Worker 
1129*9880d681SAndroid Build Coastguard Worker   // If we are already in a thread (i.e. ThinLTO), just perform
1130*9880d681SAndroid Build Coastguard Worker   // codegen passes directly.
1131*9880d681SAndroid Build Coastguard Worker   if (TaskID >= 0)
1132*9880d681SAndroid Build Coastguard Worker     runCodegenPasses();
1133*9880d681SAndroid Build Coastguard Worker   // Otherwise attempt split code gen.
1134*9880d681SAndroid Build Coastguard Worker   else
1135*9880d681SAndroid Build Coastguard Worker     runSplitCodeGen(OptFilename);
1136*9880d681SAndroid Build Coastguard Worker }
1137*9880d681SAndroid Build Coastguard Worker 
1138*9880d681SAndroid Build Coastguard Worker /// Links the module in \p View from file \p F into the combined module
1139*9880d681SAndroid Build Coastguard Worker /// saved in the IRMover \p L.
linkInModule(LLVMContext & Context,IRMover & L,claimed_file & F,const void * View,StringRef Name,raw_fd_ostream * ApiFile,StringSet<> & Internalize,bool SetName=false)1140*9880d681SAndroid Build Coastguard Worker static void linkInModule(LLVMContext &Context, IRMover &L, claimed_file &F,
1141*9880d681SAndroid Build Coastguard Worker                          const void *View, StringRef Name,
1142*9880d681SAndroid Build Coastguard Worker                          raw_fd_ostream *ApiFile, StringSet<> &Internalize,
1143*9880d681SAndroid Build Coastguard Worker                          bool SetName = false) {
1144*9880d681SAndroid Build Coastguard Worker   std::vector<GlobalValue *> Keep;
1145*9880d681SAndroid Build Coastguard Worker   StringMap<unsigned> Realign;
1146*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<Module> M = getModuleForFile(Context, F, View, Name, ApiFile,
1147*9880d681SAndroid Build Coastguard Worker                                                Internalize, Keep, Realign);
1148*9880d681SAndroid Build Coastguard Worker   if (!M.get())
1149*9880d681SAndroid Build Coastguard Worker     return;
1150*9880d681SAndroid Build Coastguard Worker   if (!options::triple.empty())
1151*9880d681SAndroid Build Coastguard Worker     M->setTargetTriple(options::triple.c_str());
1152*9880d681SAndroid Build Coastguard Worker   else if (M->getTargetTriple().empty()) {
1153*9880d681SAndroid Build Coastguard Worker     M->setTargetTriple(DefaultTriple);
1154*9880d681SAndroid Build Coastguard Worker   }
1155*9880d681SAndroid Build Coastguard Worker 
1156*9880d681SAndroid Build Coastguard Worker   // For ThinLTO we want to propagate the source file name to ensure
1157*9880d681SAndroid Build Coastguard Worker   // we can create the correct global identifiers matching those in the
1158*9880d681SAndroid Build Coastguard Worker   // original module.
1159*9880d681SAndroid Build Coastguard Worker   if (SetName)
1160*9880d681SAndroid Build Coastguard Worker     L.getModule().setSourceFileName(M->getSourceFileName());
1161*9880d681SAndroid Build Coastguard Worker 
1162*9880d681SAndroid Build Coastguard Worker   if (Error E = L.move(std::move(M), Keep,
1163*9880d681SAndroid Build Coastguard Worker                        [](GlobalValue &, IRMover::ValueAdder) {})) {
1164*9880d681SAndroid Build Coastguard Worker     handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
1165*9880d681SAndroid Build Coastguard Worker       message(LDPL_FATAL, "Failed to link module %s: %s", Name.str().c_str(),
1166*9880d681SAndroid Build Coastguard Worker               EIB.message().c_str());
1167*9880d681SAndroid Build Coastguard Worker     });
1168*9880d681SAndroid Build Coastguard Worker   }
1169*9880d681SAndroid Build Coastguard Worker 
1170*9880d681SAndroid Build Coastguard Worker   for (const auto &I : Realign) {
1171*9880d681SAndroid Build Coastguard Worker     GlobalValue *Dst = L.getModule().getNamedValue(I.first());
1172*9880d681SAndroid Build Coastguard Worker     if (!Dst)
1173*9880d681SAndroid Build Coastguard Worker       continue;
1174*9880d681SAndroid Build Coastguard Worker     cast<GlobalVariable>(Dst)->setAlignment(I.second);
1175*9880d681SAndroid Build Coastguard Worker   }
1176*9880d681SAndroid Build Coastguard Worker }
1177*9880d681SAndroid Build Coastguard Worker 
1178*9880d681SAndroid Build Coastguard Worker /// Perform the ThinLTO backend on a single module, invoking the LTO and codegen
1179*9880d681SAndroid Build Coastguard Worker /// pipelines.
thinLTOBackendTask(claimed_file & F,const void * View,StringRef Name,raw_fd_ostream * ApiFile,const ModuleSummaryIndex & CombinedIndex,raw_fd_ostream * OS,unsigned TaskID,StringMap<MemoryBufferRef> & ModuleMap,FunctionImporter::ImportMapTy & ImportList,std::map<GlobalValue::GUID,GlobalValueSummary * > & DefinedGlobals)1180*9880d681SAndroid Build Coastguard Worker static void thinLTOBackendTask(claimed_file &F, const void *View,
1181*9880d681SAndroid Build Coastguard Worker                                StringRef Name, raw_fd_ostream *ApiFile,
1182*9880d681SAndroid Build Coastguard Worker                                const ModuleSummaryIndex &CombinedIndex,
1183*9880d681SAndroid Build Coastguard Worker                                raw_fd_ostream *OS, unsigned TaskID,
1184*9880d681SAndroid Build Coastguard Worker                                StringMap<MemoryBufferRef> &ModuleMap,
1185*9880d681SAndroid Build Coastguard Worker                                FunctionImporter::ImportMapTy &ImportList,
1186*9880d681SAndroid Build Coastguard Worker                                std::map<GlobalValue::GUID, GlobalValueSummary *> &DefinedGlobals) {
1187*9880d681SAndroid Build Coastguard Worker   // Need to use a separate context for each task
1188*9880d681SAndroid Build Coastguard Worker   LLVMContext Context;
1189*9880d681SAndroid Build Coastguard Worker   Context.setDiscardValueNames(options::TheOutputType !=
1190*9880d681SAndroid Build Coastguard Worker                                options::OT_SAVE_TEMPS);
1191*9880d681SAndroid Build Coastguard Worker   Context.enableDebugTypeODRUniquing(); // Merge debug info types.
1192*9880d681SAndroid Build Coastguard Worker   Context.setDiagnosticHandler(diagnosticHandlerForContext, nullptr, true);
1193*9880d681SAndroid Build Coastguard Worker 
1194*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<llvm::Module> NewModule(new llvm::Module(Name, Context));
1195*9880d681SAndroid Build Coastguard Worker   IRMover L(*NewModule.get());
1196*9880d681SAndroid Build Coastguard Worker 
1197*9880d681SAndroid Build Coastguard Worker   StringSet<> Dummy;
1198*9880d681SAndroid Build Coastguard Worker   linkInModule(Context, L, F, View, Name, ApiFile, Dummy, true);
1199*9880d681SAndroid Build Coastguard Worker   if (renameModuleForThinLTO(*NewModule, CombinedIndex))
1200*9880d681SAndroid Build Coastguard Worker     message(LDPL_FATAL, "Failed to rename module for ThinLTO");
1201*9880d681SAndroid Build Coastguard Worker 
1202*9880d681SAndroid Build Coastguard Worker   CodeGen codeGen(std::move(NewModule), OS, TaskID, &CombinedIndex, Name,
1203*9880d681SAndroid Build Coastguard Worker                   &ModuleMap, &ImportList, &DefinedGlobals);
1204*9880d681SAndroid Build Coastguard Worker   codeGen.runAll();
1205*9880d681SAndroid Build Coastguard Worker }
1206*9880d681SAndroid Build Coastguard Worker 
1207*9880d681SAndroid Build Coastguard Worker /// Launch each module's backend pipeline in a separate task in a thread pool.
1208*9880d681SAndroid Build Coastguard Worker static void
thinLTOBackends(raw_fd_ostream * ApiFile,const ModuleSummaryIndex & CombinedIndex,StringMap<MemoryBufferRef> & ModuleMap,StringMap<FunctionImporter::ImportMapTy> & ImportLists,StringMap<std::map<GlobalValue::GUID,GlobalValueSummary * >> & ModuleToDefinedGVSummaries)1209*9880d681SAndroid Build Coastguard Worker thinLTOBackends(raw_fd_ostream *ApiFile,
1210*9880d681SAndroid Build Coastguard Worker                 const ModuleSummaryIndex &CombinedIndex,
1211*9880d681SAndroid Build Coastguard Worker                 StringMap<MemoryBufferRef> &ModuleMap,
1212*9880d681SAndroid Build Coastguard Worker                 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
1213*9880d681SAndroid Build Coastguard Worker   StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
1214*9880d681SAndroid Build Coastguard Worker       &ModuleToDefinedGVSummaries) {
1215*9880d681SAndroid Build Coastguard Worker   unsigned TaskCount = 0;
1216*9880d681SAndroid Build Coastguard Worker   std::vector<ThinLTOTaskInfo> Tasks;
1217*9880d681SAndroid Build Coastguard Worker   Tasks.reserve(Modules.size());
1218*9880d681SAndroid Build Coastguard Worker   unsigned int MaxThreads = options::Parallelism
1219*9880d681SAndroid Build Coastguard Worker                                 ? options::Parallelism
1220*9880d681SAndroid Build Coastguard Worker                                 : thread::hardware_concurrency();
1221*9880d681SAndroid Build Coastguard Worker 
1222*9880d681SAndroid Build Coastguard Worker   // Create ThreadPool in nested scope so that threads will be joined
1223*9880d681SAndroid Build Coastguard Worker   // on destruction.
1224*9880d681SAndroid Build Coastguard Worker   {
1225*9880d681SAndroid Build Coastguard Worker     ThreadPool ThinLTOThreadPool(MaxThreads);
1226*9880d681SAndroid Build Coastguard Worker     for (claimed_file &F : Modules) {
1227*9880d681SAndroid Build Coastguard Worker       // Do all the gold callbacks in the main thread, since gold is not thread
1228*9880d681SAndroid Build Coastguard Worker       // safe by default.
1229*9880d681SAndroid Build Coastguard Worker       const void *View = getSymbolsAndView(F);
1230*9880d681SAndroid Build Coastguard Worker       if (!View)
1231*9880d681SAndroid Build Coastguard Worker         continue;
1232*9880d681SAndroid Build Coastguard Worker 
1233*9880d681SAndroid Build Coastguard Worker       SmallString<128> Filename;
1234*9880d681SAndroid Build Coastguard Worker       if (!options::obj_path.empty())
1235*9880d681SAndroid Build Coastguard Worker         // Note that openOutputFile will append a unique ID for each task
1236*9880d681SAndroid Build Coastguard Worker         Filename = options::obj_path;
1237*9880d681SAndroid Build Coastguard Worker       else if (options::TheOutputType == options::OT_SAVE_TEMPS) {
1238*9880d681SAndroid Build Coastguard Worker         // Use the input file name so that we get a unique and identifiable
1239*9880d681SAndroid Build Coastguard Worker         // output file for each ThinLTO backend task.
1240*9880d681SAndroid Build Coastguard Worker         Filename = F.name;
1241*9880d681SAndroid Build Coastguard Worker         Filename += ".thinlto.o";
1242*9880d681SAndroid Build Coastguard Worker       }
1243*9880d681SAndroid Build Coastguard Worker       bool TempOutFile = Filename.empty();
1244*9880d681SAndroid Build Coastguard Worker 
1245*9880d681SAndroid Build Coastguard Worker       SmallString<128> NewFilename;
1246*9880d681SAndroid Build Coastguard Worker       int FD = openOutputFile(Filename, TempOutFile, NewFilename,
1247*9880d681SAndroid Build Coastguard Worker                               // Only append the TaskID if we will use the
1248*9880d681SAndroid Build Coastguard Worker                               // non-unique obj_path.
1249*9880d681SAndroid Build Coastguard Worker                               !options::obj_path.empty() ? TaskCount : -1);
1250*9880d681SAndroid Build Coastguard Worker       TaskCount++;
1251*9880d681SAndroid Build Coastguard Worker       std::unique_ptr<raw_fd_ostream> OS =
1252*9880d681SAndroid Build Coastguard Worker           llvm::make_unique<raw_fd_ostream>(FD, true);
1253*9880d681SAndroid Build Coastguard Worker 
1254*9880d681SAndroid Build Coastguard Worker       // Enqueue the task
1255*9880d681SAndroid Build Coastguard Worker       ThinLTOThreadPool.async(thinLTOBackendTask, std::ref(F), View, F.name,
1256*9880d681SAndroid Build Coastguard Worker                               ApiFile, std::ref(CombinedIndex), OS.get(),
1257*9880d681SAndroid Build Coastguard Worker                               TaskCount, std::ref(ModuleMap),
1258*9880d681SAndroid Build Coastguard Worker                               std::ref(ImportLists[F.name]),
1259*9880d681SAndroid Build Coastguard Worker                               std::ref(ModuleToDefinedGVSummaries[F.name]));
1260*9880d681SAndroid Build Coastguard Worker 
1261*9880d681SAndroid Build Coastguard Worker       // Record the information needed by the task or during its cleanup
1262*9880d681SAndroid Build Coastguard Worker       // to a ThinLTOTaskInfo instance. For information needed by the task
1263*9880d681SAndroid Build Coastguard Worker       // the unique_ptr ownership is transferred to the ThinLTOTaskInfo.
1264*9880d681SAndroid Build Coastguard Worker       Tasks.emplace_back(std::move(OS), NewFilename.c_str(), TempOutFile);
1265*9880d681SAndroid Build Coastguard Worker     }
1266*9880d681SAndroid Build Coastguard Worker   }
1267*9880d681SAndroid Build Coastguard Worker 
1268*9880d681SAndroid Build Coastguard Worker   for (auto &Task : Tasks)
1269*9880d681SAndroid Build Coastguard Worker     Task.cleanup();
1270*9880d681SAndroid Build Coastguard Worker }
1271*9880d681SAndroid Build Coastguard Worker 
1272*9880d681SAndroid Build Coastguard Worker /// Parse the thinlto_prefix_replace option into the \p OldPrefix and
1273*9880d681SAndroid Build Coastguard Worker /// \p NewPrefix strings, if it was specified.
getThinLTOOldAndNewPrefix(std::string & OldPrefix,std::string & NewPrefix)1274*9880d681SAndroid Build Coastguard Worker static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
1275*9880d681SAndroid Build Coastguard Worker                                       std::string &NewPrefix) {
1276*9880d681SAndroid Build Coastguard Worker   StringRef PrefixReplace = options::thinlto_prefix_replace;
1277*9880d681SAndroid Build Coastguard Worker   assert(PrefixReplace.empty() || PrefixReplace.find(";") != StringRef::npos);
1278*9880d681SAndroid Build Coastguard Worker   std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
1279*9880d681SAndroid Build Coastguard Worker   OldPrefix = Split.first.str();
1280*9880d681SAndroid Build Coastguard Worker   NewPrefix = Split.second.str();
1281*9880d681SAndroid Build Coastguard Worker }
1282*9880d681SAndroid Build Coastguard Worker 
1283*9880d681SAndroid Build Coastguard Worker /// Given the original \p Path to an output file, replace any path
1284*9880d681SAndroid Build Coastguard Worker /// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
1285*9880d681SAndroid Build Coastguard Worker /// resulting directory if it does not yet exist.
getThinLTOOutputFile(const std::string & Path,const std::string & OldPrefix,const std::string & NewPrefix)1286*9880d681SAndroid Build Coastguard Worker static std::string getThinLTOOutputFile(const std::string &Path,
1287*9880d681SAndroid Build Coastguard Worker                                         const std::string &OldPrefix,
1288*9880d681SAndroid Build Coastguard Worker                                         const std::string &NewPrefix) {
1289*9880d681SAndroid Build Coastguard Worker   if (OldPrefix.empty() && NewPrefix.empty())
1290*9880d681SAndroid Build Coastguard Worker     return Path;
1291*9880d681SAndroid Build Coastguard Worker   SmallString<128> NewPath(Path);
1292*9880d681SAndroid Build Coastguard Worker   llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
1293*9880d681SAndroid Build Coastguard Worker   StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
1294*9880d681SAndroid Build Coastguard Worker   if (!ParentPath.empty()) {
1295*9880d681SAndroid Build Coastguard Worker     // Make sure the new directory exists, creating it if necessary.
1296*9880d681SAndroid Build Coastguard Worker     if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
1297*9880d681SAndroid Build Coastguard Worker       llvm::errs() << "warning: could not create directory '" << ParentPath
1298*9880d681SAndroid Build Coastguard Worker                    << "': " << EC.message() << '\n';
1299*9880d681SAndroid Build Coastguard Worker   }
1300*9880d681SAndroid Build Coastguard Worker   return NewPath.str();
1301*9880d681SAndroid Build Coastguard Worker }
1302*9880d681SAndroid Build Coastguard Worker 
1303*9880d681SAndroid Build Coastguard Worker /// Perform ThinLTO link, which creates the combined index file.
1304*9880d681SAndroid Build Coastguard Worker /// Also, either launch backend threads or (under thinlto-index-only)
1305*9880d681SAndroid Build Coastguard Worker /// emit individual index files for distributed backends and exit.
thinLTOLink(raw_fd_ostream * ApiFile)1306*9880d681SAndroid Build Coastguard Worker static ld_plugin_status thinLTOLink(raw_fd_ostream *ApiFile) {
1307*9880d681SAndroid Build Coastguard Worker   // Map from a module name to the corresponding buffer holding a view of the
1308*9880d681SAndroid Build Coastguard Worker   // bitcode provided via the get_view gold callback.
1309*9880d681SAndroid Build Coastguard Worker   StringMap<MemoryBufferRef> ModuleMap;
1310*9880d681SAndroid Build Coastguard Worker   // Map to own RAII objects that manage the file opening and releasing
1311*9880d681SAndroid Build Coastguard Worker   // interfaces with gold.
1312*9880d681SAndroid Build Coastguard Worker   DenseMap<void *, std::unique_ptr<PluginInputFile>> HandleToInputFile;
1313*9880d681SAndroid Build Coastguard Worker 
1314*9880d681SAndroid Build Coastguard Worker   // Keep track of symbols that must not be internalized because they
1315*9880d681SAndroid Build Coastguard Worker   // are referenced outside of a single IR module.
1316*9880d681SAndroid Build Coastguard Worker   DenseSet<GlobalValue::GUID> Preserve;
1317*9880d681SAndroid Build Coastguard Worker 
1318*9880d681SAndroid Build Coastguard Worker   // Keep track of the prevailing copy for each GUID, for use in resolving
1319*9880d681SAndroid Build Coastguard Worker   // weak linkages.
1320*9880d681SAndroid Build Coastguard Worker   DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
1321*9880d681SAndroid Build Coastguard Worker 
1322*9880d681SAndroid Build Coastguard Worker   ModuleSummaryIndex CombinedIndex;
1323*9880d681SAndroid Build Coastguard Worker   uint64_t NextModuleId = 0;
1324*9880d681SAndroid Build Coastguard Worker   for (claimed_file &F : Modules) {
1325*9880d681SAndroid Build Coastguard Worker     if (!HandleToInputFile.count(F.leader_handle))
1326*9880d681SAndroid Build Coastguard Worker       HandleToInputFile.insert(std::make_pair(
1327*9880d681SAndroid Build Coastguard Worker           F.leader_handle, llvm::make_unique<PluginInputFile>(F.handle)));
1328*9880d681SAndroid Build Coastguard Worker     // Pass this into getModuleSummaryIndexForFile
1329*9880d681SAndroid Build Coastguard Worker     const void *View = getSymbolsAndView(F);
1330*9880d681SAndroid Build Coastguard Worker     if (!View)
1331*9880d681SAndroid Build Coastguard Worker       continue;
1332*9880d681SAndroid Build Coastguard Worker 
1333*9880d681SAndroid Build Coastguard Worker     MemoryBufferRef ModuleBuffer(StringRef((const char *)View, F.filesize),
1334*9880d681SAndroid Build Coastguard Worker                                  F.name);
1335*9880d681SAndroid Build Coastguard Worker     assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
1336*9880d681SAndroid Build Coastguard Worker                ModuleMap.end() &&
1337*9880d681SAndroid Build Coastguard Worker            "Expect unique Buffer Identifier");
1338*9880d681SAndroid Build Coastguard Worker     ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
1339*9880d681SAndroid Build Coastguard Worker 
1340*9880d681SAndroid Build Coastguard Worker     std::unique_ptr<ModuleSummaryIndex> Index = getModuleSummaryIndexForFile(F);
1341*9880d681SAndroid Build Coastguard Worker 
1342*9880d681SAndroid Build Coastguard Worker     // Use gold's symbol resolution information to identify symbols referenced
1343*9880d681SAndroid Build Coastguard Worker     // by more than a single IR module (i.e. referenced by multiple IR modules
1344*9880d681SAndroid Build Coastguard Worker     // or by a non-IR module). Cross references introduced by importing are
1345*9880d681SAndroid Build Coastguard Worker     // checked separately via the export lists. Also track the prevailing copy
1346*9880d681SAndroid Build Coastguard Worker     // for later symbol resolution.
1347*9880d681SAndroid Build Coastguard Worker     for (auto &Sym : F.syms) {
1348*9880d681SAndroid Build Coastguard Worker       ld_plugin_symbol_resolution Resolution =
1349*9880d681SAndroid Build Coastguard Worker           (ld_plugin_symbol_resolution)Sym.resolution;
1350*9880d681SAndroid Build Coastguard Worker       GlobalValue::GUID SymGUID = GlobalValue::getGUID(Sym.name);
1351*9880d681SAndroid Build Coastguard Worker       if (Resolution != LDPR_PREVAILING_DEF_IRONLY)
1352*9880d681SAndroid Build Coastguard Worker         Preserve.insert(SymGUID);
1353*9880d681SAndroid Build Coastguard Worker 
1354*9880d681SAndroid Build Coastguard Worker       if (Index && (Resolution == LDPR_PREVAILING_DEF ||
1355*9880d681SAndroid Build Coastguard Worker                     Resolution == LDPR_PREVAILING_DEF_IRONLY ||
1356*9880d681SAndroid Build Coastguard Worker                     Resolution == LDPR_PREVAILING_DEF_IRONLY_EXP))
1357*9880d681SAndroid Build Coastguard Worker         PrevailingCopy[SymGUID] = Index->getGlobalValueSummary(SymGUID);
1358*9880d681SAndroid Build Coastguard Worker     }
1359*9880d681SAndroid Build Coastguard Worker 
1360*9880d681SAndroid Build Coastguard Worker     // Skip files without a module summary.
1361*9880d681SAndroid Build Coastguard Worker     if (Index)
1362*9880d681SAndroid Build Coastguard Worker       CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
1363*9880d681SAndroid Build Coastguard Worker   }
1364*9880d681SAndroid Build Coastguard Worker 
1365*9880d681SAndroid Build Coastguard Worker   // Collect for each module the list of function it defines (GUID ->
1366*9880d681SAndroid Build Coastguard Worker   // Summary).
1367*9880d681SAndroid Build Coastguard Worker   StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
1368*9880d681SAndroid Build Coastguard Worker       ModuleToDefinedGVSummaries(NextModuleId);
1369*9880d681SAndroid Build Coastguard Worker   CombinedIndex.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1370*9880d681SAndroid Build Coastguard Worker 
1371*9880d681SAndroid Build Coastguard Worker   StringMap<FunctionImporter::ImportMapTy> ImportLists(NextModuleId);
1372*9880d681SAndroid Build Coastguard Worker   StringMap<FunctionImporter::ExportSetTy> ExportLists(NextModuleId);
1373*9880d681SAndroid Build Coastguard Worker   ComputeCrossModuleImport(CombinedIndex, ModuleToDefinedGVSummaries,
1374*9880d681SAndroid Build Coastguard Worker                            ImportLists, ExportLists);
1375*9880d681SAndroid Build Coastguard Worker 
1376*9880d681SAndroid Build Coastguard Worker   auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
1377*9880d681SAndroid Build Coastguard Worker     const auto &Prevailing = PrevailingCopy.find(GUID);
1378*9880d681SAndroid Build Coastguard Worker     assert(Prevailing != PrevailingCopy.end());
1379*9880d681SAndroid Build Coastguard Worker     return Prevailing->second == S;
1380*9880d681SAndroid Build Coastguard Worker   };
1381*9880d681SAndroid Build Coastguard Worker 
1382*9880d681SAndroid Build Coastguard Worker   // Callback for internalization, to prevent internalization of symbols
1383*9880d681SAndroid Build Coastguard Worker   // that were not candidates initially, and those that are being imported
1384*9880d681SAndroid Build Coastguard Worker   // (which introduces new cross references).
1385*9880d681SAndroid Build Coastguard Worker   auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
1386*9880d681SAndroid Build Coastguard Worker     const auto &ExportList = ExportLists.find(ModuleIdentifier);
1387*9880d681SAndroid Build Coastguard Worker     return (ExportList != ExportLists.end() &&
1388*9880d681SAndroid Build Coastguard Worker             ExportList->second.count(GUID)) ||
1389*9880d681SAndroid Build Coastguard Worker            Preserve.count(GUID);
1390*9880d681SAndroid Build Coastguard Worker   };
1391*9880d681SAndroid Build Coastguard Worker 
1392*9880d681SAndroid Build Coastguard Worker   thinLTOResolveWeakForLinkerInIndex(
1393*9880d681SAndroid Build Coastguard Worker       CombinedIndex, isPrevailing,
1394*9880d681SAndroid Build Coastguard Worker       [](StringRef ModuleIdentifier, GlobalValue::GUID GUID,
1395*9880d681SAndroid Build Coastguard Worker          GlobalValue::LinkageTypes NewLinkage) {});
1396*9880d681SAndroid Build Coastguard Worker 
1397*9880d681SAndroid Build Coastguard Worker   // Use global summary-based analysis to identify symbols that can be
1398*9880d681SAndroid Build Coastguard Worker   // internalized (because they aren't exported or preserved as per callback).
1399*9880d681SAndroid Build Coastguard Worker   // Changes are made in the index, consumed in the ThinLTO backends.
1400*9880d681SAndroid Build Coastguard Worker   thinLTOInternalizeAndPromoteInIndex(CombinedIndex, isExported);
1401*9880d681SAndroid Build Coastguard Worker 
1402*9880d681SAndroid Build Coastguard Worker   if (options::thinlto_emit_imports_files && !options::thinlto_index_only)
1403*9880d681SAndroid Build Coastguard Worker     message(LDPL_WARNING,
1404*9880d681SAndroid Build Coastguard Worker             "thinlto-emit-imports-files ignored unless thinlto-index-only");
1405*9880d681SAndroid Build Coastguard Worker 
1406*9880d681SAndroid Build Coastguard Worker   if (options::thinlto_index_only) {
1407*9880d681SAndroid Build Coastguard Worker     // If the thinlto-prefix-replace option was specified, parse it and
1408*9880d681SAndroid Build Coastguard Worker     // extract the old and new prefixes.
1409*9880d681SAndroid Build Coastguard Worker     std::string OldPrefix, NewPrefix;
1410*9880d681SAndroid Build Coastguard Worker     getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
1411*9880d681SAndroid Build Coastguard Worker 
1412*9880d681SAndroid Build Coastguard Worker     // For each input bitcode file, generate an individual index that
1413*9880d681SAndroid Build Coastguard Worker     // contains summaries only for its own global values, and for any that
1414*9880d681SAndroid Build Coastguard Worker     // should be imported.
1415*9880d681SAndroid Build Coastguard Worker     for (claimed_file &F : Modules) {
1416*9880d681SAndroid Build Coastguard Worker       std::error_code EC;
1417*9880d681SAndroid Build Coastguard Worker 
1418*9880d681SAndroid Build Coastguard Worker       std::string NewModulePath =
1419*9880d681SAndroid Build Coastguard Worker           getThinLTOOutputFile(F.name, OldPrefix, NewPrefix);
1420*9880d681SAndroid Build Coastguard Worker       raw_fd_ostream OS((Twine(NewModulePath) + ".thinlto.bc").str(), EC,
1421*9880d681SAndroid Build Coastguard Worker                         sys::fs::OpenFlags::F_None);
1422*9880d681SAndroid Build Coastguard Worker       if (EC)
1423*9880d681SAndroid Build Coastguard Worker         message(LDPL_FATAL, "Unable to open %s.thinlto.bc for writing: %s",
1424*9880d681SAndroid Build Coastguard Worker                 NewModulePath.c_str(), EC.message().c_str());
1425*9880d681SAndroid Build Coastguard Worker       // Build a map of module to the GUIDs and summary objects that should
1426*9880d681SAndroid Build Coastguard Worker       // be written to its index.
1427*9880d681SAndroid Build Coastguard Worker       std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
1428*9880d681SAndroid Build Coastguard Worker       gatherImportedSummariesForModule(F.name, ModuleToDefinedGVSummaries,
1429*9880d681SAndroid Build Coastguard Worker                                        ImportLists, ModuleToSummariesForIndex);
1430*9880d681SAndroid Build Coastguard Worker       WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
1431*9880d681SAndroid Build Coastguard Worker 
1432*9880d681SAndroid Build Coastguard Worker       if (options::thinlto_emit_imports_files) {
1433*9880d681SAndroid Build Coastguard Worker         if ((EC = EmitImportsFiles(F.name,
1434*9880d681SAndroid Build Coastguard Worker                                    (Twine(NewModulePath) + ".imports").str(),
1435*9880d681SAndroid Build Coastguard Worker                                    ImportLists)))
1436*9880d681SAndroid Build Coastguard Worker           message(LDPL_FATAL, "Unable to open %s.imports",
1437*9880d681SAndroid Build Coastguard Worker                   NewModulePath.c_str(), EC.message().c_str());
1438*9880d681SAndroid Build Coastguard Worker       }
1439*9880d681SAndroid Build Coastguard Worker     }
1440*9880d681SAndroid Build Coastguard Worker 
1441*9880d681SAndroid Build Coastguard Worker     cleanup_hook();
1442*9880d681SAndroid Build Coastguard Worker     exit(0);
1443*9880d681SAndroid Build Coastguard Worker   }
1444*9880d681SAndroid Build Coastguard Worker 
1445*9880d681SAndroid Build Coastguard Worker   // Create OS in nested scope so that it will be closed on destruction.
1446*9880d681SAndroid Build Coastguard Worker   {
1447*9880d681SAndroid Build Coastguard Worker     std::error_code EC;
1448*9880d681SAndroid Build Coastguard Worker     raw_fd_ostream OS(output_name + ".thinlto.bc", EC,
1449*9880d681SAndroid Build Coastguard Worker                       sys::fs::OpenFlags::F_None);
1450*9880d681SAndroid Build Coastguard Worker     if (EC)
1451*9880d681SAndroid Build Coastguard Worker       message(LDPL_FATAL, "Unable to open %s.thinlto.bc for writing: %s",
1452*9880d681SAndroid Build Coastguard Worker               output_name.data(), EC.message().c_str());
1453*9880d681SAndroid Build Coastguard Worker     WriteIndexToFile(CombinedIndex, OS);
1454*9880d681SAndroid Build Coastguard Worker   }
1455*9880d681SAndroid Build Coastguard Worker 
1456*9880d681SAndroid Build Coastguard Worker   thinLTOBackends(ApiFile, CombinedIndex, ModuleMap, ImportLists,
1457*9880d681SAndroid Build Coastguard Worker                   ModuleToDefinedGVSummaries);
1458*9880d681SAndroid Build Coastguard Worker   return LDPS_OK;
1459*9880d681SAndroid Build Coastguard Worker }
1460*9880d681SAndroid Build Coastguard Worker 
1461*9880d681SAndroid Build Coastguard Worker /// gold informs us that all symbols have been read. At this point, we use
1462*9880d681SAndroid Build Coastguard Worker /// get_symbols to see if any of our definitions have been overridden by a
1463*9880d681SAndroid Build Coastguard Worker /// native object file. Then, perform optimization and codegen.
allSymbolsReadHook(raw_fd_ostream * ApiFile)1464*9880d681SAndroid Build Coastguard Worker static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
1465*9880d681SAndroid Build Coastguard Worker   if (Modules.empty())
1466*9880d681SAndroid Build Coastguard Worker     return LDPS_OK;
1467*9880d681SAndroid Build Coastguard Worker 
1468*9880d681SAndroid Build Coastguard Worker   if (unsigned NumOpts = options::extra.size())
1469*9880d681SAndroid Build Coastguard Worker     cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
1470*9880d681SAndroid Build Coastguard Worker 
1471*9880d681SAndroid Build Coastguard Worker   if (options::thinlto)
1472*9880d681SAndroid Build Coastguard Worker     return thinLTOLink(ApiFile);
1473*9880d681SAndroid Build Coastguard Worker 
1474*9880d681SAndroid Build Coastguard Worker   LLVMContext Context;
1475*9880d681SAndroid Build Coastguard Worker   Context.setDiscardValueNames(options::TheOutputType !=
1476*9880d681SAndroid Build Coastguard Worker                                options::OT_SAVE_TEMPS);
1477*9880d681SAndroid Build Coastguard Worker   Context.enableDebugTypeODRUniquing(); // Merge debug info types.
1478*9880d681SAndroid Build Coastguard Worker   Context.setDiagnosticHandler(diagnosticHandlerForContext, nullptr, true);
1479*9880d681SAndroid Build Coastguard Worker 
1480*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
1481*9880d681SAndroid Build Coastguard Worker   IRMover L(*Combined);
1482*9880d681SAndroid Build Coastguard Worker 
1483*9880d681SAndroid Build Coastguard Worker   StringSet<> Internalize;
1484*9880d681SAndroid Build Coastguard Worker   for (claimed_file &F : Modules) {
1485*9880d681SAndroid Build Coastguard Worker     // RAII object to manage the file opening and releasing interfaces with
1486*9880d681SAndroid Build Coastguard Worker     // gold.
1487*9880d681SAndroid Build Coastguard Worker     PluginInputFile InputFile(F.handle);
1488*9880d681SAndroid Build Coastguard Worker     const void *View = getSymbolsAndView(F);
1489*9880d681SAndroid Build Coastguard Worker     if (!View)
1490*9880d681SAndroid Build Coastguard Worker       continue;
1491*9880d681SAndroid Build Coastguard Worker     linkInModule(Context, L, F, View, F.name, ApiFile, Internalize);
1492*9880d681SAndroid Build Coastguard Worker   }
1493*9880d681SAndroid Build Coastguard Worker 
1494*9880d681SAndroid Build Coastguard Worker   for (const auto &Name : Internalize) {
1495*9880d681SAndroid Build Coastguard Worker     GlobalValue *GV = Combined->getNamedValue(Name.first());
1496*9880d681SAndroid Build Coastguard Worker     if (GV)
1497*9880d681SAndroid Build Coastguard Worker       internalize(*GV);
1498*9880d681SAndroid Build Coastguard Worker   }
1499*9880d681SAndroid Build Coastguard Worker 
1500*9880d681SAndroid Build Coastguard Worker   if (options::TheOutputType == options::OT_DISABLE)
1501*9880d681SAndroid Build Coastguard Worker     return LDPS_OK;
1502*9880d681SAndroid Build Coastguard Worker 
1503*9880d681SAndroid Build Coastguard Worker   if (options::TheOutputType != options::OT_NORMAL) {
1504*9880d681SAndroid Build Coastguard Worker     std::string path;
1505*9880d681SAndroid Build Coastguard Worker     if (options::TheOutputType == options::OT_BC_ONLY)
1506*9880d681SAndroid Build Coastguard Worker       path = output_name;
1507*9880d681SAndroid Build Coastguard Worker     else
1508*9880d681SAndroid Build Coastguard Worker       path = output_name + ".bc";
1509*9880d681SAndroid Build Coastguard Worker     saveBCFile(path, *Combined);
1510*9880d681SAndroid Build Coastguard Worker     if (options::TheOutputType == options::OT_BC_ONLY)
1511*9880d681SAndroid Build Coastguard Worker       return LDPS_OK;
1512*9880d681SAndroid Build Coastguard Worker   }
1513*9880d681SAndroid Build Coastguard Worker 
1514*9880d681SAndroid Build Coastguard Worker   CodeGen codeGen(std::move(Combined));
1515*9880d681SAndroid Build Coastguard Worker   codeGen.runAll();
1516*9880d681SAndroid Build Coastguard Worker 
1517*9880d681SAndroid Build Coastguard Worker   if (!options::extra_library_path.empty() &&
1518*9880d681SAndroid Build Coastguard Worker       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
1519*9880d681SAndroid Build Coastguard Worker     message(LDPL_FATAL, "Unable to set the extra library path.");
1520*9880d681SAndroid Build Coastguard Worker 
1521*9880d681SAndroid Build Coastguard Worker   return LDPS_OK;
1522*9880d681SAndroid Build Coastguard Worker }
1523*9880d681SAndroid Build Coastguard Worker 
all_symbols_read_hook(void)1524*9880d681SAndroid Build Coastguard Worker static ld_plugin_status all_symbols_read_hook(void) {
1525*9880d681SAndroid Build Coastguard Worker   ld_plugin_status Ret;
1526*9880d681SAndroid Build Coastguard Worker   if (!options::generate_api_file) {
1527*9880d681SAndroid Build Coastguard Worker     Ret = allSymbolsReadHook(nullptr);
1528*9880d681SAndroid Build Coastguard Worker   } else {
1529*9880d681SAndroid Build Coastguard Worker     std::error_code EC;
1530*9880d681SAndroid Build Coastguard Worker     raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
1531*9880d681SAndroid Build Coastguard Worker     if (EC)
1532*9880d681SAndroid Build Coastguard Worker       message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
1533*9880d681SAndroid Build Coastguard Worker               EC.message().c_str());
1534*9880d681SAndroid Build Coastguard Worker     Ret = allSymbolsReadHook(&ApiFile);
1535*9880d681SAndroid Build Coastguard Worker   }
1536*9880d681SAndroid Build Coastguard Worker 
1537*9880d681SAndroid Build Coastguard Worker   llvm_shutdown();
1538*9880d681SAndroid Build Coastguard Worker 
1539*9880d681SAndroid Build Coastguard Worker   if (options::TheOutputType == options::OT_BC_ONLY ||
1540*9880d681SAndroid Build Coastguard Worker       options::TheOutputType == options::OT_DISABLE) {
1541*9880d681SAndroid Build Coastguard Worker     if (options::TheOutputType == options::OT_DISABLE) {
1542*9880d681SAndroid Build Coastguard Worker       // Remove the output file here since ld.bfd creates the output file
1543*9880d681SAndroid Build Coastguard Worker       // early.
1544*9880d681SAndroid Build Coastguard Worker       std::error_code EC = sys::fs::remove(output_name);
1545*9880d681SAndroid Build Coastguard Worker       if (EC)
1546*9880d681SAndroid Build Coastguard Worker         message(LDPL_ERROR, "Failed to delete '%s': %s", output_name.c_str(),
1547*9880d681SAndroid Build Coastguard Worker                 EC.message().c_str());
1548*9880d681SAndroid Build Coastguard Worker     }
1549*9880d681SAndroid Build Coastguard Worker     exit(0);
1550*9880d681SAndroid Build Coastguard Worker   }
1551*9880d681SAndroid Build Coastguard Worker 
1552*9880d681SAndroid Build Coastguard Worker   return Ret;
1553*9880d681SAndroid Build Coastguard Worker }
1554*9880d681SAndroid Build Coastguard Worker 
cleanup_hook(void)1555*9880d681SAndroid Build Coastguard Worker static ld_plugin_status cleanup_hook(void) {
1556*9880d681SAndroid Build Coastguard Worker   for (std::string &Name : Cleanup) {
1557*9880d681SAndroid Build Coastguard Worker     std::error_code EC = sys::fs::remove(Name);
1558*9880d681SAndroid Build Coastguard Worker     if (EC)
1559*9880d681SAndroid Build Coastguard Worker       message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
1560*9880d681SAndroid Build Coastguard Worker               EC.message().c_str());
1561*9880d681SAndroid Build Coastguard Worker   }
1562*9880d681SAndroid Build Coastguard Worker 
1563*9880d681SAndroid Build Coastguard Worker   return LDPS_OK;
1564*9880d681SAndroid Build Coastguard Worker }
1565