Coverage Report

Created: 2017-09-19 22:28

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/lld/ELF/LTO.cpp
Line
Count
Source
1
//===- LTO.cpp ------------------------------------------------------------===//
2
//
3
//                             The LLVM Linker
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
10
#include "LTO.h"
11
#include "Config.h"
12
#include "Error.h"
13
#include "InputFiles.h"
14
#include "SymbolTable.h"
15
#include "Symbols.h"
16
#include "lld/Core/TargetOptionsCommandFlags.h"
17
#include "llvm/ADT/STLExtras.h"
18
#include "llvm/ADT/SmallString.h"
19
#include "llvm/ADT/StringRef.h"
20
#include "llvm/ADT/Twine.h"
21
#include "llvm/BinaryFormat/ELF.h"
22
#include "llvm/IR/DiagnosticPrinter.h"
23
#include "llvm/LTO/Caching.h"
24
#include "llvm/LTO/Config.h"
25
#include "llvm/LTO/LTO.h"
26
#include "llvm/Object/SymbolicFile.h"
27
#include "llvm/Support/CodeGen.h"
28
#include "llvm/Support/Error.h"
29
#include "llvm/Support/FileSystem.h"
30
#include "llvm/Support/MemoryBuffer.h"
31
#include "llvm/Support/raw_ostream.h"
32
#include <algorithm>
33
#include <cstddef>
34
#include <memory>
35
#include <string>
36
#include <system_error>
37
#include <vector>
38
39
using namespace llvm;
40
using namespace llvm::object;
41
using namespace llvm::ELF;
42
43
using namespace lld;
44
using namespace lld::elf;
45
46
// This is for use when debugging LTO.
47
static void saveBuffer(StringRef Buffer, const Twine &Path) {
48
  std::error_code EC;
49
  raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None);
50
  if (EC)
51
    error("cannot create " + Path + ": " + EC.message());
52
  OS << Buffer;
53
}
54
55
static void diagnosticHandler(const DiagnosticInfo &DI) {
56
  SmallString<128> ErrStorage;
57
  raw_svector_ostream OS(ErrStorage);
58
  DiagnosticPrinterRawOStream DP(OS);
59
  DI.print(DP);
60
  warn(ErrStorage);
61
}
62
63
static void checkError(Error E) {
64
  handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) -> Error {
65
    error(EIB.message());
66
    return Error::success();
67
  });
