Coverage Report

Created: 2018-08-19 14:04

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