1 //===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization  ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is a gold plugin for LLVM. It provides an LLVM implementation of the
11 // interface described in http://gcc.gnu.org/wiki/whopr/driver .
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Config/config.h" // plugin-api.h requires HAVE_STDINT_H
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/StringSet.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/CodeGen/Analysis.h"
22 #include "llvm/CodeGen/CommandFlags.h"
23 #include "llvm/CodeGen/ParallelCG.h"
24 #include "llvm/IR/AutoUpgrade.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 #include "llvm/IR/DiagnosticPrinter.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/LegacyPassManager.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Verifier.h"
32 #include "llvm/Linker/IRMover.h"
33 #include "llvm/MC/SubtargetFeature.h"
34 #include "llvm/Object/FunctionIndexObjectFile.h"
35 #include "llvm/Object/IRObjectFile.h"
36 #include "llvm/Support/Host.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Transforms/IPO.h"
43 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
44 #include "llvm/Transforms/Utils/GlobalStatus.h"
45 #include "llvm/Transforms/Utils/ModuleUtils.h"
46 #include "llvm/Transforms/Utils/ValueMapper.h"
47 #include <list>
48 #include <plugin-api.h>
49 #include <system_error>
50 #include <vector>
51 
52 #ifndef LDPO_PIE
53 // FIXME: remove this declaration when we stop maintaining Ubuntu Quantal and
54 // Precise and Debian Wheezy (binutils 2.23 is required)
55 # define LDPO_PIE 3
56 #endif
57 
58 using namespace llvm;
59 
60 static ld_plugin_status discard_message(int level, const char *format, ...) {
61   // Die loudly. Recent versions of Gold pass ld_plugin_message as the first
62   // callback in the transfer vector. This should never be called.
63   abort();
64 }
65 
66 static ld_plugin_release_input_file release_input_file = nullptr;
67 static ld_plugin_get_input_file get_input_file = nullptr;
68 static ld_plugin_message message = discard_message;
69 
70 namespace {
71 struct claimed_file {
72   void *handle;
73   std::vector<ld_plugin_symbol> syms;
74 };
75 
76 /// RAII wrapper to manage opening and releasing of a ld_plugin_input_file.
77 struct PluginInputFile {
78   void *Handle;
79   ld_plugin_input_file File;
80 
81   PluginInputFile(void *Handle) : Handle(Handle) {
82     if (get_input_file(Handle, &File) != LDPS_OK)
83       message(LDPL_FATAL, "Failed to get file information");
84   }
85   ~PluginInputFile() {
86     if (release_input_file(Handle) != LDPS_OK)
87       message(LDPL_FATAL, "Failed to release file information");
88   }
89   ld_plugin_input_file &file() { return File; }
90 };
91 
92 struct ResolutionInfo {
93   bool IsLinkonceOdr = true;
94   bool UnnamedAddr = true;
95   GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
96   bool CommonInternal = false;
97   bool UseCommon = false;
98   unsigned CommonSize = 0;
99   unsigned CommonAlign = 0;
100   claimed_file *CommonFile = nullptr;
101 };
102 }
103 
104 static ld_plugin_add_symbols add_symbols = nullptr;
105 static ld_plugin_get_symbols get_symbols = nullptr;
106 static ld_plugin_add_input_file add_input_file = nullptr;
107 static ld_plugin_set_extra_library_path set_extra_library_path = nullptr;
108 static ld_plugin_get_view get_view = nullptr;
109 static Reloc::Model RelocationModel = Reloc::Default;
110 static std::string output_name = "";
111 static std::list<claimed_file> Modules;
112 static StringMap<ResolutionInfo> ResInfo;
113 static std::vector<std::string> Cleanup;
114 static llvm::TargetOptions TargetOpts;
115 
116 namespace options {
117   enum OutputType {
118     OT_NORMAL,
119     OT_DISABLE,
120     OT_BC_ONLY,
121     OT_SAVE_TEMPS
122   };
123   static bool generate_api_file = false;
124   static OutputType TheOutputType = OT_NORMAL;
125   static unsigned OptLevel = 2;
126   static unsigned Parallelism = 1;
127 #ifdef NDEBUG
128   static bool DisableVerify = true;
129 #else
130   static bool DisableVerify = false;
131 #endif
132   static std::string obj_path;
133   static std::string extra_library_path;
134   static std::string triple;
135   static std::string mcpu;
136   // When the thinlto plugin option is specified, only read the function
137   // the information from intermediate files and write a combined
138   // global index for the ThinLTO backends.
139   static bool thinlto = false;
140   // Additional options to pass into the code generator.
141   // Note: This array will contain all plugin options which are not claimed
142   // as plugin exclusive to pass to the code generator.
143   // For example, "generate-api-file" and "as"options are for the plugin
144   // use only and will not be passed.
145   static std::vector<const char *> extra;
146 
147   static void process_plugin_option(const char *opt_)
148   {
149     if (opt_ == nullptr)
150       return;
151     llvm::StringRef opt = opt_;
152 
153     if (opt == "generate-api-file") {
154       generate_api_file = true;
155     } else if (opt.startswith("mcpu=")) {
156       mcpu = opt.substr(strlen("mcpu="));
157     } else if (opt.startswith("extra-library-path=")) {
158       extra_library_path = opt.substr(strlen("extra_library_path="));
159     } else if (opt.startswith("mtriple=")) {
160       triple = opt.substr(strlen("mtriple="));
161     } else if (opt.startswith("obj-path=")) {
162       obj_path = opt.substr(strlen("obj-path="));
163     } else if (opt == "emit-llvm") {
164       TheOutputType = OT_BC_ONLY;
165     } else if (opt == "save-temps") {
166       TheOutputType = OT_SAVE_TEMPS;
167     } else if (opt == "disable-output") {
168       TheOutputType = OT_DISABLE;
169     } else if (opt == "thinlto") {
170       thinlto = true;
171     } else if (opt.size() == 2 && opt[0] == 'O') {
172       if (opt[1] < '0' || opt[1] > '3')
173         message(LDPL_FATAL, "Optimization level must be between 0 and 3");
174       OptLevel = opt[1] - '0';
175     } else if (opt.startswith("jobs=")) {
176       if (StringRef(opt_ + 5).getAsInteger(10, Parallelism))
177         message(LDPL_FATAL, "Invalid parallelism level: %s", opt_ + 5);
178     } else if (opt == "disable-verify") {
179       DisableVerify = true;
180     } else {
181       // Save this option to pass to the code generator.
182       // ParseCommandLineOptions() expects argv[0] to be program name. Lazily
183       // add that.
184       if (extra.empty())
185         extra.push_back("LLVMgold");
186 
187       extra.push_back(opt_);
188     }
189   }
190 }
191 
192 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
193                                         int *claimed);
194 static ld_plugin_status all_symbols_read_hook(void);
195 static ld_plugin_status cleanup_hook(void);
196 
197 extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
198 ld_plugin_status onload(ld_plugin_tv *tv) {
199   InitializeAllTargetInfos();
200   InitializeAllTargets();
201   InitializeAllTargetMCs();
202   InitializeAllAsmParsers();
203   InitializeAllAsmPrinters();
204 
205   // We're given a pointer to the first transfer vector. We read through them
206   // until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
207   // contain pointers to functions that we need to call to register our own
208   // hooks. The others are addresses of functions we can use to call into gold
209   // for services.
210 
211   bool registeredClaimFile = false;
212   bool RegisteredAllSymbolsRead = false;
213 
214   for (; tv->tv_tag != LDPT_NULL; ++tv) {
215     switch (tv->tv_tag) {
216       case LDPT_OUTPUT_NAME:
217         output_name = tv->tv_u.tv_string;
218         break;
219       case LDPT_LINKER_OUTPUT:
220         switch (tv->tv_u.tv_val) {
221           case LDPO_REL:  // .o
222           case LDPO_DYN:  // .so
223           case LDPO_PIE:  // position independent executable
224             RelocationModel = Reloc::PIC_;
225             break;
226           case LDPO_EXEC:  // .exe
227             RelocationModel = Reloc::Static;
228             break;
229           default:
230             message(LDPL_ERROR, "Unknown output file type %d", tv->tv_u.tv_val);
231             return LDPS_ERR;
232         }
233         break;
234       case LDPT_OPTION:
235         options::process_plugin_option(tv->tv_u.tv_string);
236         break;
237       case LDPT_REGISTER_CLAIM_FILE_HOOK: {
238         ld_plugin_register_claim_file callback;
239         callback = tv->tv_u.tv_register_claim_file;
240 
241         if (callback(claim_file_hook) != LDPS_OK)
242           return LDPS_ERR;
243 
244         registeredClaimFile = true;
245       } break;
246       case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
247         ld_plugin_register_all_symbols_read callback;
248         callback = tv->tv_u.tv_register_all_symbols_read;
249 
250         if (callback(all_symbols_read_hook) != LDPS_OK)
251           return LDPS_ERR;
252 
253         RegisteredAllSymbolsRead = true;
254       } break;
255       case LDPT_REGISTER_CLEANUP_HOOK: {
256         ld_plugin_register_cleanup callback;
257         callback = tv->tv_u.tv_register_cleanup;
258 
259         if (callback(cleanup_hook) != LDPS_OK)
260           return LDPS_ERR;
261       } break;
262       case LDPT_GET_INPUT_FILE:
263         get_input_file = tv->tv_u.tv_get_input_file;
264         break;
265       case LDPT_RELEASE_INPUT_FILE:
266         release_input_file = tv->tv_u.tv_release_input_file;
267         break;
268       case LDPT_ADD_SYMBOLS:
269         add_symbols = tv->tv_u.tv_add_symbols;
270         break;
271       case LDPT_GET_SYMBOLS_V2:
272         get_symbols = tv->tv_u.tv_get_symbols;
273         break;
274       case LDPT_ADD_INPUT_FILE:
275         add_input_file = tv->tv_u.tv_add_input_file;
276         break;
277       case LDPT_SET_EXTRA_LIBRARY_PATH:
278         set_extra_library_path = tv->tv_u.tv_set_extra_library_path;
279         break;
280       case LDPT_GET_VIEW:
281         get_view = tv->tv_u.tv_get_view;
282         break;
283       case LDPT_MESSAGE:
284         message = tv->tv_u.tv_message;
285         break;
286       default:
287         break;
288     }
289   }
290 
291   if (!registeredClaimFile) {
292     message(LDPL_ERROR, "register_claim_file not passed to LLVMgold.");
293     return LDPS_ERR;
294   }
295   if (!add_symbols) {
296     message(LDPL_ERROR, "add_symbols not passed to LLVMgold.");
297     return LDPS_ERR;
298   }
299 
300   if (!RegisteredAllSymbolsRead)
301     return LDPS_OK;
302 
303   if (!get_input_file) {
304     message(LDPL_ERROR, "get_input_file not passed to LLVMgold.");
305     return LDPS_ERR;
306   }
307   if (!release_input_file) {
308     message(LDPL_ERROR, "relesase_input_file not passed to LLVMgold.");
309     return LDPS_ERR;
310   }
311 
312   return LDPS_OK;
313 }
314 
315 static const GlobalObject *getBaseObject(const GlobalValue &GV) {
316   if (auto *GA = dyn_cast<GlobalAlias>(&GV))
317     return GA->getBaseObject();
318   return cast<GlobalObject>(&GV);
319 }
320 
321 static bool shouldSkip(uint32_t Symflags) {
322   if (!(Symflags & object::BasicSymbolRef::SF_Global))
323     return true;
324   if (Symflags & object::BasicSymbolRef::SF_FormatSpecific)
325     return true;
326   return false;
327 }
328 
329 static void diagnosticHandler(const DiagnosticInfo &DI) {
330   if (const auto *BDI = dyn_cast<BitcodeDiagnosticInfo>(&DI)) {
331     std::error_code EC = BDI->getError();
332     if (EC == BitcodeError::InvalidBitcodeSignature)
333       return;
334   }
335 
336   std::string ErrStorage;
337   {
338     raw_string_ostream OS(ErrStorage);
339     DiagnosticPrinterRawOStream DP(OS);
340     DI.print(DP);
341   }
342   ld_plugin_level Level;
343   switch (DI.getSeverity()) {
344   case DS_Error:
345     message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
346             ErrStorage.c_str());
347   case DS_Warning:
348     Level = LDPL_WARNING;
349     break;
350   case DS_Note:
351   case DS_Remark:
352     Level = LDPL_INFO;
353     break;
354   }
355   message(Level, "LLVM gold plugin: %s",  ErrStorage.c_str());
356 }
357 
358 static void diagnosticHandlerForContext(const DiagnosticInfo &DI,
359                                         void *Context) {
360   diagnosticHandler(DI);
361 }
362 
363 static GlobalValue::VisibilityTypes
364 getMinVisibility(GlobalValue::VisibilityTypes A,
365                  GlobalValue::VisibilityTypes B) {
366   if (A == GlobalValue::HiddenVisibility)
367     return A;
368   if (B == GlobalValue::HiddenVisibility)
369     return B;
370   if (A == GlobalValue::ProtectedVisibility)
371     return A;
372   return B;
373 }
374 
375 /// Called by gold to see whether this file is one that our plugin can handle.
376 /// We'll try to open it and register all the symbols with add_symbol if
377 /// possible.
378 static ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
379                                         int *claimed) {
380   LLVMContext Context;
381   MemoryBufferRef BufferRef;
382   std::unique_ptr<MemoryBuffer> Buffer;
383   if (get_view) {
384     const void *view;
385     if (get_view(file->handle, &view) != LDPS_OK) {
386       message(LDPL_ERROR, "Failed to get a view of %s", file->name);
387       return LDPS_ERR;
388     }
389     BufferRef =
390         MemoryBufferRef(StringRef((const char *)view, file->filesize), "");
391   } else {
392     int64_t offset = 0;
393     // Gold has found what might be IR part-way inside of a file, such as
394     // an .a archive.
395     if (file->offset) {
396       offset = file->offset;
397     }
398     ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
399         MemoryBuffer::getOpenFileSlice(file->fd, file->name, file->filesize,
400                                        offset);
401     if (std::error_code EC = BufferOrErr.getError()) {
402       message(LDPL_ERROR, EC.message().c_str());
403       return LDPS_ERR;
404     }
405     Buffer = std::move(BufferOrErr.get());
406     BufferRef = Buffer->getMemBufferRef();
407   }
408 
409   Context.setDiagnosticHandler(diagnosticHandlerForContext);
410   ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
411       object::IRObjectFile::create(BufferRef, Context);
412   std::error_code EC = ObjOrErr.getError();
413   if (EC == object::object_error::invalid_file_type ||
414       EC == object::object_error::bitcode_section_not_found)
415     return LDPS_OK;
416 
417   *claimed = 1;
418 
419   if (EC) {
420     message(LDPL_ERROR, "LLVM gold plugin has failed to create LTO module: %s",
421             EC.message().c_str());
422     return LDPS_ERR;
423   }
424   std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
425 
426   Modules.resize(Modules.size() + 1);
427   claimed_file &cf = Modules.back();
428 
429   cf.handle = file->handle;
430 
431   // If we are doing ThinLTO compilation, don't need to process the symbols.
432   // Later we simply build a combined index file after all files are claimed.
433   if (options::thinlto)
434     return LDPS_OK;
435 
436   for (auto &Sym : Obj->symbols()) {
437     uint32_t Symflags = Sym.getFlags();
438     if (shouldSkip(Symflags))
439       continue;
440 
441     cf.syms.push_back(ld_plugin_symbol());
442     ld_plugin_symbol &sym = cf.syms.back();
443     sym.version = nullptr;
444 
445     SmallString<64> Name;
446     {
447       raw_svector_ostream OS(Name);
448       Sym.printName(OS);
449     }
450     sym.name = strdup(Name.c_str());
451 
452     const GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
453 
454     ResolutionInfo &Res = ResInfo[sym.name];
455 
456     sym.visibility = LDPV_DEFAULT;
457     if (GV) {
458       Res.UnnamedAddr &= GV->hasUnnamedAddr();
459       Res.IsLinkonceOdr &= GV->hasLinkOnceLinkage();
460       if (GV->hasCommonLinkage()) {
461         Res.CommonAlign = std::max(Res.CommonAlign, GV->getAlignment());
462         const DataLayout &DL = GV->getParent()->getDataLayout();
463         uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
464         if (Size >= Res.CommonSize) {
465           Res.CommonSize = Size;
466           Res.CommonFile = &cf;
467         }
468       }
469       Res.Visibility = getMinVisibility(Res.Visibility, GV->getVisibility());
470       switch (GV->getVisibility()) {
471       case GlobalValue::DefaultVisibility:
472         sym.visibility = LDPV_DEFAULT;
473         break;
474       case GlobalValue::HiddenVisibility:
475         sym.visibility = LDPV_HIDDEN;
476         break;
477       case GlobalValue::ProtectedVisibility:
478         sym.visibility = LDPV_PROTECTED;
479         break;
480       }
481     }
482 
483     if (Symflags & object::BasicSymbolRef::SF_Undefined) {
484       sym.def = LDPK_UNDEF;
485       if (GV && GV->hasExternalWeakLinkage())
486         sym.def = LDPK_WEAKUNDEF;
487     } else {
488       sym.def = LDPK_DEF;
489       if (GV) {
490         assert(!GV->hasExternalWeakLinkage() &&
491                !GV->hasAvailableExternallyLinkage() && "Not a declaration!");
492         if (GV->hasCommonLinkage())
493           sym.def = LDPK_COMMON;
494         else if (GV->isWeakForLinker())
495           sym.def = LDPK_WEAKDEF;
496       }
497     }
498 
499     sym.size = 0;
500     sym.comdat_key = nullptr;
501     if (GV) {
502       const GlobalObject *Base = getBaseObject(*GV);
503       if (!Base)
504         message(LDPL_FATAL, "Unable to determine comdat of alias!");
505       const Comdat *C = Base->getComdat();
506       if (C)
507         sym.comdat_key = strdup(C->getName().str().c_str());
508     }
509 
510     sym.resolution = LDPR_UNKNOWN;
511   }
512 
513   if (!cf.syms.empty()) {
514     if (add_symbols(cf.handle, cf.syms.size(), cf.syms.data()) != LDPS_OK) {
515       message(LDPL_ERROR, "Unable to add symbols!");
516       return LDPS_ERR;
517     }
518   }
519 
520   return LDPS_OK;
521 }
522 
523 static void internalize(GlobalValue &GV) {
524   if (GV.isDeclarationForLinker())
525     return; // We get here if there is a matching asm definition.
526   if (!GV.hasLocalLinkage())
527     GV.setLinkage(GlobalValue::InternalLinkage);
528 }
529 
530 static const char *getResolutionName(ld_plugin_symbol_resolution R) {
531   switch (R) {
532   case LDPR_UNKNOWN:
533     return "UNKNOWN";
534   case LDPR_UNDEF:
535     return "UNDEF";
536   case LDPR_PREVAILING_DEF:
537     return "PREVAILING_DEF";
538   case LDPR_PREVAILING_DEF_IRONLY:
539     return "PREVAILING_DEF_IRONLY";
540   case LDPR_PREEMPTED_REG:
541     return "PREEMPTED_REG";
542   case LDPR_PREEMPTED_IR:
543     return "PREEMPTED_IR";
544   case LDPR_RESOLVED_IR:
545     return "RESOLVED_IR";
546   case LDPR_RESOLVED_EXEC:
547     return "RESOLVED_EXEC";
548   case LDPR_RESOLVED_DYN:
549     return "RESOLVED_DYN";
550   case LDPR_PREVAILING_DEF_IRONLY_EXP:
551     return "PREVAILING_DEF_IRONLY_EXP";
552   }
553   llvm_unreachable("Unknown resolution");
554 }
555 
556 static void freeSymName(ld_plugin_symbol &Sym) {
557   free(Sym.name);
558   free(Sym.comdat_key);
559   Sym.name = nullptr;
560   Sym.comdat_key = nullptr;
561 }
562 
563 static std::unique_ptr<FunctionInfoIndex>
564 getFunctionIndexForFile(claimed_file &F, ld_plugin_input_file &Info) {
565 
566   if (get_symbols(F.handle, F.syms.size(), &F.syms[0]) != LDPS_OK)
567     message(LDPL_FATAL, "Failed to get symbol information");
568 
569   const void *View;
570   if (get_view(F.handle, &View) != LDPS_OK)
571     message(LDPL_FATAL, "Failed to get a view of file");
572 
573   MemoryBufferRef BufferRef(StringRef((const char *)View, Info.filesize),
574                             Info.name);
575 
576   // Don't bother trying to build an index if there is no summary information
577   // in this bitcode file.
578   if (!object::FunctionIndexObjectFile::hasFunctionSummaryInMemBuffer(
579           BufferRef, diagnosticHandler))
580     return std::unique_ptr<FunctionInfoIndex>(nullptr);
581 
582   ErrorOr<std::unique_ptr<object::FunctionIndexObjectFile>> ObjOrErr =
583       object::FunctionIndexObjectFile::create(BufferRef, diagnosticHandler);
584 
585   if (std::error_code EC = ObjOrErr.getError())
586     message(LDPL_FATAL, "Could not read function index bitcode from file : %s",
587             EC.message().c_str());
588 
589   object::FunctionIndexObjectFile &Obj = **ObjOrErr;
590 
591   return Obj.takeIndex();
592 }
593 
594 static std::unique_ptr<Module>
595 getModuleForFile(LLVMContext &Context, claimed_file &F,
596                  ld_plugin_input_file &Info, raw_fd_ostream *ApiFile,
597                  StringSet<> &Internalize, StringSet<> &Maybe,
598                  std::vector<GlobalValue *> &Keep) {
599 
600   if (get_symbols(F.handle, F.syms.size(), F.syms.data()) != LDPS_OK)
601     message(LDPL_FATAL, "Failed to get symbol information");
602 
603   const void *View;
604   if (get_view(F.handle, &View) != LDPS_OK)
605     message(LDPL_FATAL, "Failed to get a view of file");
606 
607   MemoryBufferRef BufferRef(StringRef((const char *)View, Info.filesize),
608                             Info.name);
609   ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
610       object::IRObjectFile::create(BufferRef, Context);
611 
612   if (std::error_code EC = ObjOrErr.getError())
613     message(LDPL_FATAL, "Could not read bitcode from file : %s",
614             EC.message().c_str());
615 
616   object::IRObjectFile &Obj = **ObjOrErr;
617 
618   Module &M = Obj.getModule();
619 
620   M.materializeMetadata();
621   UpgradeDebugInfo(M);
622 
623   SmallPtrSet<GlobalValue *, 8> Used;
624   collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
625 
626   unsigned SymNum = 0;
627   for (auto &ObjSym : Obj.symbols()) {
628     GlobalValue *GV = Obj.getSymbolGV(ObjSym.getRawDataRefImpl());
629     if (GV && GV->hasAppendingLinkage())
630       Keep.push_back(GV);
631 
632     if (shouldSkip(ObjSym.getFlags()))
633       continue;
634     ld_plugin_symbol &Sym = F.syms[SymNum];
635     ++SymNum;
636 
637     ld_plugin_symbol_resolution Resolution =
638         (ld_plugin_symbol_resolution)Sym.resolution;
639 
640     if (options::generate_api_file)
641       *ApiFile << Sym.name << ' ' << getResolutionName(Resolution) << '\n';
642 
643     if (!GV) {
644       freeSymName(Sym);
645       continue; // Asm symbol.
646     }
647 
648     ResolutionInfo &Res = ResInfo[Sym.name];
649     if (Resolution == LDPR_PREVAILING_DEF_IRONLY_EXP && !Res.IsLinkonceOdr)
650       Resolution = LDPR_PREVAILING_DEF;
651 
652     GV->setUnnamedAddr(Res.UnnamedAddr);
653     GV->setVisibility(Res.Visibility);
654 
655     // Override gold's resolution for common symbols. We want the largest
656     // one to win.
657     if (GV->hasCommonLinkage()) {
658       cast<GlobalVariable>(GV)->setAlignment(Res.CommonAlign);
659       if (Resolution == LDPR_PREVAILING_DEF_IRONLY)
660         Res.CommonInternal = true;
661 
662       if (Resolution == LDPR_PREVAILING_DEF_IRONLY ||
663           Resolution == LDPR_PREVAILING_DEF)
664         Res.UseCommon = true;
665 
666       if (Res.CommonFile == &F && Res.UseCommon) {
667         if (Res.CommonInternal)
668           Resolution = LDPR_PREVAILING_DEF_IRONLY;
669         else
670           Resolution = LDPR_PREVAILING_DEF;
671       } else {
672         Resolution = LDPR_PREEMPTED_IR;
673       }
674     }
675 
676     switch (Resolution) {
677     case LDPR_UNKNOWN:
678       llvm_unreachable("Unexpected resolution");
679 
680     case LDPR_RESOLVED_IR:
681     case LDPR_RESOLVED_EXEC:
682     case LDPR_RESOLVED_DYN:
683     case LDPR_PREEMPTED_IR:
684     case LDPR_PREEMPTED_REG:
685       break;
686 
687     case LDPR_UNDEF:
688       if (!GV->isDeclarationForLinker())
689         assert(GV->hasComdat());
690       break;
691 
692     case LDPR_PREVAILING_DEF_IRONLY: {
693       Keep.push_back(GV);
694       // The IR linker has to be able to map this value to a declaration,
695       // so we can only internalize after linking.
696       if (!Used.count(GV))
697         Internalize.insert(GV->getName());
698       break;
699     }
700 
701     case LDPR_PREVAILING_DEF:
702       Keep.push_back(GV);
703       // There is a non IR use, so we have to force optimizations to keep this.
704       switch (GV->getLinkage()) {
705       default:
706         break;
707       case GlobalValue::LinkOnceAnyLinkage:
708         GV->setLinkage(GlobalValue::WeakAnyLinkage);
709         break;
710       case GlobalValue::LinkOnceODRLinkage:
711         GV->setLinkage(GlobalValue::WeakODRLinkage);
712         break;
713       }
714       break;
715 
716     case LDPR_PREVAILING_DEF_IRONLY_EXP: {
717       // We can only check for address uses after we merge the modules. The
718       // reason is that this GV might have a copy in another module
719       // and in that module the address might be significant, but that
720       // copy will be LDPR_PREEMPTED_IR.
721       Maybe.insert(GV->getName());
722       Keep.push_back(GV);
723       break;
724     }
725     }
726 
727     freeSymName(Sym);
728   }
729 
730   return Obj.takeModule();
731 }
732 
733 static void runLTOPasses(Module &M, TargetMachine &TM) {
734   M.setDataLayout(TM.createDataLayout());
735 
736   legacy::PassManager passes;
737   passes.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
738 
739   PassManagerBuilder PMB;
740   PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
741   PMB.Inliner = createFunctionInliningPass();
742   // Unconditionally verify input since it is not verified before this
743   // point and has unknown origin.
744   PMB.VerifyInput = true;
745   PMB.VerifyOutput = !options::DisableVerify;
746   PMB.LoopVectorize = true;
747   PMB.SLPVectorize = true;
748   PMB.OptLevel = options::OptLevel;
749   PMB.populateLTOPassManager(passes);
750   passes.run(M);
751 }
752 
753 static void saveBCFile(StringRef Path, Module &M) {
754   std::error_code EC;
755   raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
756   if (EC)
757     message(LDPL_FATAL, "Failed to write the output file.");
758   WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ false);
759 }
760 
761 static void codegen(std::unique_ptr<Module> M) {
762   const std::string &TripleStr = M->getTargetTriple();
763   Triple TheTriple(TripleStr);
764 
765   std::string ErrMsg;
766   const Target *TheTarget = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
767   if (!TheTarget)
768     message(LDPL_FATAL, "Target not found: %s", ErrMsg.c_str());
769 
770   if (unsigned NumOpts = options::extra.size())
771     cl::ParseCommandLineOptions(NumOpts, &options::extra[0]);
772 
773   SubtargetFeatures Features;
774   Features.getDefaultSubtargetFeatures(TheTriple);
775   for (const std::string &A : MAttrs)
776     Features.AddFeature(A);
777 
778   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
779   CodeGenOpt::Level CGOptLevel;
780   switch (options::OptLevel) {
781   case 0:
782     CGOptLevel = CodeGenOpt::None;
783     break;
784   case 1:
785     CGOptLevel = CodeGenOpt::Less;
786     break;
787   case 2:
788     CGOptLevel = CodeGenOpt::Default;
789     break;
790   case 3:
791     CGOptLevel = CodeGenOpt::Aggressive;
792     break;
793   }
794   std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
795       TripleStr, options::mcpu, Features.getString(), Options, RelocationModel,
796       CodeModel::Default, CGOptLevel));
797 
798   runLTOPasses(*M, *TM);
799 
800   if (options::TheOutputType == options::OT_SAVE_TEMPS)
801     saveBCFile(output_name + ".opt.bc", *M);
802 
803   SmallString<128> Filename;
804   if (!options::obj_path.empty())
805     Filename = options::obj_path;
806   else if (options::TheOutputType == options::OT_SAVE_TEMPS)
807     Filename = output_name + ".o";
808 
809   std::vector<SmallString<128>> Filenames(options::Parallelism);
810   bool TempOutFile = Filename.empty();
811   {
812     // Open a file descriptor for each backend thread. This is done in a block
813     // so that the output file descriptors are closed before gold opens them.
814     std::list<llvm::raw_fd_ostream> OSs;
815     std::vector<llvm::raw_pwrite_stream *> OSPtrs(options::Parallelism);
816     for (unsigned I = 0; I != options::Parallelism; ++I) {
817       int FD;
818       if (TempOutFile) {
819         std::error_code EC =
820             sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filenames[I]);
821         if (EC)
822           message(LDPL_FATAL, "Could not create temporary file: %s",
823                   EC.message().c_str());
824       } else {
825         Filenames[I] = Filename;
826         if (options::Parallelism != 1)
827           Filenames[I] += utostr(I);
828         std::error_code EC =
829             sys::fs::openFileForWrite(Filenames[I], FD, sys::fs::F_None);
830         if (EC)
831           message(LDPL_FATAL, "Could not open file: %s", EC.message().c_str());
832       }
833       OSs.emplace_back(FD, true);
834       OSPtrs[I] = &OSs.back();
835     }
836 
837     // Run backend threads.
838     splitCodeGen(std::move(M), OSPtrs, options::mcpu, Features.getString(),
839                  Options, RelocationModel, CodeModel::Default, CGOptLevel);
840   }
841 
842   for (auto &Filename : Filenames) {
843     if (add_input_file(Filename.c_str()) != LDPS_OK)
844       message(LDPL_FATAL,
845               "Unable to add .o file to the link. File left behind in: %s",
846               Filename.c_str());
847     if (TempOutFile)
848       Cleanup.push_back(Filename.c_str());
849   }
850 }
851 
852 /// gold informs us that all symbols have been read. At this point, we use
853 /// get_symbols to see if any of our definitions have been overridden by a
854 /// native object file. Then, perform optimization and codegen.
855 static ld_plugin_status allSymbolsReadHook(raw_fd_ostream *ApiFile) {
856   if (Modules.empty())
857     return LDPS_OK;
858 
859   // If we are doing ThinLTO compilation, simply build the combined
860   // function index/summary and emit it. We don't need to parse the modules
861   // and link them in this case.
862   if (options::thinlto) {
863     FunctionInfoIndex CombinedIndex;
864     uint64_t NextModuleId = 0;
865     for (claimed_file &F : Modules) {
866       PluginInputFile InputFile(F.handle);
867 
868       std::unique_ptr<FunctionInfoIndex> Index =
869           getFunctionIndexForFile(F, InputFile.file());
870 
871       // Skip files without a function summary.
872       if (Index)
873         CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
874     }
875 
876     std::error_code EC;
877     raw_fd_ostream OS(output_name + ".thinlto.bc", EC,
878                       sys::fs::OpenFlags::F_None);
879     if (EC)
880       message(LDPL_FATAL, "Unable to open %s.thinlto.bc for writing: %s",
881               output_name.data(), EC.message().c_str());
882     WriteFunctionSummaryToFile(CombinedIndex, OS);
883     OS.close();
884 
885     cleanup_hook();
886     exit(0);
887   }
888 
889   LLVMContext Context;
890   Context.setDiagnosticHandler(diagnosticHandlerForContext, nullptr, true);
891 
892   std::unique_ptr<Module> Combined(new Module("ld-temp.o", Context));
893   IRMover L(*Combined);
894 
895   std::string DefaultTriple = sys::getDefaultTargetTriple();
896 
897   StringSet<> Internalize;
898   StringSet<> Maybe;
899   for (claimed_file &F : Modules) {
900     PluginInputFile InputFile(F.handle);
901     std::vector<GlobalValue *> Keep;
902     std::unique_ptr<Module> M = getModuleForFile(
903         Context, F, InputFile.file(), ApiFile, Internalize, Maybe, Keep);
904     if (!options::triple.empty())
905       M->setTargetTriple(options::triple.c_str());
906     else if (M->getTargetTriple().empty())
907       M->setTargetTriple(DefaultTriple);
908 
909     if (L.move(std::move(M), Keep, [](GlobalValue &, IRMover::ValueAdder) {}))
910       message(LDPL_FATAL, "Failed to link module");
911   }
912 
913   for (const auto &Name : Internalize) {
914     GlobalValue *GV = Combined->getNamedValue(Name.first());
915     if (GV)
916       internalize(*GV);
917   }
918 
919   for (const auto &Name : Maybe) {
920     GlobalValue *GV = Combined->getNamedValue(Name.first());
921     if (!GV)
922       continue;
923     GV->setLinkage(GlobalValue::LinkOnceODRLinkage);
924     if (canBeOmittedFromSymbolTable(GV))
925       internalize(*GV);
926   }
927 
928   if (options::TheOutputType == options::OT_DISABLE)
929     return LDPS_OK;
930 
931   if (options::TheOutputType != options::OT_NORMAL) {
932     std::string path;
933     if (options::TheOutputType == options::OT_BC_ONLY)
934       path = output_name;
935     else
936       path = output_name + ".bc";
937     saveBCFile(path, *Combined);
938     if (options::TheOutputType == options::OT_BC_ONLY)
939       return LDPS_OK;
940   }
941 
942   codegen(std::move(Combined));
943 
944   if (!options::extra_library_path.empty() &&
945       set_extra_library_path(options::extra_library_path.c_str()) != LDPS_OK)
946     message(LDPL_FATAL, "Unable to set the extra library path.");
947 
948   return LDPS_OK;
949 }
950 
951 static ld_plugin_status all_symbols_read_hook(void) {
952   ld_plugin_status Ret;
953   if (!options::generate_api_file) {
954     Ret = allSymbolsReadHook(nullptr);
955   } else {
956     std::error_code EC;
957     raw_fd_ostream ApiFile("apifile.txt", EC, sys::fs::F_None);
958     if (EC)
959       message(LDPL_FATAL, "Unable to open apifile.txt for writing: %s",
960               EC.message().c_str());
961     Ret = allSymbolsReadHook(&ApiFile);
962   }
963 
964   llvm_shutdown();
965 
966   if (options::TheOutputType == options::OT_BC_ONLY ||
967       options::TheOutputType == options::OT_DISABLE) {
968     if (options::TheOutputType == options::OT_DISABLE)
969       // Remove the output file here since ld.bfd creates the output file
970       // early.
971       sys::fs::remove(output_name);
972     exit(0);
973   }
974 
975   return Ret;
976 }
977 
978 static ld_plugin_status cleanup_hook(void) {
979   for (std::string &Name : Cleanup) {
980     std::error_code EC = sys::fs::remove(Name);
981     if (EC)
982       message(LDPL_ERROR, "Failed to delete '%s': %s", Name.c_str(),
983               EC.message().c_str());
984   }
985 
986   return LDPS_OK;
987 }
988