Coverage Report

Created: 2018-10-23 15:26

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/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 "InputFiles.h"
13
#include "LinkerScript.h"
14
#include "SymbolTable.h"
15
#include "Symbols.h"
16
#include "lld/Common/ErrorHandler.h"
17
#include "lld/Common/TargetOptionsCommandFlags.h"
18
#include "llvm/ADT/STLExtras.h"
19
#include "llvm/ADT/SmallString.h"
20
#include "llvm/ADT/StringRef.h"
21
#include "llvm/ADT/Twine.h"
22
#include "llvm/BinaryFormat/ELF.h"
23
#include "llvm/Bitcode/BitcodeReader.h"
24
#include "llvm/Bitcode/BitcodeWriter.h"
25
#include "llvm/IR/DiagnosticPrinter.h"
26
#include "llvm/LTO/Caching.h"
27
#include "llvm/LTO/Config.h"
28
#include "llvm/LTO/LTO.h"
29
#include "llvm/Object/SymbolicFile.h"
30
#include "llvm/Support/CodeGen.h"
31
#include "llvm/Support/Error.h"
32
#include "llvm/Support/FileSystem.h"
33
#include "llvm/Support/MemoryBuffer.h"
34
#include <algorithm>
35
#include <cstddef>
36
#include <memory>
37
#include <string>
38
#include <system_error>
39
#include <vector>
40
41
using namespace llvm;
42
using namespace llvm::object;
43
using namespace llvm::ELF;
44
45
using namespace lld;
46
using namespace lld::elf;
47
48
// Creates an empty file to store a list of object files for final
49
// linking of distributed ThinLTO.
50
9
static std::unique_ptr<raw_fd_ostream> openFile(StringRef File) {
51
9
  std::error_code EC;
52
9
  auto Ret =
53
9
      llvm::make_unique<raw_fd_ostream>(File, EC, sys::fs::OpenFlags::F_None);
54
9
  if (EC) {
55
3
    error("cannot open " + File + ": " + EC.message());
56
3
    return nullptr;
57
3
  }
58
6
  return Ret;
59
6
}
60
61
6
static std::string getThinLTOOutputFile(StringRef ModulePath) {
62
6
  return lto::getThinLTOOutputFile(ModulePath,
63
6
                                   Config->ThinLTOPrefixReplace.first,
64
6
                                   Config->ThinLTOPrefixReplace.second);
65
6
}
66
67
167
static lto::Config createConfig() {
68
167
  lto::Config C;
69
167
70
167
  // LLD supports the new relocations and address-significance tables.
71
167
  C.Options = InitTargetOptionsFromCodeGenFlags();
72
167
  C.Options.RelaxELFRelocations = true;
73
167
  C.Options.EmitAddrsig = true;
74
167
75
167
  // Always emit a section per function/datum with LTO.
76
167
  C.Options.FunctionSections = true;
77
167
  C.Options.DataSections = true;
78
167
79
167
  if (Config->Relocatable)
80
3
    C.RelocModel = None;
81
164
  else if (Config->Pic)
82
100
    C.RelocModel = Reloc::PIC_;
83
64
  else
84
64
    C.RelocModel = Reloc::Static;
85
167
86
167
  C.CodeModel = GetCodeModelFromCMModel();
87
167
  C.DisableVerify = Config->DisableVerify;
88
167
  C.DiagHandler = diagnosticHandler;
89
167
  C.OptLevel = Config->LTOO;
90
167
  C.CPU = GetCPUStr();
91
167
92
167
  // Set up a custom pipeline if we've been asked to.
93
167
  C.OptPipeline = Config->LTONewPmPasses;
94
167
  C.AAPipeline = Config->LTOAAPipeline;
95
167
96
167
  // Set up optimization remarks if we've been asked to.
97
167
  C.RemarksFilename = Config->OptRemarksFilename;
98
167
  C.RemarksWithHotness = Config->OptRemarksWithHotness;
99
167
100
167
  C.SampleProfile = Config->LTOSampleProfile;
101
167
  C.UseNewPM = Config->LTONewPassManager;
102
167
  C.DebugPassManager = Config->LTODebugPassManager;
103
167
  C.DwoDir = Config->DwoDir;
104
167
105
167
  if (Config->SaveTemps)
106
51
    checkError(C.addSaveTemps(Config->OutputFile.str() + ".",
107
51
                              /*UseInputModulePath*/ true));
108
167
  return C;
109
167
}
110
111
167
BitcodeCompiler::BitcodeCompiler() {
112
167
  // Initialize IndexFile.
113
167
  if (!Config->ThinLTOIndexOnlyArg.empty())
114
1
    IndexFile = openFile(Config->ThinLTOIndexOnlyArg);
115
167
116
167
  // Initialize LTOObj.
117
167
  lto::ThinBackend Backend;
118
167
  if (Config->ThinLTOIndexOnly) {
119
22
    auto OnIndexWrite = [&](StringRef S) { ThinIndices.erase(S); };
120
14
    Backend = lto::createWriteIndexesThinBackend(
121
14
        Config->ThinLTOPrefixReplace.first, Config->ThinLTOPrefixReplace.second,
122
14
        Config->ThinLTOEmitImportsFiles, IndexFile.get(), OnIndexWrite);
123
153
  } else if (Config->ThinLTOJobs != -1U) {
124
2
    Backend = lto::createInProcessThinBackend(Config->ThinLTOJobs);
125
2
  }
126
167
127
167
  LTOObj = llvm::make_unique<lto::LTO>(createConfig(), Backend,
128
167
                                       Config->LTOPartitions);
129
167
130
167
  // Initialize UsedStartStop.
131
343
  for (Symbol *Sym : Symtab->getSymbols()) {
132
343
    StringRef S = Sym->getName();
133
343
    for (StringRef Prefix : {"__start_", "__stop_"})
134
686
      if (S.startswith(Prefix))
135
4
        UsedStartStop.insert(S.substr(Prefix.size()));
136
343
  }
137
167
}
138
139
167
BitcodeCompiler::~BitcodeCompiler() = default;
140
141
265
static void undefine(Symbol *S) {
142
265
  replaceSymbol<Undefined>(S, nullptr, S->getName(), STB_GLOBAL, STV_DEFAULT,
143
265
                           S->Type);
144
265
}
145
146
240
void BitcodeCompiler::add(BitcodeFile &F) {
147
240
  lto::InputFile &Obj = *F.Obj;
148
240
  bool IsExec = !Config->Shared && 
!Config->Relocatable99
;
149
240
150
240
  if (Config->ThinLTOIndexOnly)
151
26
    ThinIndices.insert(Obj.getName());
152
240
153
240
  ArrayRef<Symbol *> Syms = F.getSymbols();
154
240
  ArrayRef<lto::InputFile::Symbol> ObjSyms = Obj.symbols();
155
240
  std::vector<lto::SymbolResolution> Resols(Syms.size());
156
240
157
240
  // Provide a resolution to the LTO API for each symbol.
158
619
  for (size_t I = 0, E = Syms.size(); I != E; 
++I379
) {
159
379
    Symbol *Sym = Syms[I];
160
379
    const lto::InputFile::Symbol &ObjSym = ObjSyms[I];
161
379
    lto::SymbolResolution &R = Resols[I];
162
379
163
379
    // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
164
379
    // reports two symbols for module ASM defined. Without this check, lld
165
379
    // flags an undefined in IR with a definition in ASM as prevailing.
166
379
    // Once IRObjectFile is fixed to report only one symbol this hack can
167
379
    // be removed.
168
379
    R.Prevailing = !ObjSym.isUndefined() && 
Sym->File == &F284
;
169
379
170
379
    // We ask LTO to preserve following global symbols:
171
379
    // 1) All symbols when doing relocatable link, so that them can be used
172
379
    //    for doing final link.
173
379
    // 2) Symbols that are used in regular objects.
174
379
    // 3) C named sections if we have corresponding __start_/__stop_ symbol.
175
379
    // 4) Symbols that are defined in bitcode files and used for dynamic linking.
176
379
    R.VisibleToRegularObj = Config->Relocatable || 
Sym->IsUsedInRegularObj374
||
177
379
                            
(258
R.Prevailing258
&&
Sym->includeInDynsym()173
) ||
178
379
                            
UsedStartStop.count(ObjSym.getSectionName())144
;
179
379
    const auto *DR = dyn_cast<Defined>(Sym);
180
379
    R.FinalDefinitionInLinkageUnit =
181
379
        (IsExec || 
Sym->Visibility != STV_DEFAULT223
) &&
DR200
&&
182
379
        // Skip absolute symbols from ELF objects, otherwise PC-rel relocations
183
379
        // will be generated by for them, triggering linker errors.
184
379
        // Symbol section is always null for bitcode symbols, hence the check
185
379
        // for isElf(). Skip linker script defined symbols as well: they have
186
379
        // no File defined.
187
379
        
!(183
DR->Section == nullptr183
&&
(177
!Sym->File177
||
Sym->File->isElf()169
));
188
379
189
379
    if (R.Prevailing)
190
265
      undefine(Sym);
191
379
192
379
    // We tell LTO to not apply interprocedural optimization for wrapped
193
379
    // (with --wrap) symbols because otherwise LTO would inline them while
194
379
    // their values are still not final.
195
379
    R.LinkerRedefined = !Sym->CanInline;
196
379
  }
197
240
  checkError(LTOObj->add(std::move(F.Obj), Resols));
198
240
}
199
200
2
static void createEmptyIndex(StringRef ModulePath) {
201
2
  std::string Path = replaceThinLTOSuffix(getThinLTOOutputFile(ModulePath));
202
2
  std::unique_ptr<raw_fd_ostream> OS = openFile(Path + ".thinlto.bc");
203
2
  if (!OS)
204
1
    return;
205
1
206
1
  ModuleSummaryIndex M(/*HaveGVs*/ false);
207
1
  M.setSkipModuleByDistributedBackend();
208
1
  WriteIndexToFile(M, *OS);
209
1
210
1
  if (Config->ThinLTOEmitImportsFiles)
211
1
    openFile(Path + ".imports");
212
1
}
213
214
// Merge all the bitcode files we have seen, codegen the result
215
// and return the resulting ObjectFile(s).
216
167
std::vector<InputFile *> BitcodeCompiler::compile() {
217
167
  unsigned MaxTasks = LTOObj->getMaxTasks();
218
167
  Buf.resize(MaxTasks);
219
167
  Files.resize(MaxTasks);
220
167
221
167
  // The --thinlto-cache-dir option specifies the path to a directory in which
222
167
  // to cache native object files for ThinLTO incremental builds. If a path was
223
167
  // specified, configure LTO to use it as the cache directory.
224
167
  lto::NativeObjectCache Cache;
225
167
  if (!Config->ThinLTOCacheDir.empty())
226
6
    Cache = check(
227
6
        lto::localCache(Config->ThinLTOCacheDir,
228
12
                        [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
229
12
                          Files[Task] = std::move(MB);
230
12
                        }));
231
167
232
167
  checkError(LTOObj->run(
233
203
      [&](size_t Task) {
234
203
        return llvm::make_unique<lto::NativeObjectStream>(
235
203
            llvm::make_unique<raw_svector_ostream>(Buf[Task]));
236
203
      },
237
167
      Cache));
238
167
239
167
  // Emit empty index files for non-indexed files
240
167
  for (StringRef S : ThinIndices) {
241
4
    std::string Path = getThinLTOOutputFile(S);
242
4
    openFile(Path + ".thinlto.bc");
243
4
    if (Config->ThinLTOEmitImportsFiles)
244
1
      openFile(Path + ".imports");
245
4
  }
246
167
247
167
  // If LazyObjFile has not been added to link, emit empty index files.
248
167
  // This is needed because this is what GNU gold plugin does and we have a
249
167
  // distributed build system that depends on that behavior.
250
167
  if (Config->ThinLTOIndexOnly) {
251
14
    for (LazyObjFile *F : LazyObjFiles)
252
3
      if (!F->AddedToLink && 
isBitcode(F->MB)2
)
253
2
        createEmptyIndex(F->getName());
254
14
255
14
    if (!Config->LTOObjPath.empty())
256
1
      saveBuffer(Buf[0], Config->LTOObjPath);
257
14
258
14
    // ThinLTO with index only option is required to generate only the index
259
14
    // files. After that, we exit from linker and ThinLTO backend runs in a
260
14
    // distributed environment.
261
14
    if (IndexFile)
262
1
      IndexFile->close();
263
14
    return {};
264
14
  }
265
153
266
153
  if (!Config->ThinLTOCacheDir.empty())
267
6
    pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy);
268
153
269
153
  std::vector<InputFile *> Ret;
270
354
  for (unsigned I = 0; I != MaxTasks; 
++I201
) {
271
201
    if (Buf[I].empty())
272
12
      continue;
273
189
    if (Config->SaveTemps) {
274
60
      if (I == 0)
275
51
        saveBuffer(Buf[I], Config->OutputFile + ".lto.o");
276
9
      else
277
9
        saveBuffer(Buf[I], Config->OutputFile + Twine(I) + ".lto.o");
278
60
    }
279
189
    InputFile *Obj = createObjectFile(MemoryBufferRef(Buf[I], "lto.tmp"));
280
189
    Ret.push_back(Obj);
281
189
  }
282
153
283
153
  for (std::unique_ptr<MemoryBuffer> &File : Files)
284
201
    if (File)
285
12
      Ret.push_back(createObjectFile(*File));
286
153
  return Ret;
287
153
}