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