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