File: linker.cpp

package info (click to toggle)
ldc 1%3A1.30.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 59,248 kB
  • sloc: cpp: 61,598; ansic: 14,545; sh: 1,014; makefile: 972; asm: 510; objc: 135; exp: 48; python: 12
file content (337 lines) | stat: -rw-r--r-- 10,880 bytes parent folder | download
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
//===-- linker.cpp --------------------------------------------------------===//
//
//                         LDC – the LLVM D compiler
//
// This file is distributed under the BSD-style LDC license. See the LICENSE
// file for details.
//
//===----------------------------------------------------------------------===//

#include "driver/linker.h"

#include "dmd/errors.h"
#include "dmd/target.h"
#include "driver/cl_options.h"
#include "driver/timetrace.h"
#include "driver/tool.h"
#include "gen/llvm.h"
#include "gen/logger.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Linker/Linker.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/SourceMgr.h"
#include <sstream>

namespace cl = llvm::cl;

//////////////////////////////////////////////////////////////////////////////

#if LDC_WITH_LLD
static cl::opt<bool> linkInternally("link-internally", cl::ZeroOrMore,
                                    cl::desc("Use internal LLD for linking"),
                                    cl::cat(opts::linkingCategory));
#else
constexpr bool linkInternally = false;
#endif

static cl::opt<std::string> platformLib(
    "platformlib", cl::ZeroOrMore, cl::value_desc("lib1,lib2,..."),
    cl::desc("Platform libraries to link with (overrides previous)"),
    cl::cat(opts::linkingCategory));

static cl::opt<bool> noDefaultLib(
    "nodefaultlib", cl::ZeroOrMore, cl::Hidden,
    cl::desc("Don't add a default library for linking implicitly"));

static cl::opt<std::string>
    defaultLib("defaultlib", cl::ZeroOrMore, cl::value_desc("lib1,lib2,..."),
               cl::desc("Default libraries to link with (overrides previous)"),
               cl::cat(opts::linkingCategory));

static cl::opt<std::string> debugLib(
    "debuglib", cl::ZeroOrMore, cl::Hidden, cl::value_desc("lib1,lib2,..."),
    cl::desc("Debug versions of default libraries (overrides previous). If the "
             "option is omitted, LDC will append -debug to the -defaultlib "
             "names when linking with -link-defaultlib-debug"),
    cl::cat(opts::linkingCategory));

static cl::opt<bool> linkDefaultLibDebug(
    "link-defaultlib-debug", cl::ZeroOrMore,
    cl::desc("Link with debug versions of default libraries"),
    cl::cat(opts::linkingCategory));
static cl::alias _linkDebugLib("link-debuglib", cl::Hidden,
                               cl::aliasopt(linkDefaultLibDebug),
                               cl::desc("Alias for -link-defaultlib-debug"),
                               cl::cat(opts::linkingCategory));

static cl::opt<cl::boolOrDefault> linkDefaultLibShared(
    "link-defaultlib-shared", cl::ZeroOrMore,
    cl::desc("Link with shared versions of default libraries. Defaults to true "
             "when generating a shared library (-shared)."),
    cl::cat(opts::linkingCategory));

static cl::opt<cl::boolOrDefault>
    staticFlag("static", cl::ZeroOrMore,
               cl::desc("Create a statically linked binary, including "
                        "all system dependencies"),
               cl::cat(opts::linkingCategory));

static llvm::cl::opt<std::string>
    mscrtlib("mscrtlib", llvm::cl::ZeroOrMore,
             llvm::cl::desc("MS C runtime library to link with"),
             llvm::cl::value_desc("libcmt[d]|msvcrt[d]"),
             llvm::cl::cat(opts::linkingCategory));

//////////////////////////////////////////////////////////////////////////////

// linker-gcc.cpp
int linkObjToBinaryGcc(llvm::StringRef outputPath,
                       const std::vector<std::string> &defaultLibNames);

// linker-msvc.cpp
int linkObjToBinaryMSVC(llvm::StringRef outputPath,
                        const std::vector<std::string> &defaultLibNames);

//////////////////////////////////////////////////////////////////////////////

static std::string getOutputPath() {
  const auto &triple = *global.params.targetTriple;
  const bool sharedLib = global.params.dll;

  const char *extension = nullptr;
  if (sharedLib) {
    extension = target.dll_ext.ptr;
  } else if (triple.isOSWindows()) {
    extension = "exe";
  } else if (triple.getArch() == llvm::Triple::wasm32 ||
             triple.getArch() == llvm::Triple::wasm64) {
    extension = "wasm";
  }

  if (global.params.exefile.length) {
    // DMD adds the default extension if there is none
    return opts::invokedByLDMD && extension
               ? FileName::defaultExt(global.params.exefile.ptr, extension)
               : global.params.exefile.ptr;
  }

  // Infer output name from first object file.
  std::string result =
      global.params.objfiles.length
          ? FileName::removeExt(FileName::name(global.params.objfiles[0]))
          : "a.out";

  if (sharedLib && !triple.isWindowsMSVCEnvironment())
    result = "lib" + result;

  if (global.params.run) {
    // If `-run` is passed, the executable is temporary and is removed
    // after execution. Make sure the name does not collide with other files
    // from other processes by creating a unique filename.
    llvm::SmallString<128> tempFilename;
    auto EC = llvm::sys::fs::createTemporaryFile(
        result, extension ? extension : "", tempFilename);
    if (!EC)
      result = {tempFilename.data(), tempFilename.size()};
  } else if (extension) {
    result += '.';
    result += extension;
  }

  return result;
}

//////////////////////////////////////////////////////////////////////////////

