]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/lib/Driver/DarwinLdDriver.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / lib / Driver / DarwinLdDriver.cpp
1 //===- lib/Driver/DarwinLdDriver.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 /// \file
11 ///
12 /// Concrete instance of the Driver for darwin's ld.
13 ///
14 //===----------------------------------------------------------------------===//
15
16 #include "lld/Common/Args.h"
17 #include "lld/Common/ErrorHandler.h"
18 #include "lld/Common/LLVM.h"
19 #include "lld/Core/ArchiveLibraryFile.h"
20 #include "lld/Core/Error.h"
21 #include "lld/Core/File.h"
22 #include "lld/Core/Instrumentation.h"
23 #include "lld/Core/LinkingContext.h"
24 #include "lld/Core/Node.h"
25 #include "lld/Core/PassManager.h"
26 #include "lld/Core/Resolver.h"
27 #include "lld/Core/SharedLibraryFile.h"
28 #include "lld/Core/Simple.h"
29 #include "lld/ReaderWriter/MachOLinkingContext.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/Twine.h"
37 #include "llvm/BinaryFormat/MachO.h"
38 #include "llvm/Option/Arg.h"
39 #include "llvm/Option/ArgList.h"
40 #include "llvm/Option/OptTable.h"
41 #include "llvm/Option/Option.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Error.h"
45 #include "llvm/Support/ErrorOr.h"
46 #include "llvm/Support/Format.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/Path.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include <algorithm>
52 #include <cstdint>
53 #include <memory>
54 #include <string>
55 #include <system_error>
56 #include <utility>
57 #include <vector>
58
59 using namespace lld;
60
61 namespace {
62
63 // Create enum with OPT_xxx values for each option in DarwinLdOptions.td
64 enum {
65   OPT_INVALID = 0,
66 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
67                HELP, META, VALUES)                                             \
68   OPT_##ID,
69 #include "DarwinLdOptions.inc"
70 #undef OPTION
71 };
72
73 // Create prefix string literals used in DarwinLdOptions.td
74 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
75 #include "DarwinLdOptions.inc"
76 #undef PREFIX
77
78 // Create table mapping all options defined in DarwinLdOptions.td
79 static const llvm::opt::OptTable::Info InfoTable[] = {
80 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
81                HELPTEXT, METAVAR, VALUES)                                      \
82   {PREFIX,      NAME,      HELPTEXT,                                           \
83    METAVAR,     OPT_##ID,  llvm::opt::Option::KIND##Class,                     \
84    PARAM,       FLAGS,     OPT_##GROUP,                                        \
85    OPT_##ALIAS, ALIASARGS, VALUES},
86 #include "DarwinLdOptions.inc"
87 #undef OPTION
88 };
89
90 // Create OptTable class for parsing actual command line arguments
91 class DarwinLdOptTable : public llvm::opt::OptTable {
92 public:
93   DarwinLdOptTable() : OptTable(InfoTable) {}
94 };
95
96 static std::vector<std::unique_ptr<File>>
97 makeErrorFile(StringRef path, std::error_code ec) {
98   std::vector<std::unique_ptr<File>> result;
99   result.push_back(llvm::make_unique<ErrorFile>(path, ec));
100   return result;
101 }
102
103 static std::vector<std::unique_ptr<File>>
104 parseMemberFiles(std::unique_ptr<File> file) {
105   std::vector<std::unique_ptr<File>> members;
106   if (auto *archive = dyn_cast<ArchiveLibraryFile>(file.get())) {
107     if (std::error_code ec = archive->parseAllMembers(members))
108       return makeErrorFile(file->path(), ec);
109   } else {
110     members.push_back(std::move(file));
111   }
112   return members;
113 }
114
115 std::vector<std::unique_ptr<File>> loadFile(MachOLinkingContext &ctx,
116                                             StringRef path, bool wholeArchive,
117                                             bool upwardDylib) {
118   if (ctx.logInputFiles())
119     message(path);
120
121   ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = ctx.getMemoryBuffer(path);
122   if (std::error_code ec = mbOrErr.getError())
123     return makeErrorFile(path, ec);
124   ErrorOr<std::unique_ptr<File>> fileOrErr =
125       ctx.registry().loadFile(std::move(mbOrErr.get()));
126   if (std::error_code ec = fileOrErr.getError())
127     return makeErrorFile(path, ec);
128   std::unique_ptr<File> &file = fileOrErr.get();
129
130   // If file is a dylib, inform LinkingContext about it.
131   if (SharedLibraryFile *shl = dyn_cast<SharedLibraryFile>(file.get())) {
132     if (std::error_code ec = shl->parse())
133       return makeErrorFile(path, ec);
134     ctx.registerDylib(reinterpret_cast<mach_o::MachODylibFile *>(shl),
135                       upwardDylib);
136   }
137   if (wholeArchive)
138     return parseMemberFiles(std::move(file));
139   std::vector<std::unique_ptr<File>> files;
140   files.push_back(std::move(file));
141   return files;
142 }
143
144 } // end anonymous namespace
145
146 // Test may be running on Windows. Canonicalize the path
147 // separator to '/' to get consistent outputs for tests.
148 static std::string canonicalizePath(StringRef path) {
149   char sep = llvm::sys::path::get_separator().front();
150   if (sep != '/') {
151     std::string fixedPath = path;
152     std::replace(fixedPath.begin(), fixedPath.end(), sep, '/');
153     return fixedPath;
154   } else {
155     return path;
156   }
157 }
158
159 static void addFile(StringRef path, MachOLinkingContext &ctx,
160                     bool loadWholeArchive, bool upwardDylib) {
161   std::vector<std::unique_ptr<File>> files =
162       loadFile(ctx, path, loadWholeArchive, upwardDylib);
163   for (std::unique_ptr<File> &file : files)
164     ctx.getNodes().push_back(llvm::make_unique<FileNode>(std::move(file)));
165 }
166
167 // Export lists are one symbol per line.  Blank lines are ignored.
168 // Trailing comments start with #.
169 static std::error_code parseExportsList(StringRef exportFilePath,
170                                         MachOLinkingContext &ctx) {
171   // Map in export list file.
172   ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
173                                    MemoryBuffer::getFileOrSTDIN(exportFilePath);
174   if (std::error_code ec = mb.getError())
175     return ec;
176   ctx.addInputFileDependency(exportFilePath);
177   StringRef buffer = mb->get()->getBuffer();
178   while (!buffer.empty()) {
179     // Split off each line in the file.
180     std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
181     StringRef line = lineAndRest.first;
182     // Ignore trailing # comments.
183     std::pair<StringRef, StringRef> symAndComment = line.split('#');
184     StringRef sym = symAndComment.first.trim();
185     if (!sym.empty())
186       ctx.addExportSymbol(sym);
187     buffer = lineAndRest.second;
188   }
189   return std::error_code();
190 }
191
192 /// Order files are one symbol per line. Blank lines are ignored.
193 /// Trailing comments start with #. Symbol names can be prefixed with an
194 /// architecture name and/or .o leaf name.  Examples:
195 ///     _foo
196 ///     bar.o:_bar
197 ///     libfrob.a(bar.o):_bar
198 ///     x86_64:_foo64
199 static std::error_code parseOrderFile(StringRef orderFilePath,
200                                       MachOLinkingContext &ctx) {
201   // Map in order file.
202   ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
203                                    MemoryBuffer::getFileOrSTDIN(orderFilePath);
204   if (std::error_code ec = mb.getError())
205     return ec;
206   ctx.addInputFileDependency(orderFilePath);
207   StringRef buffer = mb->get()->getBuffer();
208   while (!buffer.empty()) {
209     // Split off each line in the file.
210     std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
211     StringRef line = lineAndRest.first;
212     buffer = lineAndRest.second;
213     // Ignore trailing # comments.
214     std::pair<StringRef, StringRef> symAndComment = line.split('#');
215     if (symAndComment.first.empty())
216       continue;
217     StringRef sym = symAndComment.first.trim();
218     if (sym.empty())
219       continue;
220     // Check for prefix.
221     StringRef prefix;
222     std::pair<StringRef, StringRef> prefixAndSym = sym.split(':');
223     if (!prefixAndSym.second.empty()) {
224       sym = prefixAndSym.second;
225       prefix = prefixAndSym.first;
226       if (!prefix.endswith(".o") && !prefix.endswith(".o)")) {
227         // If arch name prefix does not match arch being linked, ignore symbol.
228         if (!ctx.archName().equals(prefix))
229           continue;
230         prefix = "";
231       }
232     } else
233      sym = prefixAndSym.first;
234     if (!sym.empty()) {
235       ctx.appendOrderedSymbol(sym, prefix);
236       //llvm::errs() << sym << ", prefix=" << prefix << "\n";
237     }
238   }
239   return std::error_code();
240 }
241
242 //
243 // There are two variants of the  -filelist option:
244 //
245 //   -filelist <path>
246 // In this variant, the path is to a text file which contains one file path
247 // per line.  There are no comments or trimming of whitespace.
248 //
249 //   -fileList <path>,<dir>
250 // In this variant, the path is to a text file which contains a partial path
251 // per line. The <dir> prefix is prepended to each partial path.
252 //
253 static llvm::Error loadFileList(StringRef fileListPath,
254                                 MachOLinkingContext &ctx, bool forceLoad) {
255   // If there is a comma, split off <dir>.
256   std::pair<StringRef, StringRef> opt = fileListPath.split(',');
257   StringRef filePath = opt.first;
258   StringRef dirName = opt.second;
259   ctx.addInputFileDependency(filePath);
260   // Map in file list file.
261   ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
262                                         MemoryBuffer::getFileOrSTDIN(filePath);
263   if (std::error_code ec = mb.getError())
264     return llvm::errorCodeToError(ec);
265   StringRef buffer = mb->get()->getBuffer();
266   while (!buffer.empty()) {
267     // Split off each line in the file.
268     std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
269     StringRef line = lineAndRest.first;
270     StringRef path;
271     if (!dirName.empty()) {
272       // If there is a <dir> then prepend dir to each line.
273       SmallString<256> fullPath;
274       fullPath.assign(dirName);
275       llvm::sys::path::append(fullPath, Twine(line));
276       path = ctx.copy(fullPath.str());
277     } else {
278       // No <dir> use whole line as input file path.
279       path = ctx.copy(line);
280     }
281     if (!ctx.pathExists(path)) {
282       return llvm::make_error<GenericError>(Twine("File not found '")
283                                             + path
284                                             + "'");
285     }
286     if (ctx.testingFileUsage()) {
287       message("Found filelist entry " + canonicalizePath(path));
288     }
289     addFile(path, ctx, forceLoad, false);
290     buffer = lineAndRest.second;
291   }
292   return llvm::Error::success();
293 }
294
295 /// Parse number assuming it is base 16, but allow 0x prefix.
296 static bool parseNumberBase16(StringRef numStr, uint64_t &baseAddress) {
297   if (numStr.startswith_lower("0x"))
298     numStr = numStr.drop_front(2);
299   return numStr.getAsInteger(16, baseAddress);
300 }
301
302 static void parseLLVMOptions(const LinkingContext &ctx) {
303   // Honor -mllvm
304   if (!ctx.llvmOptions().empty()) {
305     unsigned numArgs = ctx.llvmOptions().size();
306     auto **args = new const char *[numArgs + 2];
307     args[0] = "lld (LLVM option parsing)";
308     for (unsigned i = 0; i != numArgs; ++i)
309       args[i + 1] = ctx.llvmOptions()[i];
310     args[numArgs + 1] = nullptr;
311     llvm::cl::ParseCommandLineOptions(numArgs + 1, args);
312   }
313 }
314
315 namespace lld {
316 namespace mach_o {
317
318 bool parse(llvm::ArrayRef<const char *> args, MachOLinkingContext &ctx) {
319   // Parse command line options using DarwinLdOptions.td
320   DarwinLdOptTable table;
321   unsigned missingIndex;
322   unsigned missingCount;
323   llvm::opt::InputArgList parsedArgs =
324       table.ParseArgs(args.slice(1), missingIndex, missingCount);
325   if (missingCount) {
326     error("missing arg value for '" +
327           Twine(parsedArgs.getArgString(missingIndex)) + "' expected " +
328           Twine(missingCount) + " argument(s).");
329     return false;
330   }
331
332   for (auto unknownArg : parsedArgs.filtered(OPT_UNKNOWN)) {
333     warn("ignoring unknown argument: " +
334          Twine(unknownArg->getAsString(parsedArgs)));
335   }
336
337   errorHandler().Verbose = parsedArgs.hasArg(OPT_v);
338   errorHandler().ErrorLimit = args::getInteger(parsedArgs, OPT_error_limit, 20);
339
340   // Figure out output kind ( -dylib, -r, -bundle, -preload, or -static )
341   llvm::MachO::HeaderFileType fileType = llvm::MachO::MH_EXECUTE;
342   bool isStaticExecutable = false;
343   if (llvm::opt::Arg *kind = parsedArgs.getLastArg(
344           OPT_dylib, OPT_relocatable, OPT_bundle, OPT_static, OPT_preload)) {
345     switch (kind->getOption().getID()) {
346     case OPT_dylib:
347       fileType = llvm::MachO::MH_DYLIB;
348       break;
349     case OPT_relocatable:
350       fileType = llvm::MachO::MH_OBJECT;
351       break;
352     case OPT_bundle:
353       fileType = llvm::MachO::MH_BUNDLE;
354       break;
355     case OPT_static:
356       fileType = llvm::MachO::MH_EXECUTE;
357       isStaticExecutable = true;
358       break;
359     case OPT_preload:
360       fileType = llvm::MachO::MH_PRELOAD;
361       break;
362     }
363   }
364
365   // Handle -arch xxx
366   MachOLinkingContext::Arch arch = MachOLinkingContext::arch_unknown;
367   if (llvm::opt::Arg *archStr = parsedArgs.getLastArg(OPT_arch)) {
368     arch = MachOLinkingContext::archFromName(archStr->getValue());
369     if (arch == MachOLinkingContext::arch_unknown) {
370       error("unknown arch named '" + Twine(archStr->getValue()) + "'");
371       return false;
372     }
373   }
374   // If no -arch specified, scan input files to find first non-fat .o file.
375   if (arch == MachOLinkingContext::arch_unknown) {
376     for (auto &inFile : parsedArgs.filtered(OPT_INPUT)) {
377       // This is expensive because it opens and maps the file.  But that is
378       // ok because no -arch is rare.
379       if (MachOLinkingContext::isThinObjectFile(inFile->getValue(), arch))
380         break;
381     }
382     if (arch == MachOLinkingContext::arch_unknown &&
383         !parsedArgs.getLastArg(OPT_test_file_usage)) {
384       // If no -arch and no options at all, print usage message.
385       if (parsedArgs.size() == 0) {
386         table.PrintHelp(llvm::outs(),
387                         (std::string(args[0]) + " [options] file...").c_str(),
388                         "LLVM Linker", false);
389       } else {
390         error("-arch not specified and could not be inferred");
391       }
392       return false;
393     }
394   }
395
396   // Handle -macosx_version_min or -ios_version_min
397   MachOLinkingContext::OS os = MachOLinkingContext::OS::unknown;
398   uint32_t minOSVersion = 0;
399   if (llvm::opt::Arg *minOS =
400           parsedArgs.getLastArg(OPT_macosx_version_min, OPT_ios_version_min,
401                                 OPT_ios_simulator_version_min)) {
402     switch (minOS->getOption().getID()) {
403     case OPT_macosx_version_min:
404       os = MachOLinkingContext::OS::macOSX;
405       if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
406                                                   minOSVersion)) {
407         error("malformed macosx_version_min value");
408         return false;
409       }
410       break;
411     case OPT_ios_version_min:
412       os = MachOLinkingContext::OS::iOS;
413       if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
414                                                   minOSVersion)) {
415         error("malformed ios_version_min value");
416         return false;
417       }
418       break;
419     case OPT_ios_simulator_version_min:
420       os = MachOLinkingContext::OS::iOS_simulator;
421       if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
422                                                   minOSVersion)) {
423         error("malformed ios_simulator_version_min value");
424         return false;
425       }
426       break;
427     }
428   } else {
429     // No min-os version on command line, check environment variables
430   }
431
432   // Handle export_dynamic
433   // FIXME: Should we warn when this applies to something other than a static
434   // executable or dylib?  Those are the only cases where this has an effect.
435   // Note, this has to come before ctx.configure() so that we get the correct
436   // value for _globalsAreDeadStripRoots.
437   bool exportDynamicSymbols = parsedArgs.hasArg(OPT_export_dynamic);
438
439   // Now that there's enough information parsed in, let the linking context
440   // set up default values.
441   ctx.configure(fileType, arch, os, minOSVersion, exportDynamicSymbols);
442
443   // Handle -e xxx
444   if (llvm::opt::Arg *entry = parsedArgs.getLastArg(OPT_entry))
445     ctx.setEntrySymbolName(entry->getValue());
446
447   // Handle -o xxx
448   if (llvm::opt::Arg *outpath = parsedArgs.getLastArg(OPT_output))
449     ctx.setOutputPath(outpath->getValue());
450   else
451     ctx.setOutputPath("a.out");
452
453   // Handle -image_base XXX and -seg1addr XXXX
454   if (llvm::opt::Arg *imageBase = parsedArgs.getLastArg(OPT_image_base)) {
455     uint64_t baseAddress;
456     if (parseNumberBase16(imageBase->getValue(), baseAddress)) {
457       error("image_base expects a hex number");
458       return false;
459     } else if (baseAddress < ctx.pageZeroSize()) {
460       error("image_base overlaps with __PAGEZERO");
461       return false;
462     } else if (baseAddress % ctx.pageSize()) {
463       error("image_base must be a multiple of page size (0x" +
464             llvm::utohexstr(ctx.pageSize()) + ")");
465       return false;
466     }
467
468     ctx.setBaseAddress(baseAddress);
469   }
470
471   // Handle -dead_strip
472   if (parsedArgs.getLastArg(OPT_dead_strip))
473     ctx.setDeadStripping(true);
474
475   bool globalWholeArchive = false;
476   // Handle -all_load
477   if (parsedArgs.getLastArg(OPT_all_load))
478     globalWholeArchive = true;
479
480   // Handle -install_name
481   if (llvm::opt::Arg *installName = parsedArgs.getLastArg(OPT_install_name))
482     ctx.setInstallName(installName->getValue());
483   else
484     ctx.setInstallName(ctx.outputPath());
485
486   // Handle -mark_dead_strippable_dylib
487   if (parsedArgs.getLastArg(OPT_mark_dead_strippable_dylib))
488     ctx.setDeadStrippableDylib(true);
489
490   // Handle -compatibility_version and -current_version
491   if (llvm::opt::Arg *vers = parsedArgs.getLastArg(OPT_compatibility_version)) {
492     if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) {
493       error("-compatibility_version can only be used with -dylib");
494       return false;
495     }
496     uint32_t parsedVers;
497     if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
498       error("-compatibility_version value is malformed");
499       return false;
500     }
501     ctx.setCompatibilityVersion(parsedVers);
502   }
503
504   if (llvm::opt::Arg *vers = parsedArgs.getLastArg(OPT_current_version)) {
505     if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) {
506       error("-current_version can only be used with -dylib");
507       return false;
508     }
509     uint32_t parsedVers;
510     if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
511       error("-current_version value is malformed");
512       return false;
513     }
514     ctx.setCurrentVersion(parsedVers);
515   }
516
517   // Handle -bundle_loader
518   if (llvm::opt::Arg *loader = parsedArgs.getLastArg(OPT_bundle_loader))
519     ctx.setBundleLoader(loader->getValue());
520
521   // Handle -sectalign segname sectname align
522   for (auto &alignArg : parsedArgs.filtered(OPT_sectalign)) {
523     const char* segName   = alignArg->getValue(0);
524     const char* sectName  = alignArg->getValue(1);
525     const char* alignStr  = alignArg->getValue(2);
526     if ((alignStr[0] == '0') && (alignStr[1] == 'x'))
527       alignStr += 2;
528     unsigned long long alignValue;
529     if (llvm::getAsUnsignedInteger(alignStr, 16, alignValue)) {
530       error("-sectalign alignment value '" + Twine(alignStr) +
531             "' not a valid number");
532       return false;
533     }
534     uint16_t align = 1 << llvm::countTrailingZeros(alignValue);
535     if (!llvm::isPowerOf2_64(alignValue)) {
536       std::string Msg;
537       llvm::raw_string_ostream OS(Msg);
538       OS << "alignment for '-sectalign " << segName << " " << sectName
539          << llvm::format(" 0x%llX", alignValue)
540          << "' is not a power of two, using " << llvm::format("0x%08X", align);
541       OS.flush();
542       warn(Msg);
543     }
544     ctx.addSectionAlignment(segName, sectName, align);
545   }
546
547   // Handle -mllvm
548   for (auto &llvmArg : parsedArgs.filtered(OPT_mllvm)) {
549     ctx.appendLLVMOption(llvmArg->getValue());
550   }
551
552   // Handle -print_atoms
553   if (parsedArgs.getLastArg(OPT_print_atoms))
554     ctx.setPrintAtoms();
555
556   // Handle -t (trace) option.
557   if (parsedArgs.getLastArg(OPT_t))
558     ctx.setLogInputFiles(true);
559
560   // Handle -demangle option.
561   if (parsedArgs.getLastArg(OPT_demangle))
562     ctx.setDemangleSymbols(true);
563
564   // Handle -keep_private_externs
565   if (parsedArgs.getLastArg(OPT_keep_private_externs)) {
566     ctx.setKeepPrivateExterns(true);
567     if (ctx.outputMachOType() != llvm::MachO::MH_OBJECT)
568       warn("-keep_private_externs only used in -r mode");
569   }
570
571   // Handle -dependency_info <path> used by Xcode.
572   if (llvm::opt::Arg *depInfo = parsedArgs.getLastArg(OPT_dependency_info))
573     if (std::error_code ec = ctx.createDependencyFile(depInfo->getValue()))
574       warn(ec.message() + ", processing '-dependency_info " +
575            depInfo->getValue());
576
577   // In -test_file_usage mode, we'll be given an explicit list of paths that
578   // exist. We'll also be expected to print out information about how we located
579   // libraries and so on that the user specified, but not to actually do any
580   // linking.
581   if (parsedArgs.getLastArg(OPT_test_file_usage)) {
582     ctx.setTestingFileUsage();
583
584     // With paths existing by fiat, linking is not going to end well.
585     ctx.setDoNothing(true);
586
587     // Only bother looking for an existence override if we're going to use it.
588     for (auto existingPath : parsedArgs.filtered(OPT_path_exists)) {
589       ctx.addExistingPathForDebug(existingPath->getValue());
590     }
591   }
592
593   // Register possible input file parsers.
594   if (!ctx.doNothing()) {
595     ctx.registry().addSupportMachOObjects(ctx);
596     ctx.registry().addSupportArchives(ctx.logInputFiles());
597     ctx.registry().addSupportYamlFiles();
598   }
599
600   // Now construct the set of library search directories, following ld64's
601   // baroque set of accumulated hacks. Mostly, the algorithm constructs
602   //     { syslibroots } x { libpaths }
603   //
604   // Unfortunately, there are numerous exceptions:
605   //   1. Only absolute paths get modified by syslibroot options.
606   //   2. If there is just 1 -syslibroot, system paths not found in it are
607   //      skipped.
608   //   3. If the last -syslibroot is "/", all of them are ignored entirely.
609   //   4. If { syslibroots } x path ==  {}, the original path is kept.
610   std::vector<StringRef> sysLibRoots;
611   for (auto syslibRoot : parsedArgs.filtered(OPT_syslibroot)) {
612     sysLibRoots.push_back(syslibRoot->getValue());
613   }
614   if (!sysLibRoots.empty()) {
615     // Ignore all if last -syslibroot is "/".
616     if (sysLibRoots.back() != "/")
617       ctx.setSysLibRoots(sysLibRoots);
618   }
619
620   // Paths specified with -L come first, and are not considered system paths for
621   // the case where there is precisely 1 -syslibroot.
622   for (auto libPath : parsedArgs.filtered(OPT_L)) {
623     ctx.addModifiedSearchDir(libPath->getValue());
624   }
625
626   // Process -F directories (where to look for frameworks).
627   for (auto fwPath : parsedArgs.filtered(OPT_F)) {
628     ctx.addFrameworkSearchDir(fwPath->getValue());
629   }
630
631   // -Z suppresses the standard search paths.
632   if (!parsedArgs.hasArg(OPT_Z)) {
633     ctx.addModifiedSearchDir("/usr/lib", true);
634     ctx.addModifiedSearchDir("/usr/local/lib", true);
635     ctx.addFrameworkSearchDir("/Library/Frameworks", true);
636     ctx.addFrameworkSearchDir("/System/Library/Frameworks", true);
637   }
638
639   // Now that we've constructed the final set of search paths, print out those
640   // search paths in verbose mode.
641   if (errorHandler().Verbose) {
642     message("Library search paths:");
643     for (auto path : ctx.searchDirs()) {
644       message("    " + path);
645     }
646     message("Framework search paths:");
647     for (auto path : ctx.frameworkDirs()) {
648       message("    " + path);
649     }
650   }
651
652   // Handle -exported_symbols_list <file>
653   for (auto expFile : parsedArgs.filtered(OPT_exported_symbols_list)) {
654     if (ctx.exportMode() == MachOLinkingContext::ExportMode::blackList) {
655       error("-exported_symbols_list cannot be combined with "
656             "-unexported_symbol[s_list]");
657       return false;
658     }
659     ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList);
660     if (std::error_code ec = parseExportsList(expFile->getValue(), ctx)) {
661       error(ec.message() + ", processing '-exported_symbols_list " +
662             expFile->getValue());
663       return false;
664     }
665   }
666
667   // Handle -exported_symbol <symbol>
668   for (auto symbol : parsedArgs.filtered(OPT_exported_symbol)) {
669     if (ctx.exportMode() == MachOLinkingContext::ExportMode::blackList) {
670       error("-exported_symbol cannot be combined with "
671             "-unexported_symbol[s_list]");
672       return false;
673     }
674     ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList);
675     ctx.addExportSymbol(symbol->getValue());
676   }
677
678   // Handle -unexported_symbols_list <file>
679   for (auto expFile : parsedArgs.filtered(OPT_unexported_symbols_list)) {
680     if (ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList) {
681       error("-unexported_symbols_list cannot be combined with "
682             "-exported_symbol[s_list]");
683       return false;
684     }
685     ctx.setExportMode(MachOLinkingContext::ExportMode::blackList);
686     if (std::error_code ec = parseExportsList(expFile->getValue(), ctx)) {
687       error(ec.message() + ", processing '-unexported_symbols_list " +
688             expFile->getValue());
689       return false;
690     }
691   }
692
693   // Handle -unexported_symbol <symbol>
694   for (auto symbol : parsedArgs.filtered(OPT_unexported_symbol)) {
695     if (ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList) {
696       error("-unexported_symbol cannot be combined with "
697             "-exported_symbol[s_list]");
698       return false;
699     }
700     ctx.setExportMode(MachOLinkingContext::ExportMode::blackList);
701     ctx.addExportSymbol(symbol->getValue());
702   }
703
704   // Handle obosolete -multi_module and -single_module
705   if (llvm::opt::Arg *mod =
706           parsedArgs.getLastArg(OPT_multi_module, OPT_single_module)) {
707     if (mod->getOption().getID() == OPT_multi_module)
708       warn("-multi_module is obsolete and being ignored");
709     else if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB)
710       warn("-single_module being ignored. It is only for use when producing a "
711            "dylib");
712   }
713
714   // Handle obsolete ObjC options: -objc_gc_compaction, -objc_gc, -objc_gc_only
715   if (parsedArgs.getLastArg(OPT_objc_gc_compaction)) {
716     error("-objc_gc_compaction is not supported");
717     return false;
718   }
719
720   if (parsedArgs.getLastArg(OPT_objc_gc)) {
721     error("-objc_gc is not supported");
722     return false;
723   }
724
725   if (parsedArgs.getLastArg(OPT_objc_gc_only)) {
726     error("-objc_gc_only is not supported");
727     return false;
728   }
729
730   // Handle -pie or -no_pie
731   if (llvm::opt::Arg *pie = parsedArgs.getLastArg(OPT_pie, OPT_no_pie)) {
732     switch (ctx.outputMachOType()) {
733     case llvm::MachO::MH_EXECUTE:
734       switch (ctx.os()) {
735       case MachOLinkingContext::OS::macOSX:
736         if ((minOSVersion < 0x000A0500) &&
737             (pie->getOption().getID() == OPT_pie)) {
738           error("-pie can only be used when targeting Mac OS X 10.5 or later");
739           return false;
740         }
741         break;
742       case MachOLinkingContext::OS::iOS:
743         if ((minOSVersion < 0x00040200) &&
744             (pie->getOption().getID() == OPT_pie)) {
745           error("-pie can only be used when targeting iOS 4.2 or later");
746           return false;
747         }
748         break;
749       case MachOLinkingContext::OS::iOS_simulator:
750         if (pie->getOption().getID() == OPT_no_pie) {
751           error("iOS simulator programs must be built PIE");
752           return false;
753         }
754         break;
755       case MachOLinkingContext::OS::unknown:
756         break;
757       }
758       ctx.setPIE(pie->getOption().getID() == OPT_pie);
759       break;
760     case llvm::MachO::MH_PRELOAD:
761       break;
762     case llvm::MachO::MH_DYLIB:
763     case llvm::MachO::MH_BUNDLE:
764       warn(pie->getSpelling() +
765            " being ignored. It is only used when linking main executables");
766       break;
767     default:
768       error(pie->getSpelling() +
769             " can only used when linking main executables");
770       return false;
771     }
772   }
773
774   // Handle -version_load_command or -no_version_load_command
775   {
776     bool flagOn = false;
777     bool flagOff = false;
778     if (auto *arg = parsedArgs.getLastArg(OPT_version_load_command,
779                                           OPT_no_version_load_command)) {
780       flagOn = arg->getOption().getID() == OPT_version_load_command;
781       flagOff = arg->getOption().getID() == OPT_no_version_load_command;
782     }
783
784     // default to adding version load command for dynamic code,
785     // static code must opt-in
786     switch (ctx.outputMachOType()) {
787       case llvm::MachO::MH_OBJECT:
788         ctx.setGenerateVersionLoadCommand(false);
789         break;
790       case llvm::MachO::MH_EXECUTE:
791         // dynamic executables default to generating a version load command,
792         // while static exectuables only generate it if required.
793         if (isStaticExecutable) {
794           if (flagOn)
795             ctx.setGenerateVersionLoadCommand(true);
796         } else {
797           if (!flagOff)
798             ctx.setGenerateVersionLoadCommand(true);
799         }
800         break;
801       case llvm::MachO::MH_PRELOAD:
802       case llvm::MachO::MH_KEXT_BUNDLE:
803         if (flagOn)
804           ctx.setGenerateVersionLoadCommand(true);
805         break;
806       case llvm::MachO::MH_DYLINKER:
807       case llvm::MachO::MH_DYLIB:
808       case llvm::MachO::MH_BUNDLE:
809         if (!flagOff)
810           ctx.setGenerateVersionLoadCommand(true);
811         break;
812       case llvm::MachO::MH_FVMLIB:
813       case llvm::MachO::MH_DYLDLINK:
814       case llvm::MachO::MH_DYLIB_STUB:
815       case llvm::MachO::MH_DSYM:
816         // We don't generate load commands for these file types, even if
817         // forced on.
818         break;
819     }
820   }
821
822   // Handle -function_starts or -no_function_starts
823   {
824     bool flagOn = false;
825     bool flagOff = false;
826     if (auto *arg = parsedArgs.getLastArg(OPT_function_starts,
827                                           OPT_no_function_starts)) {
828       flagOn = arg->getOption().getID() == OPT_function_starts;
829       flagOff = arg->getOption().getID() == OPT_no_function_starts;
830     }
831
832     // default to adding functions start for dynamic code, static code must
833     // opt-in
834     switch (ctx.outputMachOType()) {
835       case llvm::MachO::MH_OBJECT:
836         ctx.setGenerateFunctionStartsLoadCommand(false);
837         break;
838       case llvm::MachO::MH_EXECUTE:
839         // dynamic executables default to generating a version load command,
840         // while static exectuables only generate it if required.
841         if (isStaticExecutable) {
842           if (flagOn)
843             ctx.setGenerateFunctionStartsLoadCommand(true);
844         } else {
845           if (!flagOff)
846             ctx.setGenerateFunctionStartsLoadCommand(true);
847         }
848         break;
849       case llvm::MachO::MH_PRELOAD:
850       case llvm::MachO::MH_KEXT_BUNDLE:
851         if (flagOn)
852           ctx.setGenerateFunctionStartsLoadCommand(true);
853         break;
854       case llvm::MachO::MH_DYLINKER:
855       case llvm::MachO::MH_DYLIB:
856       case llvm::MachO::MH_BUNDLE:
857         if (!flagOff)
858           ctx.setGenerateFunctionStartsLoadCommand(true);
859         break;
860       case llvm::MachO::MH_FVMLIB:
861       case llvm::MachO::MH_DYLDLINK:
862       case llvm::MachO::MH_DYLIB_STUB:
863       case llvm::MachO::MH_DSYM:
864         // We don't generate load commands for these file types, even if
865         // forced on.
866         break;
867     }
868   }
869
870   // Handle -data_in_code_info or -no_data_in_code_info
871   {
872     bool flagOn = false;
873     bool flagOff = false;
874     if (auto *arg = parsedArgs.getLastArg(OPT_data_in_code_info,
875                                           OPT_no_data_in_code_info)) {
876       flagOn = arg->getOption().getID() == OPT_data_in_code_info;
877       flagOff = arg->getOption().getID() == OPT_no_data_in_code_info;
878     }
879
880     // default to adding data in code for dynamic code, static code must
881     // opt-in
882     switch (ctx.outputMachOType()) {
883       case llvm::MachO::MH_OBJECT:
884         if (!flagOff)
885           ctx.setGenerateDataInCodeLoadCommand(true);
886         break;
887       case llvm::MachO::MH_EXECUTE:
888         // dynamic executables default to generating a version load command,
889         // while static exectuables only generate it if required.
890         if (isStaticExecutable) {
891           if (flagOn)
892             ctx.setGenerateDataInCodeLoadCommand(true);
893         } else {
894           if (!flagOff)
895             ctx.setGenerateDataInCodeLoadCommand(true);
896         }
897         break;
898       case llvm::MachO::MH_PRELOAD:
899       case llvm::MachO::MH_KEXT_BUNDLE:
900         if (flagOn)
901           ctx.setGenerateDataInCodeLoadCommand(true);
902         break;
903       case llvm::MachO::MH_DYLINKER:
904       case llvm::MachO::MH_DYLIB:
905       case llvm::MachO::MH_BUNDLE:
906         if (!flagOff)
907           ctx.setGenerateDataInCodeLoadCommand(true);
908         break;
909       case llvm::MachO::MH_FVMLIB:
910       case llvm::MachO::MH_DYLDLINK:
911       case llvm::MachO::MH_DYLIB_STUB:
912       case llvm::MachO::MH_DSYM:
913         // We don't generate load commands for these file types, even if
914         // forced on.
915         break;
916     }
917   }
918
919   // Handle sdk_version
920   if (llvm::opt::Arg *arg = parsedArgs.getLastArg(OPT_sdk_version)) {
921     uint32_t sdkVersion = 0;
922     if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
923                                                 sdkVersion)) {
924       error("malformed sdkVersion value");
925       return false;
926     }
927     ctx.setSdkVersion(sdkVersion);
928   } else if (ctx.generateVersionLoadCommand()) {
929     // If we don't have an sdk version, but were going to emit a load command
930     // with min_version, then we need to give an warning as we have no sdk
931     // version to put in that command.
932     // FIXME: We need to decide whether to make this an error.
933     warn("-sdk_version is required when emitting min version load command.  "
934          "Setting sdk version to match provided min version");
935     ctx.setSdkVersion(ctx.osMinVersion());
936   }
937
938   // Handle source_version
939   if (llvm::opt::Arg *arg = parsedArgs.getLastArg(OPT_source_version)) {
940     uint64_t version = 0;
941     if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
942                                                 version)) {
943       error("malformed source_version value");
944       return false;
945     }
946     ctx.setSourceVersion(version);
947   }
948
949   // Handle stack_size
950   if (llvm::opt::Arg *stackSize = parsedArgs.getLastArg(OPT_stack_size)) {
951     uint64_t stackSizeVal;
952     if (parseNumberBase16(stackSize->getValue(), stackSizeVal)) {
953       error("stack_size expects a hex number");
954       return false;
955     }
956     if ((stackSizeVal % ctx.pageSize()) != 0) {
957       error("stack_size must be a multiple of page size (0x" +
958             llvm::utohexstr(ctx.pageSize()) + ")");
959       return false;
960     }
961
962     ctx.setStackSize(stackSizeVal);
963   }
964
965   // Handle debug info handling options: -S
966   if (parsedArgs.hasArg(OPT_S))
967     ctx.setDebugInfoMode(MachOLinkingContext::DebugInfoMode::noDebugMap);
968
969   // Handle -order_file <file>
970   for (auto orderFile : parsedArgs.filtered(OPT_order_file)) {
971     if (std::error_code ec = parseOrderFile(orderFile->getValue(), ctx)) {
972       error(ec.message() + ", processing '-order_file " + orderFile->getValue()
973             + "'");
974       return false;
975     }
976   }
977
978   // Handle -flat_namespace.
979   if (llvm::opt::Arg *ns =
980           parsedArgs.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace)) {
981     if (ns->getOption().getID() == OPT_flat_namespace)
982       ctx.setUseFlatNamespace(true);
983   }
984
985   // Handle -undefined
986   if (llvm::opt::Arg *undef = parsedArgs.getLastArg(OPT_undefined)) {
987     MachOLinkingContext::UndefinedMode UndefMode;
988     if (StringRef(undef->getValue()).equals("error"))
989       UndefMode = MachOLinkingContext::UndefinedMode::error;
990     else if (StringRef(undef->getValue()).equals("warning"))
991       UndefMode = MachOLinkingContext::UndefinedMode::warning;
992     else if (StringRef(undef->getValue()).equals("suppress"))
993       UndefMode = MachOLinkingContext::UndefinedMode::suppress;
994     else if (StringRef(undef->getValue()).equals("dynamic_lookup"))
995       UndefMode = MachOLinkingContext::UndefinedMode::dynamicLookup;
996     else {
997       error("invalid option to -undefined [ warning | error | suppress | "
998             "dynamic_lookup ]");
999       return false;
1000     }
1001
1002     if (ctx.useFlatNamespace()) {
1003       // If we're using -flat_namespace then 'warning', 'suppress' and
1004       // 'dynamic_lookup' are all equivalent, so map them to 'suppress'.
1005       if (UndefMode != MachOLinkingContext::UndefinedMode::error)
1006         UndefMode = MachOLinkingContext::UndefinedMode::suppress;
1007     } else {
1008       // If we're using -twolevel_namespace then 'warning' and 'suppress' are
1009       // illegal. Emit a diagnostic if they've been (mis)used.
1010       if (UndefMode == MachOLinkingContext::UndefinedMode::warning ||
1011           UndefMode == MachOLinkingContext::UndefinedMode::suppress) {
1012         error("can't use -undefined warning or suppress with "
1013               "-twolevel_namespace");
1014         return false;
1015       }
1016     }
1017
1018     ctx.setUndefinedMode(UndefMode);
1019   }
1020
1021   // Handle -no_objc_category_merging.
1022   if (parsedArgs.getLastArg(OPT_no_objc_category_merging))
1023     ctx.setMergeObjCCategories(false);
1024
1025   // Handle -rpath <path>
1026   if (parsedArgs.hasArg(OPT_rpath)) {
1027     switch (ctx.outputMachOType()) {
1028       case llvm::MachO::MH_EXECUTE:
1029       case llvm::MachO::MH_DYLIB:
1030       case llvm::MachO::MH_BUNDLE:
1031         if (!ctx.minOS("10.5", "2.0")) {
1032           if (ctx.os() == MachOLinkingContext::OS::macOSX)
1033             error("-rpath can only be used when targeting OS X 10.5 or later");
1034           else
1035             error("-rpath can only be used when targeting iOS 2.0 or later");
1036           return false;
1037         }
1038         break;
1039       default:
1040         error("-rpath can only be used when creating a dynamic final linked "
1041               "image");
1042         return false;
1043     }
1044
1045     for (auto rPath : parsedArgs.filtered(OPT_rpath)) {
1046       ctx.addRpath(rPath->getValue());
1047     }
1048   }
1049
1050   // Parse the LLVM options before we process files in case the file handling
1051   // makes use of things like LLVM_DEBUG().
1052   parseLLVMOptions(ctx);
1053
1054   // Handle input files and sectcreate.
1055   for (auto &arg : parsedArgs) {
1056     bool upward;
1057     llvm::Optional<StringRef> resolvedPath;
1058     switch (arg->getOption().getID()) {
1059     default:
1060       continue;
1061     case OPT_INPUT:
1062       addFile(arg->getValue(), ctx, globalWholeArchive, false);
1063       break;
1064     case OPT_upward_library:
1065       addFile(arg->getValue(), ctx, false, true);
1066       break;
1067     case OPT_force_load:
1068       addFile(arg->getValue(), ctx, true, false);
1069       break;
1070     case OPT_l:
1071     case OPT_upward_l:
1072       upward = (arg->getOption().getID() == OPT_upward_l);
1073       resolvedPath = ctx.searchLibrary(arg->getValue());
1074       if (!resolvedPath) {
1075         error("Unable to find library for " + arg->getSpelling() +
1076               arg->getValue());
1077         return false;
1078       } else if (ctx.testingFileUsage()) {
1079         message(Twine("Found ") + (upward ? "upward " : " ") + "library " +
1080                 canonicalizePath(resolvedPath.getValue()));
1081       }
1082       addFile(resolvedPath.getValue(), ctx, globalWholeArchive, upward);
1083       break;
1084     case OPT_framework:
1085     case OPT_upward_framework:
1086       upward = (arg->getOption().getID() == OPT_upward_framework);
1087       resolvedPath = ctx.findPathForFramework(arg->getValue());
1088       if (!resolvedPath) {
1089         error("Unable to find framework for " + arg->getSpelling() + " " +
1090               arg->getValue());
1091         return false;
1092       } else if (ctx.testingFileUsage()) {
1093         message(Twine("Found ") + (upward ? "upward " : " ") + "framework " +
1094                 canonicalizePath(resolvedPath.getValue()));
1095       }
1096       addFile(resolvedPath.getValue(), ctx, globalWholeArchive, upward);
1097       break;
1098     case OPT_filelist:
1099       if (auto ec = loadFileList(arg->getValue(), ctx, globalWholeArchive)) {
1100         handleAllErrors(std::move(ec), [&](const llvm::ErrorInfoBase &EI) {
1101           error(EI.message() + ", processing '-filelist " + arg->getValue());
1102         });
1103         return false;
1104       }
1105       break;
1106     case OPT_sectcreate: {
1107         const char* seg  = arg->getValue(0);
1108         const char* sect = arg->getValue(1);
1109         const char* fileName = arg->getValue(2);
1110
1111         ErrorOr<std::unique_ptr<MemoryBuffer>> contentOrErr =
1112           MemoryBuffer::getFile(fileName);
1113
1114         if (!contentOrErr) {
1115           error("can't open -sectcreate file " + Twine(fileName));
1116           return false;
1117         }
1118
1119         ctx.addSectCreateSection(seg, sect, std::move(*contentOrErr));
1120       }
1121       break;
1122     }
1123   }
1124
1125   if (ctx.getNodes().empty()) {
1126     error("No input files");
1127     return false;
1128   }
1129
1130   // Validate the combination of options used.
1131   return ctx.validate();
1132 }
1133
1134 static void createFiles(MachOLinkingContext &ctx, bool Implicit) {
1135   std::vector<std::unique_ptr<File>> Files;
1136   if (Implicit)
1137     ctx.createImplicitFiles(Files);
1138   else
1139     ctx.createInternalFiles(Files);
1140   for (auto i = Files.rbegin(), e = Files.rend(); i != e; ++i) {
1141     auto &members = ctx.getNodes();
1142     members.insert(members.begin(), llvm::make_unique<FileNode>(std::move(*i)));
1143   }
1144 }
1145
1146 /// This is where the link is actually performed.
1147 bool link(llvm::ArrayRef<const char *> args, bool CanExitEarly,
1148           raw_ostream &Error) {
1149   errorHandler().LogName = args::getFilenameWithoutExe(args[0]);
1150   errorHandler().ErrorLimitExceededMsg =
1151       "too many errors emitted, stopping now (use "
1152       "'-error-limit 0' to see all errors)";
1153   errorHandler().ErrorOS = &Error;
1154   errorHandler().ExitEarly = CanExitEarly;
1155   errorHandler().ColorDiagnostics = Error.has_colors();
1156
1157   MachOLinkingContext ctx;
1158   if (!parse(args, ctx))
1159     return false;
1160   if (ctx.doNothing())
1161     return true;
1162   if (ctx.getNodes().empty())
1163     return false;
1164
1165   for (std::unique_ptr<Node> &ie : ctx.getNodes())
1166     if (FileNode *node = dyn_cast<FileNode>(ie.get()))
1167       node->getFile()->parse();
1168
1169   createFiles(ctx, false /* Implicit */);
1170
1171   // Give target a chance to add files
1172   createFiles(ctx, true /* Implicit */);
1173
1174   // Give target a chance to postprocess input files.
1175   // Mach-O uses this chance to move all object files before library files.
1176   ctx.finalizeInputFiles();
1177
1178   // Do core linking.
1179   ScopedTask resolveTask(getDefaultDomain(), "Resolve");
1180   Resolver resolver(ctx);
1181   if (!resolver.resolve())
1182     return false;
1183   SimpleFile *merged = nullptr;
1184   {
1185     std::unique_ptr<SimpleFile> mergedFile = resolver.resultFile();
1186     merged = mergedFile.get();
1187     auto &members = ctx.getNodes();
1188     members.insert(members.begin(),
1189                    llvm::make_unique<FileNode>(std::move(mergedFile)));
1190   }
1191   resolveTask.end();
1192
1193   // Run passes on linked atoms.
1194   ScopedTask passTask(getDefaultDomain(), "Passes");
1195   PassManager pm;
1196   ctx.addPasses(pm);
1197   if (auto ec = pm.runOnFile(*merged)) {
1198     // FIXME: This should be passed to logAllUnhandledErrors but it needs
1199     // to be passed a Twine instead of a string.
1200     *errorHandler().ErrorOS << "Failed to run passes on file '"
1201                             << ctx.outputPath() << "': ";
1202     logAllUnhandledErrors(std::move(ec), *errorHandler().ErrorOS,
1203                           std::string());
1204     return false;
1205   }
1206
1207   passTask.end();
1208
1209   // Give linked atoms to Writer to generate output file.
1210   ScopedTask writeTask(getDefaultDomain(), "Write");
1211   if (auto ec = ctx.writeFile(*merged)) {
1212     // FIXME: This should be passed to logAllUnhandledErrors but it needs
1213     // to be passed a Twine instead of a string.
1214     *errorHandler().ErrorOS << "Failed to write file '" << ctx.outputPath()
1215                             << "': ";
1216     logAllUnhandledErrors(std::move(ec), *errorHandler().ErrorOS,
1217                           std::string());
1218     return false;
1219   }
1220
1221   // Call exit() if we can to avoid calling destructors.
1222   if (CanExitEarly)
1223     exitLld(errorCount() ? 1 : 0);
1224
1225
1226   return true;
1227 }
1228
1229 } // end namespace mach_o
1230 } // end namespace lld