68
}
69
70
static std::unique_ptr<lto::LTO> createLTO() {
71
  lto::Config Conf;
72
73
  // LLD supports the new relocations.
74
  Conf.Options = InitTargetOptionsFromCodeGenFlags();
75
  Conf.Options.RelaxELFRelocations = true;
76
77
  // Always emit a section per function/datum with LTO.
78
  Conf.Options.FunctionSections = true;
79
  Conf.Options.DataSections = true;
80
81
  if (Config->Relocatable)
82
    Conf.RelocModel = None;
83
  else if (Config->Pic)
84
    Conf.RelocModel = Reloc::PIC_;
85
  else
86
    Conf.RelocModel = Reloc::Static;
87
  Conf.CodeModel = GetCodeModelFromCMModel();
88
  Conf.DisableVerify = Config->DisableVerify;
89
  Conf.DiagHandler = diagnosticHandler;
90
  Conf.OptLevel = Config->LTOO;
91
92
  // Set up a custom pipeline if we've been asked to.
93
  Conf.OptPipeline = Config->LTONewPmPasses;
94
  Conf.AAPipeline = Config->LTOAAPipeline;
95
96
  // Set up optimization remarks if we've been asked to.
97
  Conf.RemarksFilename = Config->OptRemarksFilename;
98
  Conf.RemarksWithHotness = Config->OptRemarksWithHotness;
99
100
  if (Config->SaveTemps)
101
    checkError(Conf.addSaveTemps(std::string(Config->OutputFile) + ".",
102
                                 /*UseInputModulePath*/ true));
103
104
  lto::ThinBackend Backend;
105
  if (Config->ThinLTOJobs != -1u)
106
    Backend = lto::createInProcessThinBackend(Config->ThinLTOJobs);
107
  return llvm::make_unique<lto::LTO>(std::move(Conf), Backend,
108
                                     Config->LTOPartitions);
109
}
110
111
110
BitcodeCompiler::BitcodeCompiler() : LTOObj(createLTO()) {
112
236
  for (Symbol *Sym : Symtab->getSymbols()) {
113
236
    StringRef Name = Sym->body()->getName();
114
236
    for (StringRef Prefix : {"__start_", "__stop_"})
115
472
      
if (472
Name.startswith(Prefix)472
)
116
4
        UsedStartStop.insert(Name.substr(Prefix.size()));
117
236
  }
118
110
}
119
120
110
BitcodeCompiler::~BitcodeCompiler() = default;
121
122
190
static void undefine(Symbol *S) {
123
190
  replaceBody<Undefined>(S, nullptr, S->body()->getName(), /*IsLocal=*/false,
124
190
                         STV_DEFAULT, S->body()->Type);
125
190
}
126
127
153
void BitcodeCompiler::add(BitcodeFile &F) {
128
153
  lto::InputFile &Obj = *F.Obj;
129
153
  unsigned SymNum = 0;
130
153
  std::vector<SymbolBody *> Syms = F.getSymbols();
131
153
  std::vector<lto::SymbolResolution> Resols(Syms.size());
132
153
133
153
  // Provide a resolution to the LTO API for each symbol.
134
271
  for (const lto::InputFile::Symbol &ObjSym : Obj.symbols()) {
135
271
    SymbolBody *B = Syms[SymNum];
136
271
    Symbol *Sym = B->symbol();
137
271
    lto::SymbolResolution &R = Resols[SymNum];
138
271
    ++SymNum;
139
271
140
271
    // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
141
271
    // reports two symbols for module ASM defined. Without this check, lld
142
271
    // flags an undefined in IR with a definition in ASM as prevailing.
143
271
    // Once IRObjectFile is fixed to report only one symbol this hack can
144
271
    // be removed.
145
202
    R.Prevailing = !ObjSym.isUndefined() && B->getFile() == &F;
146
271
147
271
    // We ask LTO to preserve following global symbols:
148
271
    // 1) All symbols when doing relocatable link, so that them can be used
149
271
    //    for doing final link.
150
271
    // 2) Symbols that are used in regular objects.
151
271
    // 3) C named sections if we have corresponding __start_/__stop_ symbol.
152
271
    // 4) Symbols that are defined in bitcode files and used for dynamic linking.
153
266
    R.VisibleToRegularObj = Config->Relocatable || Sym->IsUsedInRegularObj ||
154
187
                            
(R.Prevailing && 187
Sym->includeInDynsym()124
) ||
155
105
                            UsedStartStop.count(ObjSym.getSectionName());
156
271
    if (R.Prevailing)
157
190
      undefine(Sym);
158
271
    R.LinkerRedefined = Config->RenamedSymbols.count(Sym);
159
271
  }
160
153
  checkError(LTOObj->add(std::move(F.Obj), Resols));
161
153
}
162
163
// Merge all the bitcode files we have seen, codegen the result
164
// and return the resulting ObjectFile(s).
165
110
std::vector<InputFile *> BitcodeCompiler::compile() {
166
110
  std::vector<InputFile *> Ret;
167
110
  unsigned MaxTasks = LTOObj->getMaxTasks();
168
110
  Buff.resize(MaxTasks);
169
110
  Files.resize(MaxTasks);
170
110
171
110
  // The --thinlto-cache-dir option specifies the path to a directory in which
172
110
  // to cache native object files for ThinLTO incremental builds. If a path was
173
110
  // specified, configure LTO to use it as the cache directory.
174
110
  lto::NativeObjectCache Cache;
175
110
  if (!Config->ThinLTOCacheDir.empty())
176
3
    Cache = check(
177
3
        lto::localCache(Config->ThinLTOCacheDir,
178
3
                        [&](size_t Task, std::unique_ptr<MemoryBuffer> MB,
179
6
                            StringRef Path) { Files[Task] = std::move(MB); }));
180
110
181
110
  checkError(LTOObj->run(
182
119
      [&](size_t Task) {
183
119
        return llvm::make_unique<lto::NativeObjectStream>(
184
119
            llvm::make_unique<raw_svector_ostream>(Buff[Task]));
185
119
      },
186
110
      Cache));
187
110
188
110
  if (!Config->ThinLTOCacheDir.empty())
189
3
    pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy);
190
110
191
248
  for (unsigned I = 0; 
I != MaxTasks248
;
++I138
) {
192
138
    if (Buff[I].empty())
193
19
      continue;
194
119
    
if (119
Config->SaveTemps119
) {
195
48
      if (I == 0)
196
44
        saveBuffer(Buff[I], Config->OutputFile + ".lto.o");
197
48
      else
198
4
        saveBuffer(Buff[I], Config->OutputFile + Twine(I) + ".lto.o");
199
48
    }
200
138
    InputFile *Obj = createObjectFile(MemoryBufferRef(Buff[I], "lto.tmp"));
201
138
    Ret.push_back(Obj);
202
138
  }
203
110
204
110
  for (std::unique_ptr<MemoryBuffer> &File : Files)
205
138
    
if (138
File138
)
206
6
      Ret.push_back(createObjectFile(*File));
207
110
208
110
  return Ret;
209
110
}