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