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