summaryrefslogtreecommitdiffstats
path: root/lld/ELF/LTO.cpp
blob: 7b1c31ac693b9314827bae8abe7a3f873c99fdb7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
//===- LTO.cpp ------------------------------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "LTO.h"
#include "Config.h"
#include "Error.h"
#include "InputFiles.h"
#include "Symbols.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Linker/IRMover.h"
#include "llvm/Support/StringSaver.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"

using namespace llvm;
using namespace llvm::object;
using namespace llvm::ELF;

using namespace lld;
using namespace lld::elf;

// This is for use when debugging LTO.
static void saveLtoObjectFile(StringRef Buffer) {
  std::error_code EC;
  raw_fd_ostream OS(Config->OutputFile.str() + ".lto.o", EC,
                    sys::fs::OpenFlags::F_None);
  check(EC);
  OS << Buffer;
}

// This is for use when debugging LTO.
static void saveBCFile(Module &M, StringRef Suffix) {
  std::error_code EC;
  raw_fd_ostream OS(Config->OutputFile.str() + Suffix.str(), EC,
                    sys::fs::OpenFlags::F_None);
  check(EC);
  WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ true);
}

// Run LTO passes.
// FIXME: Reduce code duplication by sharing this code with the gold plugin.
static void runLTOPasses(Module &M, TargetMachine &TM) {
  legacy::PassManager LtoPasses;
  LtoPasses.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
  PassManagerBuilder PMB;
  PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
  PMB.Inliner = createFunctionInliningPass();
  PMB.VerifyInput = true;
  PMB.VerifyOutput = true;
  PMB.LoopVectorize = true;
  PMB.SLPVectorize = true;
  PMB.OptLevel = 2; // FIXME: This should be an option.
  PMB.populateLTOPassManager(LtoPasses);
  LtoPasses.run(M);

  if (Config->SaveTemps)
    saveBCFile(M, ".lto.opt.bc");
}

void BitcodeCompiler::add(BitcodeFile &F) {
  std::unique_ptr<IRObjectFile> Obj =
      check(IRObjectFile::create(F.MB, Context));
  std::vector<GlobalValue *> Keep;
  unsigned BodyIndex = 0;
  ArrayRef<SymbolBody *> Bodies = F.getSymbols();

  for (const BasicSymbolRef &Sym : Obj->symbols()) {
    GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
    assert(GV);
    if (GV->hasAppendingLinkage()) {
      Keep.push_back(GV);
      continue;
    }
    if (!BitcodeFile::shouldSkip(Sym)) {
      if (SymbolBody *B = Bodies[BodyIndex++])
        if (&B->repl() == B && isa<DefinedBitcode>(B)) {
          switch (GV->getLinkage()) {
          default:
            break;
          case llvm::GlobalValue::LinkOnceAnyLinkage:
            GV->setLinkage(GlobalValue::WeakAnyLinkage);
            break;
          case llvm::GlobalValue::LinkOnceODRLinkage:
            GV->setLinkage(GlobalValue::WeakODRLinkage);
            break;
          }
          Keep.push_back(GV);
        }
    }
  }

  Mover.move(Obj->takeModule(), Keep,
             [](GlobalValue &, IRMover::ValueAdder) {});
}

// Merge all the bitcode files we have seen, codegen the result
// and return the resulting ObjectFile.
template <class ELFT>
std::unique_ptr<elf::ObjectFile<ELFT>> BitcodeCompiler::compile() {
  if (Config->SaveTemps)
    saveBCFile(Combined, ".lto.bc");

  std::unique_ptr<TargetMachine> TM(getTargetMachine());
  runLTOPasses(Combined, *TM);

  raw_svector_ostream OS(OwningData);
  legacy::PassManager CodeGenPasses;
  if (TM->addPassesToEmitFile(CodeGenPasses, OS,
                              TargetMachine::CGFT_ObjectFile))
    fatal("failed to setup codegen");
  CodeGenPasses.run(Combined);
  MB = MemoryBuffer::getMemBuffer(OwningData,
                                  "LLD-INTERNAL-combined-lto-object", false);
  if (Config->SaveTemps)
    saveLtoObjectFile(MB->getBuffer());

  std::unique_ptr<InputFile> IF = createObjectFile(*MB);
  auto *OF = cast<ObjectFile<ELFT>>(IF.release());
  return std::unique_ptr<ObjectFile<ELFT>>(OF);
}

TargetMachine *BitcodeCompiler::getTargetMachine() {
  StringRef TripleStr = Combined.getTargetTriple();
  std::string Msg;
  const Target *T = TargetRegistry::lookupTarget(TripleStr, Msg);
  if (!T)
    fatal("target not found: " + Msg);
  TargetOptions Options;
  Reloc::Model R = Config->Pic ? Reloc::PIC_ : Reloc::Static;
  return T->createTargetMachine(TripleStr, "", "", Options, R);
}

template std::unique_ptr<elf::ObjectFile<ELF32LE>> BitcodeCompiler::compile();
template std::unique_ptr<elf::ObjectFile<ELF32BE>> BitcodeCompiler::compile();
template std::unique_ptr<elf::ObjectFile<ELF64LE>> BitcodeCompiler::compile();
template std::unique_ptr<elf::ObjectFile<ELF64BE>> BitcodeCompiler::compile();
OpenPOWER on IntegriCloud