static std::vector<std::string>
parseLibNames(llvm::StringRef commaSeparatedList, llvm::StringRef suffix = {}) {
  std::vector<std::string> result;

  std::stringstream list(commaSeparatedList.str());
  while (list.good()) {
    std::string lib;
    std::getline(list, lib, ',');
    if (lib.empty()) {
      continue;
    }

    result.push_back(suffix.empty() ? std::move(lib) : (lib + suffix).str());
  }

  return result;
}

//////////////////////////////////////////////////////////////////////////////

static std::vector<std::string> getDefaultLibNames() {
  std::vector<std::string> result;

  if (noDefaultLib) {
    deprecation(Loc(), "-nodefaultlib is deprecated, as -defaultlib now "
                       "overrides the existing list instead of appending to "
                       "it. Please use the latter instead.");
  } else if (!global.params.betterC) {
    llvm::StringRef list = defaultLib;
    std::string suffix;

    if (linkDefaultLibDebug) {
      if (debugLib.getNumOccurrences() == 0)
        suffix = "-debug";
      else
        list = debugLib;
    }
    if (linkAgainstSharedDefaultLibs()) {
      suffix += "-shared";
    }

    result = parseLibNames(list, suffix);
  }

  return result;
}

//////////////////////////////////////////////////////////////////////////////

llvm::Optional<std::vector<std::string>> getExplicitPlatformLibs() {
  if (platformLib.getNumOccurrences() > 0)
    return parseLibNames(platformLib);
  return llvm::None;
}

//////////////////////////////////////////////////////////////////////////////

bool useInternalLLDForLinking() {
  return linkInternally
#if LDC_WITH_LLD
         ||
         // MSVC: DWARF debuginfos and LTO require LLD
         (linkInternally.getNumOccurrences() == 0 && // not explicitly disabled
          opts::linker.empty() && // no explicitly selected linker
          global.params.targetTriple->isWindowsMSVCEnvironment() &&
          (opts::emitDwarfDebugInfo || opts::isUsingLTO()))
#endif
      ;
}

cl::boolOrDefault linkFullyStatic() { return staticFlag; }

bool linkAgainstSharedDefaultLibs() {
  // -static enforces static default libs.
  // Default to shared default libs for DLLs.
  return staticFlag != cl::BOU_TRUE &&
         (linkDefaultLibShared == cl::BOU_TRUE ||
          (linkDefaultLibShared == cl::BOU_UNSET && global.params.dll));
}

//////////////////////////////////////////////////////////////////////////////

llvm::StringRef getExplicitMscrtLibName() { return mscrtlib; }

llvm::StringRef getMscrtLibName(const bool *useInternalToolchain) {
  llvm::StringRef name = getExplicitMscrtLibName();
  if (!name.empty())
    return name;

  bool useInternal = false;
  if (useInternalToolchain) {
    useInternal = *useInternalToolchain;
  } else {
#ifdef _WIN32
    static bool haveMSVC = windows::isMsvcAvailable();
    useInternal = !haveMSVC;
#else
    useInternal = true;
#endif
  }

  if (useInternal) {
    return "vcruntime140";
  } else {
    return linkAgainstSharedDefaultLibs() ? "msvcrt" : "libcmt";
  }
}

//////////////////////////////////////////////////////////////////////////////

/// Insert an LLVM bitcode file into the module
static void insertBitcodeIntoModule(const char *bcFile, llvm::Module &M,
                                    llvm::LLVMContext &Context) {
  Logger::println("*** Linking-in bitcode file %s ***", bcFile);

  llvm::SMDiagnostic Err;
  std::unique_ptr<llvm::Module> loadedModule(
      getLazyIRFileModule(bcFile, Err, Context));
  if (!loadedModule) {
    error(Loc(), "Error when loading LLVM bitcode file: %s", bcFile);
    fatal();
  }
  llvm::Linker(M).linkInModule(std::move(loadedModule));
}

/// Insert LLVM bitcode files into the module
void insertBitcodeFiles(llvm::Module &M, llvm::LLVMContext &Ctx,
                        Array<const char *> &bitcodeFiles) {
  for (const char *fname : bitcodeFiles) {
    insertBitcodeIntoModule(fname, M, Ctx);
  }
}

//////////////////////////////////////////////////////////////////////////////

// path to the produced executable/shared library
static std::string gExePath;

//////////////////////////////////////////////////////////////////////////////

int linkObjToBinary() {
  Logger::println("*** Linking executable ***");
  TimeTraceScope timeScope("Linking executable");

  // remember output path for later
  gExePath = getOutputPath();

  createDirectoryForFileOrFail(gExePath);

  const auto defaultLibNames = getDefaultLibNames();

  if (global.params.targetTriple->isWindowsMSVCEnvironment()) {
    return linkObjToBinaryMSVC(gExePath, defaultLibNames);
  }

  return linkObjToBinaryGcc(gExePath, defaultLibNames);
}

const char *getPathToProducedBinary() {
  assert(!gExePath.empty());
  return gExePath.c_str();
}

//////////////////////////////////////////////////////////////////////////////

void deleteExeFile() {
  if (!gExePath.empty() && !llvm::sys::fs::is_directory(gExePath)) {
    llvm::sys::fs::remove(gExePath);
  }
}

//////////////////////////////////////////////////////////////////////////////

int runProgram() {
  TimeTraceScope timeScope("Run user program");

  assert(!gExePath.empty());

  // Run executable
  int status =
      executeToolAndWait(gExePath, opts::runargs, global.params.verbose);
  if (status < 0) {
#if defined(_MSC_VER) || defined(__MINGW32__)
    error(Loc(), "program received signal %d", -status);
#else
    error(Loc(), "program received signal %d (%s)", -status,
          strsignal(-status));
#endif
    return -status;
  }
  return status;
}