Bug Summary

File:tools/lld/include/lld/Core/PassManager.h
Warning:line 37, column 28
Use of memory after it is freed

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name DarwinLdDriver.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/lld/lib/Driver -I /build/llvm-toolchain-snapshot-7~svn338205/tools/lld/lib/Driver -I /build/llvm-toolchain-snapshot-7~svn338205/tools/lld/include -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/lld/include -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn338205/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/8/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/lld/lib/Driver -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-07-29-043837-17923-1 -x c++ /build/llvm-toolchain-snapshot-7~svn338205/tools/lld/lib/Driver/DarwinLdDriver.cpp -faddrsig

/build/llvm-toolchain-snapshot-7~svn338205/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
59using namespace lld;
60
61namespace {
62
63// Create enum with OPT_xxx values for each option in DarwinLdOptions.td
64enum {
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
79static 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
91class DarwinLdOptTable : public llvm::opt::OptTable {
92public:
93 DarwinLdOptTable() : OptTable(InfoTable) {}
94};
95
96static std::vector<std::unique_ptr<File>>
97makeErrorFile(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
103static std::vector<std::unique_ptr<File>>
104parseMemberFiles(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
115std::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.
148static 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
159static 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 #.
169static 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
199static 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//
253static 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.
296static 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
302static 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
315namespace lld {
316namespace mach_o {
317
318bool 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(), args[0], "LLVM Linker", false);
387 else
388 error("-arch not specified and could not be inferred");
389 return false;
390 }
391 }
392
393 // Handle -macosx_version_min or -ios_version_min
394 MachOLinkingContext::OS os = MachOLinkingContext::OS::unknown;
395 uint32_t minOSVersion = 0;
396 if (llvm::opt::Arg *minOS =
397 parsedArgs.getLastArg(OPT_macosx_version_min, OPT_ios_version_min,
398 OPT_ios_simulator_version_min)) {
399 switch (minOS->getOption().getID()) {
400 case OPT_macosx_version_min:
401 os = MachOLinkingContext::OS::macOSX;
402 if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
403 minOSVersion)) {
404 error("malformed macosx_version_min value");
405 return false;
406 }
407 break;
408 case OPT_ios_version_min:
409 os = MachOLinkingContext::OS::iOS;
410 if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
411 minOSVersion)) {
412 error("malformed ios_version_min value");
413 return false;
414 }
415 break;
416 case OPT_ios_simulator_version_min:
417 os = MachOLinkingContext::OS::iOS_simulator;
418 if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
419 minOSVersion)) {
420 error("malformed ios_simulator_version_min value");
421 return false;
422 }
423 break;
424 }
425 } else {
426 // No min-os version on command line, check environment variables
427 }
428
429 // Handle export_dynamic
430 // FIXME: Should we warn when this applies to something other than a static
431 // executable or dylib? Those are the only cases where this has an effect.
432 // Note, this has to come before ctx.configure() so that we get the correct
433 // value for _globalsAreDeadStripRoots.
434 bool exportDynamicSymbols = parsedArgs.hasArg(OPT_export_dynamic);
435
436 // Now that there's enough information parsed in, let the linking context
437 // set up default values.
438 ctx.configure(fileType, arch, os, minOSVersion, exportDynamicSymbols);
439
440 // Handle -e xxx
441 if (llvm::opt::Arg *entry = parsedArgs.getLastArg(OPT_entry))
442 ctx.setEntrySymbolName(entry->getValue());
443
444 // Handle -o xxx
445 if (llvm::opt::Arg *outpath = parsedArgs.getLastArg(OPT_output))
446 ctx.setOutputPath(outpath->getValue());
447 else
448 ctx.setOutputPath("a.out");
449
450 // Handle -image_base XXX and -seg1addr XXXX
451 if (llvm::opt::Arg *imageBase = parsedArgs.getLastArg(OPT_image_base)) {
452 uint64_t baseAddress;
453 if (parseNumberBase16(imageBase->getValue(), baseAddress)) {
454 error("image_base expects a hex number");
455 return false;
456 } else if (baseAddress < ctx.pageZeroSize()) {
457 error("image_base overlaps with __PAGEZERO");
458 return false;
459 } else if (baseAddress % ctx.pageSize()) {
460 error("image_base must be a multiple of page size (0x" +
461 llvm::utohexstr(ctx.pageSize()) + ")");
462 return false;
463 }
464
465 ctx.setBaseAddress(baseAddress);
466 }
467
468 // Handle -dead_strip
469 if (parsedArgs.getLastArg(OPT_dead_strip))
470 ctx.setDeadStripping(true);
471
472 bool globalWholeArchive = false;
473 // Handle -all_load
474 if (parsedArgs.getLastArg(OPT_all_load))
475 globalWholeArchive = true;
476
477 // Handle -install_name
478 if (llvm::opt::Arg *installName = parsedArgs.getLastArg(OPT_install_name))
479 ctx.setInstallName(installName->getValue());
480 else
481 ctx.setInstallName(ctx.outputPath());
482
483 // Handle -mark_dead_strippable_dylib
484 if (parsedArgs.getLastArg(OPT_mark_dead_strippable_dylib))
485 ctx.setDeadStrippableDylib(true);
486
487 // Handle -compatibility_version and -current_version
488 if (llvm::opt::Arg *vers = parsedArgs.getLastArg(OPT_compatibility_version)) {
489 if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) {
490 error("-compatibility_version can only be used with -dylib");
491 return false;
492 }
493 uint32_t parsedVers;
494 if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
495 error("-compatibility_version value is malformed");
496 return false;
497 }
498 ctx.setCompatibilityVersion(parsedVers);
499 }
500
501 if (llvm::opt::Arg *vers = parsedArgs.getLastArg(OPT_current_version)) {
502 if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) {
503 error("-current_version can only be used with -dylib");
504 return false;
505 }
506 uint32_t parsedVers;
507 if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
508 error("-current_version value is malformed");
509 return false;
510 }
511 ctx.setCurrentVersion(parsedVers);
512 }
513
514 // Handle -bundle_loader
515 if (llvm::opt::Arg *loader = parsedArgs.getLastArg(OPT_bundle_loader))
516 ctx.setBundleLoader(loader->getValue());
517
518 // Handle -sectalign segname sectname align
519 for (auto &alignArg : parsedArgs.filtered(OPT_sectalign)) {
520 const char* segName = alignArg->getValue(0);
521 const char* sectName = alignArg->getValue(1);
522 const char* alignStr = alignArg->getValue(2);
523 if ((alignStr[0] == '0') && (alignStr[1] == 'x'))
524 alignStr += 2;
525 unsigned long long alignValue;
526 if (llvm::getAsUnsignedInteger(alignStr, 16, alignValue)) {
527 error("-sectalign alignment value '" + Twine(alignStr) +
528 "' not a valid number");
529 return false;
530 }
531 uint16_t align = 1 << llvm::countTrailingZeros(alignValue);
532 if (!llvm::isPowerOf2_64(alignValue)) {
533 std::string Msg;
534 llvm::raw_string_ostream OS(Msg);
535 OS << "alignment for '-sectalign " << segName << " " << sectName
536 << llvm::format(" 0x%llX", alignValue)
537 << "' is not a power of two, using " << llvm::format("0x%08X", align);
538 OS.flush();
539 warn(Msg);
540 }
541 ctx.addSectionAlignment(segName, sectName, align);
542 }
543
544 // Handle -mllvm
545 for (auto &llvmArg : parsedArgs.filtered(OPT_mllvm)) {
546 ctx.appendLLVMOption(llvmArg->getValue());
547 }
548
549 // Handle -print_atoms
550 if (parsedArgs.getLastArg(OPT_print_atoms))
551 ctx.setPrintAtoms();
552
553 // Handle -t (trace) option.
554 if (parsedArgs.getLastArg(OPT_t))
555 ctx.setLogInputFiles(true);
556
557 // Handle -demangle option.
558 if (parsedArgs.getLastArg(OPT_demangle))
559 ctx.setDemangleSymbols(true);
560
561 // Handle -keep_private_externs
562 if (parsedArgs.getLastArg(OPT_keep_private_externs)) {
563 ctx.setKeepPrivateExterns(true);
564 if (ctx.outputMachOType() != llvm::MachO::MH_OBJECT)
565 warn("-keep_private_externs only used in -r mode");
566 }
567
568 // Handle -dependency_info <path> used by Xcode.
569 if (llvm::opt::Arg *depInfo = parsedArgs.getLastArg(OPT_dependency_info))
570 if (std::error_code ec = ctx.createDependencyFile(depInfo->getValue()))
571 warn(ec.message() + ", processing '-dependency_info " +
572 depInfo->getValue());
573
574 // In -test_file_usage mode, we'll be given an explicit list of paths that
575 // exist. We'll also be expected to print out information about how we located
576 // libraries and so on that the user specified, but not to actually do any
577 // linking.
578 if (parsedArgs.getLastArg(OPT_test_file_usage)) {
579 ctx.setTestingFileUsage();
580
581 // With paths existing by fiat, linking is not going to end well.
582 ctx.setDoNothing(true);
583
584 // Only bother looking for an existence override if we're going to use it.
585 for (auto existingPath : parsedArgs.filtered(OPT_path_exists)) {
586 ctx.addExistingPathForDebug(existingPath->getValue());
587 }
588 }
589
590 // Register possible input file parsers.
591 if (!ctx.doNothing()) {
592 ctx.registry().addSupportMachOObjects(ctx);
593 ctx.registry().addSupportArchives(ctx.logInputFiles());
594 ctx.registry().addSupportYamlFiles();
595 }
596
597 // Now construct the set of library search directories, following ld64's
598 // baroque set of accumulated hacks. Mostly, the algorithm constructs
599 // { syslibroots } x { libpaths }
600 //
601 // Unfortunately, there are numerous exceptions:
602 // 1. Only absolute paths get modified by syslibroot options.
603 // 2. If there is just 1 -syslibroot, system paths not found in it are
604 // skipped.
605 // 3. If the last -syslibroot is "/", all of them are ignored entirely.
606 // 4. If { syslibroots } x path == {}, the original path is kept.
607 std::vector<StringRef> sysLibRoots;
608 for (auto syslibRoot : parsedArgs.filtered(OPT_syslibroot)) {
609 sysLibRoots.push_back(syslibRoot->getValue());
610 }
611 if (!sysLibRoots.empty()) {
612 // Ignore all if last -syslibroot is "/".
613 if (sysLibRoots.back() != "/")
614 ctx.setSysLibRoots(sysLibRoots);
615 }
616
617 // Paths specified with -L come first, and are not considered system paths for
618 // the case where there is precisely 1 -syslibroot.
619 for (auto libPath : parsedArgs.filtered(OPT_L)) {
620 ctx.addModifiedSearchDir(libPath->getValue());
621 }
622
623 // Process -F directories (where to look for frameworks).
624 for (auto fwPath : parsedArgs.filtered(OPT_F)) {
625 ctx.addFrameworkSearchDir(fwPath->getValue());
626 }
627
628 // -Z suppresses the standard search paths.
629 if (!parsedArgs.hasArg(OPT_Z)) {
630 ctx.addModifiedSearchDir("/usr/lib", true);
631 ctx.addModifiedSearchDir("/usr/local/lib", true);
632 ctx.addFrameworkSearchDir("/Library/Frameworks", true);
633 ctx.addFrameworkSearchDir("/System/Library/Frameworks", true);
634 }
635
636 // Now that we've constructed the final set of search paths, print out those
637 // search paths in verbose mode.
638 if (errorHandler().Verbose) {
639 message("Library search paths:");
640 for (auto path : ctx.searchDirs()) {
641 message(" " + path);
642 }
643 message("Framework search paths:");
644 for (auto path : ctx.frameworkDirs()) {
645 message(" " + path);
646 }
647 }
648
649 // Handle -exported_symbols_list <file>
650 for (auto expFile : parsedArgs.filtered(OPT_exported_symbols_list)) {
651 if (ctx.exportMode() == MachOLinkingContext::ExportMode::blackList) {
652 error("-exported_symbols_list cannot be combined with "
653 "-unexported_symbol[s_list]");
654 return false;
655 }
656 ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList);
657 if (std::error_code ec = parseExportsList(expFile->getValue(), ctx)) {
658 error(ec.message() + ", processing '-exported_symbols_list " +
659 expFile->getValue());
660 return false;
661 }
662 }
663
664 // Handle -exported_symbol <symbol>
665 for (auto symbol : parsedArgs.filtered(OPT_exported_symbol)) {
666 if (ctx.exportMode() == MachOLinkingContext::ExportMode::blackList) {
667 error("-exported_symbol cannot be combined with "
668 "-unexported_symbol[s_list]");
669 return false;
670 }
671 ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList);
672 ctx.addExportSymbol(symbol->getValue());
673 }
674
675 // Handle -unexported_symbols_list <file>
676 for (auto expFile : parsedArgs.filtered(OPT_unexported_symbols_list)) {
677 if (ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList) {
678 error("-unexported_symbols_list cannot be combined with "
679 "-exported_symbol[s_list]");
680 return false;
681 }
682 ctx.setExportMode(MachOLinkingContext::ExportMode::blackList);
683 if (std::error_code ec = parseExportsList(expFile->getValue(), ctx)) {
684 error(ec.message() + ", processing '-unexported_symbols_list " +
685 expFile->getValue());
686 return false;
687 }
688 }
689
690 // Handle -unexported_symbol <symbol>
691 for (auto symbol : parsedArgs.filtered(OPT_unexported_symbol)) {
692 if (ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList) {
693 error("-unexported_symbol cannot be combined with "
694 "-exported_symbol[s_list]");
695 return false;
696 }
697 ctx.setExportMode(MachOLinkingContext::ExportMode::blackList);
698 ctx.addExportSymbol(symbol->getValue());
699 }
700
701 // Handle obosolete -multi_module and -single_module
702 if (llvm::opt::Arg *mod =
703 parsedArgs.getLastArg(OPT_multi_module, OPT_single_module)) {
704 if (mod->getOption().getID() == OPT_multi_module)
705 warn("-multi_module is obsolete and being ignored");
706 else if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB)
707 warn("-single_module being ignored. It is only for use when producing a "
708 "dylib");
709 }
710
711 // Handle obsolete ObjC options: -objc_gc_compaction, -objc_gc, -objc_gc_only
712 if (parsedArgs.getLastArg(OPT_objc_gc_compaction)) {
713 error("-objc_gc_compaction is not supported");
714 return false;
715 }
716
717 if (parsedArgs.getLastArg(OPT_objc_gc)) {
718 error("-objc_gc is not supported");
719 return false;
720 }
721
722 if (parsedArgs.getLastArg(OPT_objc_gc_only)) {
723 error("-objc_gc_only is not supported");
724 return false;
725 }
726
727 // Handle -pie or -no_pie
728 if (llvm::opt::Arg *pie = parsedArgs.getLastArg(OPT_pie, OPT_no_pie)) {
729 switch (ctx.outputMachOType()) {
730 case llvm::MachO::MH_EXECUTE:
731 switch (ctx.os()) {
732 case MachOLinkingContext::OS::macOSX:
733 if ((minOSVersion < 0x000A0500) &&
734 (pie->getOption().getID() == OPT_pie)) {
735 error("-pie can only be used when targeting Mac OS X 10.5 or later");
736 return false;
737 }
738 break;
739 case MachOLinkingContext::OS::iOS:
740 if ((minOSVersion < 0x00040200) &&
741 (pie->getOption().getID() == OPT_pie)) {
742 error("-pie can only be used when targeting iOS 4.2 or later");
743 return false;
744 }
745 break;
746 case MachOLinkingContext::OS::iOS_simulator:
747 if (pie->getOption().getID() == OPT_no_pie) {
748 error("iOS simulator programs must be built PIE");
749 return false;
750 }
751 break;
752 case MachOLinkingContext::OS::unknown:
753 break;
754 }
755 ctx.setPIE(pie->getOption().getID() == OPT_pie);
756 break;
757 case llvm::MachO::MH_PRELOAD:
758 break;
759 case llvm::MachO::MH_DYLIB:
760 case llvm::MachO::MH_BUNDLE:
761 warn(pie->getSpelling() +
762 " being ignored. It is only used when linking main executables");
763 break;
764 default:
765 error(pie->getSpelling() +
766 " can only used when linking main executables");
767 return false;
768 }
769 }
770
771 // Handle -version_load_command or -no_version_load_command
772 {
773 bool flagOn = false;
774 bool flagOff = false;
775 if (auto *arg = parsedArgs.getLastArg(OPT_version_load_command,
776 OPT_no_version_load_command)) {
777 flagOn = arg->getOption().getID() == OPT_version_load_command;
778 flagOff = arg->getOption().getID() == OPT_no_version_load_command;
779 }
780
781 // default to adding version load command for dynamic code,
782 // static code must opt-in
783 switch (ctx.outputMachOType()) {
784 case llvm::MachO::MH_OBJECT:
785 ctx.setGenerateVersionLoadCommand(false);
786 break;
787 case llvm::MachO::MH_EXECUTE:
788 // dynamic executables default to generating a version load command,
789 // while static exectuables only generate it if required.
790 if (isStaticExecutable) {
791 if (flagOn)
792 ctx.setGenerateVersionLoadCommand(true);
793 } else {
794 if (!flagOff)
795 ctx.setGenerateVersionLoadCommand(true);
796 }
797 break;
798 case llvm::MachO::MH_PRELOAD:
799 case llvm::MachO::MH_KEXT_BUNDLE:
800 if (flagOn)
801 ctx.setGenerateVersionLoadCommand(true);
802 break;
803 case llvm::MachO::MH_DYLINKER:
804 case llvm::MachO::MH_DYLIB:
805 case llvm::MachO::MH_BUNDLE:
806 if (!flagOff)
807 ctx.setGenerateVersionLoadCommand(true);
808 break;
809 case llvm::MachO::MH_FVMLIB:
810 case llvm::MachO::MH_DYLDLINK:
811 case llvm::MachO::MH_DYLIB_STUB:
812 case llvm::MachO::MH_DSYM:
813 // We don't generate load commands for these file types, even if
814 // forced on.
815 break;
816 }
817 }
818
819 // Handle -function_starts or -no_function_starts
820 {
821 bool flagOn = false;
822 bool flagOff = false;
823 if (auto *arg = parsedArgs.getLastArg(OPT_function_starts,
824 OPT_no_function_starts)) {
825 flagOn = arg->getOption().getID() == OPT_function_starts;
826 flagOff = arg->getOption().getID() == OPT_no_function_starts;
827 }
828
829 // default to adding functions start for dynamic code, static code must
830 // opt-in
831 switch (ctx.outputMachOType()) {
832 case llvm::MachO::MH_OBJECT:
833 ctx.setGenerateFunctionStartsLoadCommand(false);
834 break;
835 case llvm::MachO::MH_EXECUTE:
836 // dynamic executables default to generating a version load command,
837 // while static exectuables only generate it if required.
838 if (isStaticExecutable) {
839 if (flagOn)
840 ctx.setGenerateFunctionStartsLoadCommand(true);
841 } else {
842 if (!flagOff)
843 ctx.setGenerateFunctionStartsLoadCommand(true);
844 }
845 break;
846 case llvm::MachO::MH_PRELOAD:
847 case llvm::MachO::MH_KEXT_BUNDLE:
848 if (flagOn)
849 ctx.setGenerateFunctionStartsLoadCommand(true);
850 break;
851 case llvm::MachO::MH_DYLINKER:
852 case llvm::MachO::MH_DYLIB:
853 case llvm::MachO::MH_BUNDLE:
854 if (!flagOff)
855 ctx.setGenerateFunctionStartsLoadCommand(true);
856 break;
857 case llvm::MachO::MH_FVMLIB:
858 case llvm::MachO::MH_DYLDLINK:
859 case llvm::MachO::MH_DYLIB_STUB:
860 case llvm::MachO::MH_DSYM:
861 // We don't generate load commands for these file types, even if
862 // forced on.
863 break;
864 }
865 }
866
867 // Handle -data_in_code_info or -no_data_in_code_info
868 {
869 bool flagOn = false;
870 bool flagOff = false;
871 if (auto *arg = parsedArgs.getLastArg(OPT_data_in_code_info,
872 OPT_no_data_in_code_info)) {
873 flagOn = arg->getOption().getID() == OPT_data_in_code_info;
874 flagOff = arg->getOption().getID() == OPT_no_data_in_code_info;
875 }
876
877 // default to adding data in code for dynamic code, static code must
878 // opt-in
879 switch (ctx.outputMachOType()) {
880 case llvm::MachO::MH_OBJECT:
881 if (!flagOff)
882 ctx.setGenerateDataInCodeLoadCommand(true);
883 break;
884 case llvm::MachO::MH_EXECUTE:
885 // dynamic executables default to generating a version load command,
886 // while static exectuables only generate it if required.
887 if (isStaticExecutable) {
888 if (flagOn)
889 ctx.setGenerateDataInCodeLoadCommand(true);
890 } else {
891 if (!flagOff)
892 ctx.setGenerateDataInCodeLoadCommand(true);
893 }
894 break;
895 case llvm::MachO::MH_PRELOAD:
896 case llvm::MachO::MH_KEXT_BUNDLE:
897 if (flagOn)
898 ctx.setGenerateDataInCodeLoadCommand(true);
899 break;
900 case llvm::MachO::MH_DYLINKER:
901 case llvm::MachO::MH_DYLIB:
902 case llvm::MachO::MH_BUNDLE:
903 if (!flagOff)
904 ctx.setGenerateDataInCodeLoadCommand(true);
905 break;
906 case llvm::MachO::MH_FVMLIB:
907 case llvm::MachO::MH_DYLDLINK:
908 case llvm::MachO::MH_DYLIB_STUB:
909 case llvm::MachO::MH_DSYM:
910 // We don't generate load commands for these file types, even if
911 // forced on.
912 break;
913 }
914 }
915
916 // Handle sdk_version
917 if (llvm::opt::Arg *arg = parsedArgs.getLastArg(OPT_sdk_version)) {
918 uint32_t sdkVersion = 0;
919 if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
920 sdkVersion)) {
921 error("malformed sdkVersion value");
922 return false;
923 }
924 ctx.setSdkVersion(sdkVersion);
925 } else if (ctx.generateVersionLoadCommand()) {
926 // If we don't have an sdk version, but were going to emit a load command
927 // with min_version, then we need to give an warning as we have no sdk
928 // version to put in that command.
929 // FIXME: We need to decide whether to make this an error.
930 warn("-sdk_version is required when emitting min version load command. "
931 "Setting sdk version to match provided min version");
932 ctx.setSdkVersion(ctx.osMinVersion());
933 }
934
935 // Handle source_version
936 if (llvm::opt::Arg *arg = parsedArgs.getLastArg(OPT_source_version)) {
937 uint64_t version = 0;
938 if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
939 version)) {
940 error("malformed source_version value");
941 return false;
942 }
943 ctx.setSourceVersion(version);
944 }
945
946 // Handle stack_size
947 if (llvm::opt::Arg *stackSize = parsedArgs.getLastArg(OPT_stack_size)) {
948 uint64_t stackSizeVal;
949 if (parseNumberBase16(stackSize->getValue(), stackSizeVal)) {
950 error("stack_size expects a hex number");
951 return false;
952 }
953 if ((stackSizeVal % ctx.pageSize()) != 0) {
954 error("stack_size must be a multiple of page size (0x" +
955 llvm::utohexstr(ctx.pageSize()) + ")");
956 return false;
957 }
958
959 ctx.setStackSize(stackSizeVal);
960 }
961
962 // Handle debug info handling options: -S
963 if (parsedArgs.hasArg(OPT_S))
964 ctx.setDebugInfoMode(MachOLinkingContext::DebugInfoMode::noDebugMap);
965
966 // Handle -order_file <file>
967 for (auto orderFile : parsedArgs.filtered(OPT_order_file)) {
968 if (std::error_code ec = parseOrderFile(orderFile->getValue(), ctx)) {
969 error(ec.message() + ", processing '-order_file " + orderFile->getValue()
970 + "'");
971 return false;
972 }
973 }
974
975 // Handle -flat_namespace.
976 if (llvm::opt::Arg *ns =
977 parsedArgs.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace)) {
978 if (ns->getOption().getID() == OPT_flat_namespace)
979 ctx.setUseFlatNamespace(true);
980 }
981
982 // Handle -undefined
983 if (llvm::opt::Arg *undef = parsedArgs.getLastArg(OPT_undefined)) {
984 MachOLinkingContext::UndefinedMode UndefMode;
985 if (StringRef(undef->getValue()).equals("error"))
986 UndefMode = MachOLinkingContext::UndefinedMode::error;
987 else if (StringRef(undef->getValue()).equals("warning"))
988 UndefMode = MachOLinkingContext::UndefinedMode::warning;
989 else if (StringRef(undef->getValue()).equals("suppress"))
990 UndefMode = MachOLinkingContext::UndefinedMode::suppress;
991 else if (StringRef(undef->getValue()).equals("dynamic_lookup"))
992 UndefMode = MachOLinkingContext::UndefinedMode::dynamicLookup;
993 else {
994 error("invalid option to -undefined [ warning | error | suppress | "
995 "dynamic_lookup ]");
996 return false;
997 }
998
999 if (ctx.useFlatNamespace()) {
1000 // If we're using -flat_namespace then 'warning', 'suppress' and
1001 // 'dynamic_lookup' are all equivalent, so map them to 'suppress'.
1002 if (UndefMode != MachOLinkingContext::UndefinedMode::error)
1003 UndefMode = MachOLinkingContext::UndefinedMode::suppress;
1004 } else {
1005 // If we're using -twolevel_namespace then 'warning' and 'suppress' are
1006 // illegal. Emit a diagnostic if they've been (mis)used.
1007 if (UndefMode == MachOLinkingContext::UndefinedMode::warning ||
1008 UndefMode == MachOLinkingContext::UndefinedMode::suppress) {
1009 error("can't use -undefined warning or suppress with "
1010 "-twolevel_namespace");
1011 return false;
1012 }
1013 }
1014
1015 ctx.setUndefinedMode(UndefMode);
1016 }
1017
1018 // Handle -no_objc_category_merging.
1019 if (parsedArgs.getLastArg(OPT_no_objc_category_merging))
1020 ctx.setMergeObjCCategories(false);
1021
1022 // Handle -rpath <path>
1023 if (parsedArgs.hasArg(OPT_rpath)) {
1024 switch (ctx.outputMachOType()) {
1025 case llvm::MachO::MH_EXECUTE:
1026 case llvm::MachO::MH_DYLIB:
1027 case llvm::MachO::MH_BUNDLE:
1028 if (!ctx.minOS("10.5", "2.0")) {
1029 if (ctx.os() == MachOLinkingContext::OS::macOSX)
1030 error("-rpath can only be used when targeting OS X 10.5 or later");
1031 else
1032 error("-rpath can only be used when targeting iOS 2.0 or later");
1033 return false;
1034 }
1035 break;
1036 default:
1037 error("-rpath can only be used when creating a dynamic final linked "
1038 "image");
1039 return false;
1040 }
1041
1042 for (auto rPath : parsedArgs.filtered(OPT_rpath)) {
1043 ctx.addRpath(rPath->getValue());
1044 }
1045 }
1046
1047 // Parse the LLVM options before we process files in case the file handling
1048 // makes use of things like LLVM_DEBUG().
1049 parseLLVMOptions(ctx);
1050
1051 // Handle input files and sectcreate.
1052 for (auto &arg : parsedArgs) {
1053 bool upward;
1054 llvm::Optional<StringRef> resolvedPath;
1055 switch (arg->getOption().getID()) {
1056 default:
1057 continue;
1058 case OPT_INPUT:
1059 addFile(arg->getValue(), ctx, globalWholeArchive, false);
1060 break;
1061 case OPT_upward_library:
1062 addFile(arg->getValue(), ctx, false, true);
1063 break;
1064 case OPT_force_load:
1065 addFile(arg->getValue(), ctx, true, false);
1066 break;
1067 case OPT_l:
1068 case OPT_upward_l:
1069 upward = (arg->getOption().getID() == OPT_upward_l);
1070 resolvedPath = ctx.searchLibrary(arg->getValue());
1071 if (!resolvedPath) {
1072 error("Unable to find library for " + arg->getSpelling() +
1073 arg->getValue());
1074 return false;
1075 } else if (ctx.testingFileUsage()) {
1076 message(Twine("Found ") + (upward ? "upward " : " ") + "library " +
1077 canonicalizePath(resolvedPath.getValue()));
1078 }
1079 addFile(resolvedPath.getValue(), ctx, globalWholeArchive, upward);
1080 break;
1081 case OPT_framework:
1082 case OPT_upward_framework:
1083 upward = (arg->getOption().getID() == OPT_upward_framework);
1084 resolvedPath = ctx.findPathForFramework(arg->getValue());
1085 if (!resolvedPath) {
1086 error("Unable to find framework for " + arg->getSpelling() + " " +
1087 arg->getValue());
1088 return false;
1089 } else if (ctx.testingFileUsage()) {
1090 message(Twine("Found ") + (upward ? "upward " : " ") + "framework " +
1091 canonicalizePath(resolvedPath.getValue()));
1092 }
1093 addFile(resolvedPath.getValue(), ctx, globalWholeArchive, upward);
1094 break;
1095 case OPT_filelist:
1096 if (auto ec = loadFileList(arg->getValue(), ctx, globalWholeArchive)) {
1097 handleAllErrors(std::move(ec), [&](const llvm::ErrorInfoBase &EI) {
1098 error(EI.message() + ", processing '-filelist " + arg->getValue());
1099 });
1100 return false;
1101 }
1102 break;
1103 case OPT_sectcreate: {
1104 const char* seg = arg->getValue(0);
1105 const char* sect = arg->getValue(1);
1106 const char* fileName = arg->getValue(2);
1107
1108 ErrorOr<std::unique_ptr<MemoryBuffer>> contentOrErr =
1109 MemoryBuffer::getFile(fileName);
1110
1111 if (!contentOrErr) {
1112 error("can't open -sectcreate file " + Twine(fileName));
1113 return false;
1114 }
1115
1116 ctx.addSectCreateSection(seg, sect, std::move(*contentOrErr));
1117 }
1118 break;
1119 }
1120 }
1121
1122 if (ctx.getNodes().empty()) {
1123 error("No input files");
1124 return false;
1125 }
1126
1127 // Validate the combination of options used.
1128 return ctx.validate();
1129}
1130
1131static void createFiles(MachOLinkingContext &ctx, bool Implicit) {
1132 std::vector<std::unique_ptr<File>> Files;
1133 if (Implicit)
1134 ctx.createImplicitFiles(Files);
1135 else
1136 ctx.createInternalFiles(Files);
1137 for (auto i = Files.rbegin(), e = Files.rend(); i != e; ++i) {
1138 auto &members = ctx.getNodes();
1139 members.insert(members.begin(), llvm::make_unique<FileNode>(std::move(*i)));
1140 }
1141}
1142
1143/// This is where the link is actually performed.
1144bool link(llvm::ArrayRef<const char *> args, bool CanExitEarly,
1145 raw_ostream &Error) {
1146 errorHandler().LogName = llvm::sys::path::filename(args[0]);
1147 errorHandler().ErrorLimitExceededMsg =
1148 "too many errors emitted, stopping now (use "
1149 "'-error-limit 0' to see all errors)";
1150 errorHandler().ErrorOS = &Error;
1151 errorHandler().ExitEarly = CanExitEarly;
1152 errorHandler().ColorDiagnostics = Error.has_colors();
1153
1154 MachOLinkingContext ctx;
1155 if (!parse(args, ctx))
1
Assuming the condition is false
2
Taking false branch
1156 return false;
1157 if (ctx.doNothing())
3
Assuming the condition is false
4
Taking false branch
1158 return true;
1159 if (ctx.getNodes().empty())
5
Assuming the condition is false
6
Taking false branch
1160 return false;
1161
1162 for (std::unique_ptr<Node> &ie : ctx.getNodes())
1163 if (FileNode *node = dyn_cast<FileNode>(ie.get()))
1164 node->getFile()->parse();
1165
1166 createFiles(ctx, false /* Implicit */);
1167
1168 // Give target a chance to add files
1169 createFiles(ctx, true /* Implicit */);
1170
1171 // Give target a chance to postprocess input files.
1172 // Mach-O uses this chance to move all object files before library files.
1173 ctx.finalizeInputFiles();
1174
1175 // Do core linking.
1176 ScopedTask resolveTask(getDefaultDomain(), "Resolve");
1177 Resolver resolver(ctx);
1178 if (!resolver.resolve())
7
Assuming the condition is false
8
Taking false branch
1179 return false;
1180 SimpleFile *merged = nullptr;
1181 {
1182 std::unique_ptr<SimpleFile> mergedFile = resolver.resultFile();
1183 merged = mergedFile.get();
1184 auto &members = ctx.getNodes();
1185 members.insert(members.begin(),
1186 llvm::make_unique<FileNode>(std::move(mergedFile)));
9
Calling 'make_unique<lld::FileNode, std::unique_ptr<lld::SimpleFile, std::default_delete<lld::SimpleFile> >>'
17
Returning; memory was released
1187 }
1188 resolveTask.end();
1189
1190 // Run passes on linked atoms.
1191 ScopedTask passTask(getDefaultDomain(), "Passes");
1192 PassManager pm;
1193 ctx.addPasses(pm);
1194 if (auto ec = pm.runOnFile(*merged)) {
18
Calling 'PassManager::runOnFile'
1195 // FIXME: This should be passed to logAllUnhandledErrors but it needs
1196 // to be passed a Twine instead of a string.
1197 *errorHandler().ErrorOS << "Failed to run passes on file '"
1198 << ctx.outputPath() << "': ";
1199 logAllUnhandledErrors(std::move(ec), *errorHandler().ErrorOS,
1200 std::string());
1201 return false;
1202 }
1203
1204 passTask.end();
1205
1206 // Give linked atoms to Writer to generate output file.
1207 ScopedTask writeTask(getDefaultDomain(), "Write");
1208 if (auto ec = ctx.writeFile(*merged)) {
1209 // FIXME: This should be passed to logAllUnhandledErrors but it needs
1210 // to be passed a Twine instead of a string.
1211 *errorHandler().ErrorOS << "Failed to write file '" << ctx.outputPath()
1212 << "': ";
1213 logAllUnhandledErrors(std::move(ec), *errorHandler().ErrorOS,
1214 std::string());
1215 return false;
1216 }
1217
1218 // Call exit() if we can to avoid calling destructors.
1219 if (CanExitEarly)
1220 exitLld(errorCount() ? 1 : 0);
1221
1222
1223 return true;
1224}
1225
1226} // end namespace mach_o
1227} // end namespace lld

/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/ADT/STLExtras.h

1//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains some templates that are useful if you are working with the
11// STL at all.
12//
13// No library is required when using these functions.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_ADT_STLEXTRAS_H
18#define LLVM_ADT_STLEXTRAS_H
19
20#include "llvm/ADT/Optional.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/iterator.h"
23#include "llvm/ADT/iterator_range.h"
24#include "llvm/Support/ErrorHandling.h"
25#include <algorithm>
26#include <cassert>
27#include <cstddef>
28#include <cstdint>
29#include <cstdlib>
30#include <functional>
31#include <initializer_list>
32#include <iterator>
33#include <limits>
34#include <memory>
35#include <tuple>
36#include <type_traits>
37#include <utility>
38
39#ifdef EXPENSIVE_CHECKS
40#include <random> // for std::mt19937
41#endif
42
43namespace llvm {
44
45// Only used by compiler if both template types are the same. Useful when
46// using SFINAE to test for the existence of member functions.
47template <typename T, T> struct SameType;
48
49namespace detail {
50
51template <typename RangeT>
52using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
53
54template <typename RangeT>
55using ValueOfRange = typename std::remove_reference<decltype(
56 *std::begin(std::declval<RangeT &>()))>::type;
57
58} // end namespace detail
59
60//===----------------------------------------------------------------------===//
61// Extra additions to <type_traits>
62//===----------------------------------------------------------------------===//
63
64template <typename T>
65struct negation : std::integral_constant<bool, !bool(T::value)> {};
66
67template <typename...> struct conjunction : std::true_type {};
68template <typename B1> struct conjunction<B1> : B1 {};
69template <typename B1, typename... Bn>
70struct conjunction<B1, Bn...>
71 : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
72
73//===----------------------------------------------------------------------===//
74// Extra additions to <functional>
75//===----------------------------------------------------------------------===//
76
77template <class Ty> struct identity {
78 using argument_type = Ty;
79
80 Ty &operator()(Ty &self) const {
81 return self;
82 }
83 const Ty &operator()(const Ty &self) const {
84 return self;
85 }
86};
87
88template <class Ty> struct less_ptr {
89 bool operator()(const Ty* left, const Ty* right) const {
90 return *left < *right;
91 }
92};
93
94template <class Ty> struct greater_ptr {
95 bool operator()(const Ty* left, const Ty* right) const {
96 return *right < *left;
97 }
98};
99
100/// An efficient, type-erasing, non-owning reference to a callable. This is
101/// intended for use as the type of a function parameter that is not used
102/// after the function in question returns.
103///
104/// This class does not own the callable, so it is not in general safe to store
105/// a function_ref.
106template<typename Fn> class function_ref;
107
108template<typename Ret, typename ...Params>
109class function_ref<Ret(Params...)> {
110 Ret (*callback)(intptr_t callable, Params ...params) = nullptr;
111 intptr_t callable;
112
113 template<typename Callable>
114 static Ret callback_fn(intptr_t callable, Params ...params) {
115 return (*reinterpret_cast<Callable*>(callable))(
116 std::forward<Params>(params)...);
117 }
118
119public:
120 function_ref() = default;
121 function_ref(std::nullptr_t) {}
122
123 template <typename Callable>
124 function_ref(Callable &&callable,
125 typename std::enable_if<
126 !std::is_same<typename std::remove_reference<Callable>::type,
127 function_ref>::value>::type * = nullptr)
128 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
129 callable(reinterpret_cast<intptr_t>(&callable)) {}
130
131 Ret operator()(Params ...params) const {
132 return callback(callable, std::forward<Params>(params)...);
133 }
134
135 operator bool() const { return callback; }
136};
137
138// deleter - Very very very simple method that is used to invoke operator
139// delete on something. It is used like this:
140//
141// for_each(V.begin(), B.end(), deleter<Interval>);
142template <class T>
143inline void deleter(T *Ptr) {
144 delete Ptr;
145}
146
147//===----------------------------------------------------------------------===//
148// Extra additions to <iterator>
149//===----------------------------------------------------------------------===//
150
151namespace adl_detail {
152
153using std::begin;
154
155template <typename ContainerTy>
156auto adl_begin(ContainerTy &&container)
157 -> decltype(begin(std::forward<ContainerTy>(container))) {
158 return begin(std::forward<ContainerTy>(container));
159}
160
161using std::end;
162
163template <typename ContainerTy>
164auto adl_end(ContainerTy &&container)
165 -> decltype(end(std::forward<ContainerTy>(container))) {
166 return end(std::forward<ContainerTy>(container));
167}
168
169using std::swap;
170
171template <typename T>
172void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(),
173 std::declval<T>()))) {
174 swap(std::forward<T>(lhs), std::forward<T>(rhs));
175}
176
177} // end namespace adl_detail
178
179template <typename ContainerTy>
180auto adl_begin(ContainerTy &&container)
181 -> decltype(adl_detail::adl_begin(std::forward<ContainerTy>(container))) {
182 return adl_detail::adl_begin(std::forward<ContainerTy>(container));
183}
184
185template <typename ContainerTy>
186auto adl_end(ContainerTy &&container)
187 -> decltype(adl_detail::adl_end(std::forward<ContainerTy>(container))) {
188 return adl_detail::adl_end(std::forward<ContainerTy>(container));
189}
190
191template <typename T>
192void adl_swap(T &&lhs, T &&rhs) noexcept(
193 noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) {
194 adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs));
195}
196
197// mapped_iterator - This is a simple iterator adapter that causes a function to
198// be applied whenever operator* is invoked on the iterator.
199
200template <typename ItTy, typename FuncTy,
201 typename FuncReturnTy =
202 decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
203class mapped_iterator
204 : public iterator_adaptor_base<
205 mapped_iterator<ItTy, FuncTy>, ItTy,
206 typename std::iterator_traits<ItTy>::iterator_category,
207 typename std::remove_reference<FuncReturnTy>::type> {
208public:
209 mapped_iterator(ItTy U, FuncTy F)
210 : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {}
211
212 ItTy getCurrent() { return this->I; }
213
214 FuncReturnTy operator*() { return F(*this->I); }
215
216private:
217 FuncTy F;
218};
219
220// map_iterator - Provide a convenient way to create mapped_iterators, just like
221// make_pair is useful for creating pairs...
222template <class ItTy, class FuncTy>
223inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) {
224 return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
225}
226
227/// Helper to determine if type T has a member called rbegin().
228template <typename Ty> class has_rbegin_impl {
229 using yes = char[1];
230 using no = char[2];
231
232 template <typename Inner>
233 static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
234
235 template <typename>
236 static no& test(...);
237
238public:
239 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
240};
241
242/// Metafunction to determine if T& or T has a member called rbegin().
243template <typename Ty>
244struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
245};
246
247// Returns an iterator_range over the given container which iterates in reverse.
248// Note that the container must have rbegin()/rend() methods for this to work.
249template <typename ContainerTy>
250auto reverse(ContainerTy &&C,
251 typename std::enable_if<has_rbegin<ContainerTy>::value>::type * =
252 nullptr) -> decltype(make_range(C.rbegin(), C.rend())) {
253 return make_range(C.rbegin(), C.rend());
254}
255
256// Returns a std::reverse_iterator wrapped around the given iterator.
257template <typename IteratorTy>
258std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
259 return std::reverse_iterator<IteratorTy>(It);
260}
261
262// Returns an iterator_range over the given container which iterates in reverse.
263// Note that the container must have begin()/end() methods which return
264// bidirectional iterators for this to work.
265template <typename ContainerTy>
266auto reverse(
267 ContainerTy &&C,
268 typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr)
269 -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)),
270 llvm::make_reverse_iterator(std::begin(C)))) {
271 return make_range(llvm::make_reverse_iterator(std::end(C)),
272 llvm::make_reverse_iterator(std::begin(C)));
273}
274
275/// An iterator adaptor that filters the elements of given inner iterators.
276///
277/// The predicate parameter should be a callable object that accepts the wrapped
278/// iterator's reference type and returns a bool. When incrementing or
279/// decrementing the iterator, it will call the predicate on each element and
280/// skip any where it returns false.
281///
282/// \code
283/// int A[] = { 1, 2, 3, 4 };
284/// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
285/// // R contains { 1, 3 }.
286/// \endcode
287///
288/// Note: filter_iterator_base implements support for forward iteration.
289/// filter_iterator_impl exists to provide support for bidirectional iteration,
290/// conditional on whether the wrapped iterator supports it.
291template <typename WrappedIteratorT, typename PredicateT, typename IterTag>
292class filter_iterator_base
293 : public iterator_adaptor_base<
294 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
295 WrappedIteratorT,
296 typename std::common_type<
297 IterTag, typename std::iterator_traits<
298 WrappedIteratorT>::iterator_category>::type> {
299 using BaseT = iterator_adaptor_base<
300 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
301 WrappedIteratorT,
302 typename std::common_type<
303 IterTag, typename std::iterator_traits<
304 WrappedIteratorT>::iterator_category>::type>;
305
306protected:
307 WrappedIteratorT End;
308 PredicateT Pred;
309
310 void findNextValid() {
311 while (this->I != End && !Pred(*this->I))
312 BaseT::operator++();
313 }
314
315 // Construct the iterator. The begin iterator needs to know where the end
316 // is, so that it can properly stop when it gets there. The end iterator only
317 // needs the predicate to support bidirectional iteration.
318 filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End,
319 PredicateT Pred)
320 : BaseT(Begin), End(End), Pred(Pred) {
321 findNextValid();
322 }
323
324public:
325 using BaseT::operator++;
326
327 filter_iterator_base &operator++() {
328 BaseT::operator++();
329 findNextValid();
330 return *this;
331 }
332};
333
334/// Specialization of filter_iterator_base for forward iteration only.
335template <typename WrappedIteratorT, typename PredicateT,
336 typename IterTag = std::forward_iterator_tag>
337class filter_iterator_impl
338 : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> {
339 using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>;
340
341public:
342 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
343 PredicateT Pred)
344 : BaseT(Begin, End, Pred) {}
345};
346
347/// Specialization of filter_iterator_base for bidirectional iteration.
348template <typename WrappedIteratorT, typename PredicateT>
349class filter_iterator_impl<WrappedIteratorT, PredicateT,
350 std::bidirectional_iterator_tag>
351 : public filter_iterator_base<WrappedIteratorT, PredicateT,
352 std::bidirectional_iterator_tag> {
353 using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT,
354 std::bidirectional_iterator_tag>;
355 void findPrevValid() {
356 while (!this->Pred(*this->I))
357 BaseT::operator--();
358 }
359
360public:
361 using BaseT::operator--;
362
363 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
364 PredicateT Pred)
365 : BaseT(Begin, End, Pred) {}
366
367 filter_iterator_impl &operator--() {
368 BaseT::operator--();
369 findPrevValid();
370 return *this;
371 }
372};
373
374namespace detail {
375
376template <bool is_bidirectional> struct fwd_or_bidi_tag_impl {
377 using type = std::forward_iterator_tag;
378};
379
380template <> struct fwd_or_bidi_tag_impl<true> {
381 using type = std::bidirectional_iterator_tag;
382};
383
384/// Helper which sets its type member to forward_iterator_tag if the category
385/// of \p IterT does not derive from bidirectional_iterator_tag, and to
386/// bidirectional_iterator_tag otherwise.
387template <typename IterT> struct fwd_or_bidi_tag {
388 using type = typename fwd_or_bidi_tag_impl<std::is_base_of<
389 std::bidirectional_iterator_tag,
390 typename std::iterator_traits<IterT>::iterator_category>::value>::type;
391};
392
393} // namespace detail
394
395/// Defines filter_iterator to a suitable specialization of
396/// filter_iterator_impl, based on the underlying iterator's category.
397template <typename WrappedIteratorT, typename PredicateT>
398using filter_iterator = filter_iterator_impl<
399 WrappedIteratorT, PredicateT,
400 typename detail::fwd_or_bidi_tag<WrappedIteratorT>::type>;
401
402/// Convenience function that takes a range of elements and a predicate,
403/// and return a new filter_iterator range.
404///
405/// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
406/// lifetime of that temporary is not kept by the returned range object, and the
407/// temporary is going to be dropped on the floor after the make_iterator_range
408/// full expression that contains this function call.
409template <typename RangeT, typename PredicateT>
410iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
411make_filter_range(RangeT &&Range, PredicateT Pred) {
412 using FilterIteratorT =
413 filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
414 return make_range(
415 FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
416 std::end(std::forward<RangeT>(Range)), Pred),
417 FilterIteratorT(std::end(std::forward<RangeT>(Range)),
418 std::end(std::forward<RangeT>(Range)), Pred));
419}
420
421// forward declarations required by zip_shortest/zip_first
422template <typename R, typename UnaryPredicate>
423bool all_of(R &&range, UnaryPredicate P);
424
425template <size_t... I> struct index_sequence;
426
427template <class... Ts> struct index_sequence_for;
428
429namespace detail {
430
431using std::declval;
432
433// We have to alias this since inlining the actual type at the usage site
434// in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
435template<typename... Iters> struct ZipTupleType {
436 using type = std::tuple<decltype(*declval<Iters>())...>;
437};
438
439template <typename ZipType, typename... Iters>
440using zip_traits = iterator_facade_base<
441 ZipType, typename std::common_type<std::bidirectional_iterator_tag,
442 typename std::iterator_traits<
443 Iters>::iterator_category...>::type,
444 // ^ TODO: Implement random access methods.
445 typename ZipTupleType<Iters...>::type,
446 typename std::iterator_traits<typename std::tuple_element<
447 0, std::tuple<Iters...>>::type>::difference_type,
448 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
449 // inner iterators have the same difference_type. It would fail if, for
450 // instance, the second field's difference_type were non-numeric while the
451 // first is.
452 typename ZipTupleType<Iters...>::type *,
453 typename ZipTupleType<Iters...>::type>;
454
455template <typename ZipType, typename... Iters>
456struct zip_common : public zip_traits<ZipType, Iters...> {
457 using Base = zip_traits<ZipType, Iters...>;
458 using value_type = typename Base::value_type;
459
460 std::tuple<Iters...> iterators;
461
462protected:
463 template <size_t... Ns> value_type deref(index_sequence<Ns...>) const {
464 return value_type(*std::get<Ns>(iterators)...);
465 }
466
467 template <size_t... Ns>
468 decltype(iterators) tup_inc(index_sequence<Ns...>) const {
469 return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
470 }
471
472 template <size_t... Ns>
473 decltype(iterators) tup_dec(index_sequence<Ns...>) const {
474 return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
475 }
476
477public:
478 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
479
480 value_type operator*() { return deref(index_sequence_for<Iters...>{}); }
481
482 const value_type operator*() const {
483 return deref(index_sequence_for<Iters...>{});
484 }
485
486 ZipType &operator++() {
487 iterators = tup_inc(index_sequence_for<Iters...>{});
488 return *reinterpret_cast<ZipType *>(this);
489 }
490
491 ZipType &operator--() {
492 static_assert(Base::IsBidirectional,
493 "All inner iterators must be at least bidirectional.");
494 iterators = tup_dec(index_sequence_for<Iters...>{});
495 return *reinterpret_cast<ZipType *>(this);
496 }
497};
498
499template <typename... Iters>
500struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
501 using Base = zip_common<zip_first<Iters...>, Iters...>;
502
503 bool operator==(const zip_first<Iters...> &other) const {
504 return std::get<0>(this->iterators) == std::get<0>(other.iterators);
505 }
506
507 zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
508};
509
510template <typename... Iters>
511class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
512 template <size_t... Ns>
513 bool test(const zip_shortest<Iters...> &other, index_sequence<Ns...>) const {
514 return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
515 std::get<Ns>(other.iterators)...},
516 identity<bool>{});
517 }
518
519public:
520 using Base = zip_common<zip_shortest<Iters...>, Iters...>;
521
522 zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
523
524 bool operator==(const zip_shortest<Iters...> &other) const {
525 return !test(other, index_sequence_for<Iters...>{});
526 }
527};
528
529template <template <typename...> class ItType, typename... Args> class zippy {
530public:
531 using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>;
532 using iterator_category = typename iterator::iterator_category;
533 using value_type = typename iterator::value_type;
534 using difference_type = typename iterator::difference_type;
535 using pointer = typename iterator::pointer;
536 using reference = typename iterator::reference;
537
538private:
539 std::tuple<Args...> ts;
540
541 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const {
542 return iterator(std::begin(std::get<Ns>(ts))...);
543 }
544 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const {
545 return iterator(std::end(std::get<Ns>(ts))...);
546 }
547
548public:
549 zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
550
551 iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); }
552 iterator end() const { return end_impl(index_sequence_for<Args...>{}); }
553};
554
555} // end namespace detail
556
557/// zip iterator for two or more iteratable types.
558template <typename T, typename U, typename... Args>
559detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
560 Args &&... args) {
561 return detail::zippy<detail::zip_shortest, T, U, Args...>(
562 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
563}
564
565/// zip iterator that, for the sake of efficiency, assumes the first iteratee to
566/// be the shortest.
567template <typename T, typename U, typename... Args>
568detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
569 Args &&... args) {
570 return detail::zippy<detail::zip_first, T, U, Args...>(
571 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
572}
573
574/// Iterator wrapper that concatenates sequences together.
575///
576/// This can concatenate different iterators, even with different types, into
577/// a single iterator provided the value types of all the concatenated
578/// iterators expose `reference` and `pointer` types that can be converted to
579/// `ValueT &` and `ValueT *` respectively. It doesn't support more
580/// interesting/customized pointer or reference types.
581///
582/// Currently this only supports forward or higher iterator categories as
583/// inputs and always exposes a forward iterator interface.
584template <typename ValueT, typename... IterTs>
585class concat_iterator
586 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
587 std::forward_iterator_tag, ValueT> {
588 using BaseT = typename concat_iterator::iterator_facade_base;
589
590 /// We store both the current and end iterators for each concatenated
591 /// sequence in a tuple of pairs.
592 ///
593 /// Note that something like iterator_range seems nice at first here, but the
594 /// range properties are of little benefit and end up getting in the way
595 /// because we need to do mutation on the current iterators.
596 std::tuple<std::pair<IterTs, IterTs>...> IterPairs;
597
598 /// Attempts to increment a specific iterator.
599 ///
600 /// Returns true if it was able to increment the iterator. Returns false if
601 /// the iterator is already at the end iterator.
602 template <size_t Index> bool incrementHelper() {
603 auto &IterPair = std::get<Index>(IterPairs);
604 if (IterPair.first == IterPair.second)
605 return false;
606
607 ++IterPair.first;
608 return true;
609 }
610
611 /// Increments the first non-end iterator.
612 ///
613 /// It is an error to call this with all iterators at the end.
614 template <size_t... Ns> void increment(index_sequence<Ns...>) {
615 // Build a sequence of functions to increment each iterator if possible.
616 bool (concat_iterator::*IncrementHelperFns[])() = {
617 &concat_iterator::incrementHelper<Ns>...};
618
619 // Loop over them, and stop as soon as we succeed at incrementing one.
620 for (auto &IncrementHelperFn : IncrementHelperFns)
621 if ((this->*IncrementHelperFn)())
622 return;
623
624 llvm_unreachable("Attempted to increment an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to increment an end concat iterator!"
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/ADT/STLExtras.h"
, 624)
;
625 }
626
627 /// Returns null if the specified iterator is at the end. Otherwise,
628 /// dereferences the iterator and returns the address of the resulting
629 /// reference.
630 template <size_t Index> ValueT *getHelper() const {
631 auto &IterPair = std::get<Index>(IterPairs);
632 if (IterPair.first == IterPair.second)
633 return nullptr;
634
635 return &*IterPair.first;
636 }
637
638 /// Finds the first non-end iterator, dereferences, and returns the resulting
639 /// reference.
640 ///
641 /// It is an error to call this with all iterators at the end.
642 template <size_t... Ns> ValueT &get(index_sequence<Ns...>) const {
643 // Build a sequence of functions to get from iterator if possible.
644 ValueT *(concat_iterator::*GetHelperFns[])() const = {
645 &concat_iterator::getHelper<Ns>...};
646
647 // Loop over them, and return the first result we find.
648 for (auto &GetHelperFn : GetHelperFns)
649 if (ValueT *P = (this->*GetHelperFn)())
650 return *P;
651
652 llvm_unreachable("Attempted to get a pointer from an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to get a pointer from an end concat iterator!"
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/ADT/STLExtras.h"
, 652)
;
653 }
654
655public:
656 /// Constructs an iterator from a squence of ranges.
657 ///
658 /// We need the full range to know how to switch between each of the
659 /// iterators.
660 template <typename... RangeTs>
661 explicit concat_iterator(RangeTs &&... Ranges)
662 : IterPairs({std::begin(Ranges), std::end(Ranges)}...) {}
663
664 using BaseT::operator++;
665
666 concat_iterator &operator++() {
667 increment(index_sequence_for<IterTs...>());
668 return *this;
669 }
670
671 ValueT &operator*() const { return get(index_sequence_for<IterTs...>()); }
672
673 bool operator==(const concat_iterator &RHS) const {
674 return IterPairs == RHS.IterPairs;
675 }
676};
677
678namespace detail {
679
680/// Helper to store a sequence of ranges being concatenated and access them.
681///
682/// This is designed to facilitate providing actual storage when temporaries
683/// are passed into the constructor such that we can use it as part of range
684/// based for loops.
685template <typename ValueT, typename... RangeTs> class concat_range {
686public:
687 using iterator =
688 concat_iterator<ValueT,
689 decltype(std::begin(std::declval<RangeTs &>()))...>;
690
691private:
692 std::tuple<RangeTs...> Ranges;
693
694 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) {
695 return iterator(std::get<Ns>(Ranges)...);
696 }
697 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) {
698 return iterator(make_range(std::end(std::get<Ns>(Ranges)),
699 std::end(std::get<Ns>(Ranges)))...);
700 }
701
702public:
703 concat_range(RangeTs &&... Ranges)
704 : Ranges(std::forward<RangeTs>(Ranges)...) {}
705
706 iterator begin() { return begin_impl(index_sequence_for<RangeTs...>{}); }
707 iterator end() { return end_impl(index_sequence_for<RangeTs...>{}); }
708};
709
710} // end namespace detail
711
712/// Concatenated range across two or more ranges.
713///
714/// The desired value type must be explicitly specified.
715template <typename ValueT, typename... RangeTs>
716detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
717 static_assert(sizeof...(RangeTs) > 1,
718 "Need more than one range to concatenate!");
719 return detail::concat_range<ValueT, RangeTs...>(
720 std::forward<RangeTs>(Ranges)...);
721}
722
723//===----------------------------------------------------------------------===//
724// Extra additions to <utility>
725//===----------------------------------------------------------------------===//
726
727/// Function object to check whether the first component of a std::pair
728/// compares less than the first component of another std::pair.
729struct less_first {
730 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
731 return lhs.first < rhs.first;
732 }
733};
734
735/// Function object to check whether the second component of a std::pair
736/// compares less than the second component of another std::pair.
737struct less_second {
738 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
739 return lhs.second < rhs.second;
740 }
741};
742
743// A subset of N3658. More stuff can be added as-needed.
744
745/// Represents a compile-time sequence of integers.
746template <class T, T... I> struct integer_sequence {
747 using value_type = T;
748
749 static constexpr size_t size() { return sizeof...(I); }
750};
751
752/// Alias for the common case of a sequence of size_ts.
753template <size_t... I>
754struct index_sequence : integer_sequence<std::size_t, I...> {};
755
756template <std::size_t N, std::size_t... I>
757struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
758template <std::size_t... I>
759struct build_index_impl<0, I...> : index_sequence<I...> {};
760
761/// Creates a compile-time integer sequence for a parameter pack.
762template <class... Ts>
763struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
764
765/// Utility type to build an inheritance chain that makes it easy to rank
766/// overload candidates.
767template <int N> struct rank : rank<N - 1> {};
768template <> struct rank<0> {};
769
770/// traits class for checking whether type T is one of any of the given
771/// types in the variadic list.
772template <typename T, typename... Ts> struct is_one_of {
773 static const bool value = false;
774};
775
776template <typename T, typename U, typename... Ts>
777struct is_one_of<T, U, Ts...> {
778 static const bool value =
779 std::is_same<T, U>::value || is_one_of<T, Ts...>::value;
780};
781
782/// traits class for checking whether type T is a base class for all
783/// the given types in the variadic list.
784template <typename T, typename... Ts> struct are_base_of {
785 static const bool value = true;
786};
787
788template <typename T, typename U, typename... Ts>
789struct are_base_of<T, U, Ts...> {
790 static const bool value =
791 std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value;
792};
793
794//===----------------------------------------------------------------------===//
795// Extra additions for arrays
796//===----------------------------------------------------------------------===//
797
798/// Find the length of an array.
799template <class T, std::size_t N>
800constexpr inline size_t array_lengthof(T (&)[N]) {
801 return N;
802}
803
804/// Adapt std::less<T> for array_pod_sort.
805template<typename T>
806inline int array_pod_sort_comparator(const void *P1, const void *P2) {
807 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
808 *reinterpret_cast<const T*>(P2)))
809 return -1;
810 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
811 *reinterpret_cast<const T*>(P1)))
812 return 1;
813 return 0;
814}
815
816/// get_array_pod_sort_comparator - This is an internal helper function used to
817/// get type deduction of T right.
818template<typename T>
819inline int (*get_array_pod_sort_comparator(const T &))
820 (const void*, const void*) {
821 return array_pod_sort_comparator<T>;
822}
823
824/// array_pod_sort - This sorts an array with the specified start and end
825/// extent. This is just like std::sort, except that it calls qsort instead of
826/// using an inlined template. qsort is slightly slower than std::sort, but
827/// most sorts are not performance critical in LLVM and std::sort has to be
828/// template instantiated for each type, leading to significant measured code
829/// bloat. This function should generally be used instead of std::sort where
830/// possible.
831///
832/// This function assumes that you have simple POD-like types that can be
833/// compared with std::less and can be moved with memcpy. If this isn't true,
834/// you should use std::sort.
835///
836/// NOTE: If qsort_r were portable, we could allow a custom comparator and
837/// default to std::less.
838template<class IteratorTy>
839inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
840 // Don't inefficiently call qsort with one element or trigger undefined
841 // behavior with an empty sequence.
842 auto NElts = End - Start;
843 if (NElts <= 1) return;
844#ifdef EXPENSIVE_CHECKS
845 std::mt19937 Generator(std::random_device{}());
846 std::shuffle(Start, End, Generator);
847#endif
848 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
849}
850
851template <class IteratorTy>
852inline void array_pod_sort(
853 IteratorTy Start, IteratorTy End,
854 int (*Compare)(
855 const typename std::iterator_traits<IteratorTy>::value_type *,
856 const typename std::iterator_traits<IteratorTy>::value_type *)) {
857 // Don't inefficiently call qsort with one element or trigger undefined
858 // behavior with an empty sequence.
859 auto NElts = End - Start;
860 if (NElts <= 1) return;
861#ifdef EXPENSIVE_CHECKS
862 std::mt19937 Generator(std::random_device{}());
863 std::shuffle(Start, End, Generator);
864#endif
865 qsort(&*Start, NElts, sizeof(*Start),
866 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
867}
868
869// Provide wrappers to std::sort which shuffle the elements before sorting
870// to help uncover non-deterministic behavior (PR35135).
871template <typename IteratorTy>
872inline void sort(IteratorTy Start, IteratorTy End) {
873#ifdef EXPENSIVE_CHECKS
874 std::mt19937 Generator(std::random_device{}());
875 std::shuffle(Start, End, Generator);
876#endif
877 std::sort(Start, End);
878}
879
880template <typename IteratorTy, typename Compare>
881inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
882#ifdef EXPENSIVE_CHECKS
883 std::mt19937 Generator(std::random_device{}());
884 std::shuffle(Start, End, Generator);
885#endif
886 std::sort(Start, End, Comp);
887}
888
889//===----------------------------------------------------------------------===//
890// Extra additions to <algorithm>
891//===----------------------------------------------------------------------===//
892
893/// For a container of pointers, deletes the pointers and then clears the
894/// container.
895template<typename Container>
896void DeleteContainerPointers(Container &C) {
897 for (auto V : C)
898 delete V;
899 C.clear();
900}
901
902/// In a container of pairs (usually a map) whose second element is a pointer,
903/// deletes the second elements and then clears the container.
904template<typename Container>
905void DeleteContainerSeconds(Container &C) {
906 for (auto &V : C)
907 delete V.second;
908 C.clear();
909}
910
911/// Provide wrappers to std::for_each which take ranges instead of having to
912/// pass begin/end explicitly.
913template <typename R, typename UnaryPredicate>
914UnaryPredicate for_each(R &&Range, UnaryPredicate P) {
915 return std::for_each(adl_begin(Range), adl_end(Range), P);
916}
917
918/// Provide wrappers to std::all_of which take ranges instead of having to pass
919/// begin/end explicitly.
920template <typename R, typename UnaryPredicate>
921bool all_of(R &&Range, UnaryPredicate P) {
922 return std::all_of(adl_begin(Range), adl_end(Range), P);
923}
924
925/// Provide wrappers to std::any_of which take ranges instead of having to pass
926/// begin/end explicitly.
927template <typename R, typename UnaryPredicate>
928bool any_of(R &&Range, UnaryPredicate P) {
929 return std::any_of(adl_begin(Range), adl_end(Range), P);
930}
931
932/// Provide wrappers to std::none_of which take ranges instead of having to pass
933/// begin/end explicitly.
934template <typename R, typename UnaryPredicate>
935bool none_of(R &&Range, UnaryPredicate P) {
936 return std::none_of(adl_begin(Range), adl_end(Range), P);
937}
938
939/// Provide wrappers to std::find which take ranges instead of having to pass
940/// begin/end explicitly.
941template <typename R, typename T>
942auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range)) {
943 return std::find(adl_begin(Range), adl_end(Range), Val);
944}
945
946/// Provide wrappers to std::find_if which take ranges instead of having to pass
947/// begin/end explicitly.
948template <typename R, typename UnaryPredicate>
949auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
950 return std::find_if(adl_begin(Range), adl_end(Range), P);
951}
952
953template <typename R, typename UnaryPredicate>
954auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
955 return std::find_if_not(adl_begin(Range), adl_end(Range), P);
956}
957
958/// Provide wrappers to std::remove_if which take ranges instead of having to
959/// pass begin/end explicitly.
960template <typename R, typename UnaryPredicate>
961auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
962 return std::remove_if(adl_begin(Range), adl_end(Range), P);
963}
964
965/// Provide wrappers to std::copy_if which take ranges instead of having to
966/// pass begin/end explicitly.
967template <typename R, typename OutputIt, typename UnaryPredicate>
968OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
969 return std::copy_if(adl_begin(Range), adl_end(Range), Out, P);
970}
971
972template <typename R, typename OutputIt>
973OutputIt copy(R &&Range, OutputIt Out) {
974 return std::copy(adl_begin(Range), adl_end(Range), Out);
975}
976
977/// Wrapper function around std::find to detect if an element exists
978/// in a container.
979template <typename R, typename E>
980bool is_contained(R &&Range, const E &Element) {
981 return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range);
982}
983
984/// Wrapper function around std::count to count the number of times an element
985/// \p Element occurs in the given range \p Range.
986template <typename R, typename E>
987auto count(R &&Range, const E &Element) ->
988 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
989 return std::count(adl_begin(Range), adl_end(Range), Element);
990}
991
992/// Wrapper function around std::count_if to count the number of times an
993/// element satisfying a given predicate occurs in a range.
994template <typename R, typename UnaryPredicate>
995auto count_if(R &&Range, UnaryPredicate P) ->
996 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
997 return std::count_if(adl_begin(Range), adl_end(Range), P);
998}
999
1000/// Wrapper function around std::transform to apply a function to a range and
1001/// store the result elsewhere.
1002template <typename R, typename OutputIt, typename UnaryPredicate>
1003OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) {
1004 return std::transform(adl_begin(Range), adl_end(Range), d_first, P);
1005}
1006
1007/// Provide wrappers to std::partition which take ranges instead of having to
1008/// pass begin/end explicitly.
1009template <typename R, typename UnaryPredicate>
1010auto partition(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1011 return std::partition(adl_begin(Range), adl_end(Range), P);
1012}
1013
1014/// Provide wrappers to std::lower_bound which take ranges instead of having to
1015/// pass begin/end explicitly.
1016template <typename R, typename ForwardIt>
1017auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range)) {
1018 return std::lower_bound(adl_begin(Range), adl_end(Range), I);
1019}
1020
1021/// Given a range of type R, iterate the entire range and return a
1022/// SmallVector with elements of the vector. This is useful, for example,
1023/// when you want to iterate a range and then sort the results.
1024template <unsigned Size, typename R>
1025SmallVector<typename std::remove_const<detail::ValueOfRange<R>>::type, Size>
1026to_vector(R &&Range) {
1027 return {adl_begin(Range), adl_end(Range)};
1028}
1029
1030/// Provide a container algorithm similar to C++ Library Fundamentals v2's
1031/// `erase_if` which is equivalent to:
1032///
1033/// C.erase(remove_if(C, pred), C.end());
1034///
1035/// This version works for any container with an erase method call accepting
1036/// two iterators.
1037template <typename Container, typename UnaryPredicate>
1038void erase_if(Container &C, UnaryPredicate P) {
1039 C.erase(remove_if(C, P), C.end());
1040}
1041
1042/// Get the size of a range. This is a wrapper function around std::distance
1043/// which is only enabled when the operation is O(1).
1044template <typename R>
1045auto size(R &&Range, typename std::enable_if<
1046 std::is_same<typename std::iterator_traits<decltype(
1047 Range.begin())>::iterator_category,
1048 std::random_access_iterator_tag>::value,
1049 void>::type * = nullptr)
1050 -> decltype(std::distance(Range.begin(), Range.end())) {
1051 return std::distance(Range.begin(), Range.end());
1052}
1053
1054//===----------------------------------------------------------------------===//
1055// Extra additions to <memory>
1056//===----------------------------------------------------------------------===//
1057
1058// Implement make_unique according to N3656.
1059
1060/// Constructs a `new T()` with the given args and returns a
1061/// `unique_ptr<T>` which owns the object.
1062///
1063/// Example:
1064///
1065/// auto p = make_unique<int>();
1066/// auto p = make_unique<std::tuple<int, int>>(0, 1);
1067template <class T, class... Args>
1068typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
1069make_unique(Args &&... args) {
1070 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
10
Calling '~unique_ptr'
16
Returning from '~unique_ptr'
1071}
1072
1073/// Constructs a `new T[n]` with the given args and returns a
1074/// `unique_ptr<T[]>` which owns the object.
1075///
1076/// \param n size of the new array.
1077///
1078/// Example:
1079///
1080/// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
1081template <class T>
1082typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
1083 std::unique_ptr<T>>::type
1084make_unique(size_t n) {
1085 return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
1086}
1087
1088/// This function isn't used and is only here to provide better compile errors.
1089template <class T, class... Args>
1090typename std::enable_if<std::extent<T>::value != 0>::type
1091make_unique(Args &&...) = delete;
1092
1093struct FreeDeleter {
1094 void operator()(void* v) {
1095 ::free(v);
1096 }
1097};
1098
1099template<typename First, typename Second>
1100struct pair_hash {
1101 size_t operator()(const std::pair<First, Second> &P) const {
1102 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
1103 }
1104};
1105
1106/// A functor like C++14's std::less<void> in its absence.
1107struct less {
1108 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1109 return std::forward<A>(a) < std::forward<B>(b);
1110 }
1111};
1112
1113/// A functor like C++14's std::equal<void> in its absence.
1114struct equal {
1115 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1116 return std::forward<A>(a) == std::forward<B>(b);
1117 }
1118};
1119
1120/// Binary functor that adapts to any other binary functor after dereferencing
1121/// operands.
1122template <typename T> struct deref {
1123 T func;
1124
1125 // Could be further improved to cope with non-derivable functors and
1126 // non-binary functors (should be a variadic template member function
1127 // operator()).
1128 template <typename A, typename B>
1129 auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
1130 assert(lhs)(static_cast <bool> (lhs) ? void (0) : __assert_fail ("lhs"
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/ADT/STLExtras.h"
, 1130, __extension__ __PRETTY_FUNCTION__))
;
1131 assert(rhs)(static_cast <bool> (rhs) ? void (0) : __assert_fail ("rhs"
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/ADT/STLExtras.h"
, 1131, __extension__ __PRETTY_FUNCTION__))
;
1132 return func(*lhs, *rhs);
1133 }
1134};
1135
1136namespace detail {
1137
1138template <typename R> class enumerator_iter;
1139
1140template <typename R> struct result_pair {
1141 friend class enumerator_iter<R>;
1142
1143 result_pair() = default;
1144 result_pair(std::size_t Index, IterOfRange<R> Iter)
1145 : Index(Index), Iter(Iter) {}
1146
1147 result_pair<R> &operator=(const result_pair<R> &Other) {
1148 Index = Other.Index;
1149 Iter = Other.Iter;
1150 return *this;
1151 }
1152
1153 std::size_t index() const { return Index; }
1154 const ValueOfRange<R> &value() const { return *Iter; }
1155 ValueOfRange<R> &value() { return *Iter; }
1156
1157private:
1158 std::size_t Index = std::numeric_limits<std::size_t>::max();
1159 IterOfRange<R> Iter;
1160};
1161
1162template <typename R>
1163class enumerator_iter
1164 : public iterator_facade_base<
1165 enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>,
1166 typename std::iterator_traits<IterOfRange<R>>::difference_type,
1167 typename std::iterator_traits<IterOfRange<R>>::pointer,
1168 typename std::iterator_traits<IterOfRange<R>>::reference> {
1169 using result_type = result_pair<R>;
1170
1171public:
1172 explicit enumerator_iter(IterOfRange<R> EndIter)
1173 : Result(std::numeric_limits<size_t>::max(), EndIter) {}
1174
1175 enumerator_iter(std::size_t Index, IterOfRange<R> Iter)
1176 : Result(Index, Iter) {}
1177
1178 result_type &operator*() { return Result; }
1179 const result_type &operator*() const { return Result; }
1180
1181 enumerator_iter<R> &operator++() {
1182 assert(Result.Index != std::numeric_limits<size_t>::max())(static_cast <bool> (Result.Index != std::numeric_limits
<size_t>::max()) ? void (0) : __assert_fail ("Result.Index != std::numeric_limits<size_t>::max()"
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/ADT/STLExtras.h"
, 1182, __extension__ __PRETTY_FUNCTION__))
;
1183 ++Result.Iter;
1184 ++Result.Index;
1185 return *this;
1186 }
1187
1188 bool operator==(const enumerator_iter<R> &RHS) const {
1189 // Don't compare indices here, only iterators. It's possible for an end
1190 // iterator to have different indices depending on whether it was created
1191 // by calling std::end() versus incrementing a valid iterator.
1192 return Result.Iter == RHS.Result.Iter;
1193 }
1194
1195 enumerator_iter<R> &operator=(const enumerator_iter<R> &Other) {
1196 Result = Other.Result;
1197 return *this;
1198 }
1199
1200private:
1201 result_type Result;
1202};
1203
1204template <typename R> class enumerator {
1205public:
1206 explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
1207
1208 enumerator_iter<R> begin() {
1209 return enumerator_iter<R>(0, std::begin(TheRange));
1210 }
1211
1212 enumerator_iter<R> end() {
1213 return enumerator_iter<R>(std::end(TheRange));
1214 }
1215
1216private:
1217 R TheRange;
1218};
1219
1220} // end namespace detail
1221
1222/// Given an input range, returns a new range whose values are are pair (A,B)
1223/// such that A is the 0-based index of the item in the sequence, and B is
1224/// the value from the original sequence. Example:
1225///
1226/// std::vector<char> Items = {'A', 'B', 'C', 'D'};
1227/// for (auto X : enumerate(Items)) {
1228/// printf("Item %d - %c\n", X.index(), X.value());
1229/// }
1230///
1231/// Output:
1232/// Item 0 - A
1233/// Item 1 - B
1234/// Item 2 - C
1235/// Item 3 - D
1236///
1237template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
1238 return detail::enumerator<R>(std::forward<R>(TheRange));
1239}
1240
1241namespace detail {
1242
1243template <typename F, typename Tuple, std::size_t... I>
1244auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence<I...>)
1245 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) {
1246 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
1247}
1248
1249} // end namespace detail
1250
1251/// Given an input tuple (a1, a2, ..., an), pass the arguments of the
1252/// tuple variadically to f as if by calling f(a1, a2, ..., an) and
1253/// return the result.
1254template <typename F, typename Tuple>
1255auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl(
1256 std::forward<F>(f), std::forward<Tuple>(t),
1257 build_index_impl<
1258 std::tuple_size<typename std::decay<Tuple>::type>::value>{})) {
1259 using Indices = build_index_impl<
1260 std::tuple_size<typename std::decay<Tuple>::type>::value>;
1261
1262 return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
1263 Indices{});
1264}
1265
1266} // end namespace llvm
1267
1268#endif // LLVM_ADT_STLEXTRAS_H

/usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/unique_ptr.h

1// unique_ptr implementation -*- C++ -*-
2
3// Copyright (C) 2008-2018 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file bits/unique_ptr.h
26 * This is an internal header file, included by other library headers.
27 * Do not attempt to use it directly. @headername{memory}
28 */
29
30#ifndef _UNIQUE_PTR_H1
31#define _UNIQUE_PTR_H1 1
32
33#include <bits/c++config.h>
34#include <debug/assertions.h>
35#include <type_traits>
36#include <utility>
37#include <tuple>
38#include <bits/stl_function.h>
39#include <bits/functional_hash.h>
40
41namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
42{
43_GLIBCXX_BEGIN_NAMESPACE_VERSION
44
45 /**
46 * @addtogroup pointer_abstractions
47 * @{
48 */
49
50#if _GLIBCXX_USE_DEPRECATED1
51#pragma GCC diagnostic push
52#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
53 template<typename> class auto_ptr;
54#pragma GCC diagnostic pop
55#endif
56
57 /// Primary template of default_delete, used by unique_ptr
58 template<typename _Tp>
59 struct default_delete
60 {
61 /// Default constructor
62 constexpr default_delete() noexcept = default;
63
64 /** @brief Converting constructor.
65 *
66 * Allows conversion from a deleter for arrays of another type, @p _Up,
67 * only if @p _Up* is convertible to @p _Tp*.
68 */
69 template<typename _Up, typename = typename
70 enable_if<is_convertible<_Up*, _Tp*>::value>::type>
71 default_delete(const default_delete<_Up>&) noexcept { }
72
73 /// Calls @c delete @p __ptr
74 void
75 operator()(_Tp* __ptr) const
76 {
77 static_assert(!is_void<_Tp>::value,
78 "can't delete pointer to incomplete type");
79 static_assert(sizeof(_Tp)>0,
80 "can't delete pointer to incomplete type");
81 delete __ptr;
14
Memory is released
82 }
83 };
84
85 // _GLIBCXX_RESOLVE_LIB_DEFECTS
86 // DR 740 - omit specialization for array objects with a compile time length
87 /// Specialization for arrays, default_delete.
88 template<typename _Tp>
89 struct default_delete<_Tp[]>
90 {
91 public:
92 /// Default constructor
93 constexpr default_delete() noexcept = default;
94
95 /** @brief Converting constructor.
96 *
97 * Allows conversion from a deleter for arrays of another type, such as
98 * a const-qualified version of @p _Tp.
99 *
100 * Conversions from types derived from @c _Tp are not allowed because
101 * it is unsafe to @c delete[] an array of derived types through a
102 * pointer to the base type.
103 */
104 template<typename _Up, typename = typename
105 enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value>::type>
106 default_delete(const default_delete<_Up[]>&) noexcept { }
107
108 /// Calls @c delete[] @p __ptr
109 template<typename _Up>
110 typename enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value>::type
111 operator()(_Up* __ptr) const
112 {
113 static_assert(sizeof(_Tp)>0,
114 "can't delete pointer to incomplete type");
115 delete [] __ptr;
116 }
117 };
118
119 template <typename _Tp, typename _Dp>
120 class __uniq_ptr_impl
121 {
122 template <typename _Up, typename _Ep, typename = void>
123 struct _Ptr
124 {
125 using type = _Up*;
126 };
127
128 template <typename _Up, typename _Ep>
129 struct
130 _Ptr<_Up, _Ep, __void_t<typename remove_reference<_Ep>::type::pointer>>
131 {
132 using type = typename remove_reference<_Ep>::type::pointer;
133 };
134
135 public:
136 using _DeleterConstraint = enable_if<
137 __and_<__not_<is_pointer<_Dp>>,
138 is_default_constructible<_Dp>>::value>;
139
140 using pointer = typename _Ptr<_Tp, _Dp>::type;
141
142 __uniq_ptr_impl() = default;
143 __uniq_ptr_impl(pointer __p) : _M_t() { _M_ptr() = __p; }
144
145 template<typename _Del>
146 __uniq_ptr_impl(pointer __p, _Del&& __d)
147 : _M_t(__p, std::forward<_Del>(__d)) { }
148
149 pointer& _M_ptr() { return std::get<0>(_M_t); }
150 pointer _M_ptr() const { return std::get<0>(_M_t); }
151 _Dp& _M_deleter() { return std::get<1>(_M_t); }
152 const _Dp& _M_deleter() const { return std::get<1>(_M_t); }
153
154 private:
155 tuple<pointer, _Dp> _M_t;
156 };
157
158 /// 20.7.1.2 unique_ptr for single objects.
159 template <typename _Tp, typename _Dp = default_delete<_Tp>>
160 class unique_ptr
161 {
162 template <class _Up>
163 using _DeleterConstraint =
164 typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type;
165
166 __uniq_ptr_impl<_Tp, _Dp> _M_t;
167
168 public:
169 using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer;
170 using element_type = _Tp;
171 using deleter_type = _Dp;
172
173 // helper template for detecting a safe conversion from another
174 // unique_ptr
175 template<typename _Up, typename _Ep>
176 using __safe_conversion_up = __and_<
177 is_convertible<typename unique_ptr<_Up, _Ep>::pointer, pointer>,
178 __not_<is_array<_Up>>,
179 __or_<__and_<is_reference<deleter_type>,
180 is_same<deleter_type, _Ep>>,
181 __and_<__not_<is_reference<deleter_type>>,
182 is_convertible<_Ep, deleter_type>>
183 >
184 >;
185
186 // Constructors.
187
188 /// Default constructor, creates a unique_ptr that owns nothing.
189 template <typename _Up = _Dp,
190 typename = _DeleterConstraint<_Up>>
191 constexpr unique_ptr() noexcept
192 : _M_t()
193 { }
194
195 /** Takes ownership of a pointer.
196 *
197 * @param __p A pointer to an object of @c element_type
198 *
199 * The deleter will be value-initialized.
200 */
201 template <typename _Up = _Dp,
202 typename = _DeleterConstraint<_Up>>
203 explicit
204 unique_ptr(pointer __p) noexcept
205 : _M_t(__p)
206 { }
207
208 /** Takes ownership of a pointer.
209 *
210 * @param __p A pointer to an object of @c element_type
211 * @param __d A reference to a deleter.
212 *
213 * The deleter will be initialized with @p __d
214 */
215 unique_ptr(pointer __p,
216 typename conditional<is_reference<deleter_type>::value,
217 deleter_type, const deleter_type&>::type __d) noexcept
218 : _M_t(__p, __d) { }
219
220 /** Takes ownership of a pointer.
221 *
222 * @param __p A pointer to an object of @c element_type
223 * @param __d An rvalue reference to a deleter.
224 *
225 * The deleter will be initialized with @p std::move(__d)
226 */
227 unique_ptr(pointer __p,
228 typename remove_reference<deleter_type>::type&& __d) noexcept
229 : _M_t(std::move(__p), std::move(__d))
230 { static_assert(!std::is_reference<deleter_type>::value,
231 "rvalue deleter bound to reference"); }
232
233 /// Creates a unique_ptr that owns nothing.
234 template <typename _Up = _Dp,
235 typename = _DeleterConstraint<_Up>>
236 constexpr unique_ptr(nullptr_t) noexcept : unique_ptr() { }
237
238 // Move constructors.
239
240 /// Move constructor.
241 unique_ptr(unique_ptr&& __u) noexcept
242 : _M_t(__u.release(), std::forward<deleter_type>(__u.get_deleter())) { }
243
244 /** @brief Converting constructor from another type
245 *
246 * Requires that the pointer owned by @p __u is convertible to the
247 * type of pointer owned by this object, @p __u does not own an array,
248 * and @p __u has a compatible deleter type.
249 */
250 template<typename _Up, typename _Ep, typename = _Require<
251 __safe_conversion_up<_Up, _Ep>,
252 typename conditional<is_reference<_Dp>::value,
253 is_same<_Ep, _Dp>,
254 is_convertible<_Ep, _Dp>>::type>>
255 unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept
256 : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter()))
257 { }
258
259#if _GLIBCXX_USE_DEPRECATED1
260#pragma GCC diagnostic push
261#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
262 /// Converting constructor from @c auto_ptr
263 template<typename _Up, typename = _Require<
264 is_convertible<_Up*, _Tp*>, is_same<_Dp, default_delete<_Tp>>>>
265 unique_ptr(auto_ptr<_Up>&& __u) noexcept;
266#pragma GCC diagnostic pop
267#endif
268
269 /// Destructor, invokes the deleter if the stored pointer is not null.
270 ~unique_ptr() noexcept
271 {
272 auto& __ptr = _M_t._M_ptr();
273 if (__ptr != nullptr)
11
Assuming the condition is true
12
Taking true branch
274 get_deleter()(__ptr);
13
Calling 'default_delete::operator()'
15
Returning; memory was released via 2nd parameter
275 __ptr = pointer();
276 }
277
278 // Assignment.
279
280 /** @brief Move assignment operator.
281 *
282 * @param __u The object to transfer ownership from.
283 *
284 * Invokes the deleter first if this object owns a pointer.
285 */
286 unique_ptr&
287 operator=(unique_ptr&& __u) noexcept
288 {
289 reset(__u.release());
290 get_deleter() = std::forward<deleter_type>(__u.get_deleter());
291 return *this;
292 }
293
294 /** @brief Assignment from another type.
295 *
296 * @param __u The object to transfer ownership from, which owns a
297 * convertible pointer to a non-array object.
298 *
299 * Invokes the deleter first if this object owns a pointer.
300 */
301 template<typename _Up, typename _Ep>
302 typename enable_if< __and_<
303 __safe_conversion_up<_Up, _Ep>,
304 is_assignable<deleter_type&, _Ep&&>
305 >::value,
306 unique_ptr&>::type
307 operator=(unique_ptr<_Up, _Ep>&& __u) noexcept
308 {
309 reset(__u.release());
310 get_deleter() = std::forward<_Ep>(__u.get_deleter());
311 return *this;
312 }
313
314 /// Reset the %unique_ptr to empty, invoking the deleter if necessary.
315 unique_ptr&
316 operator=(nullptr_t) noexcept
317 {
318 reset();
319 return *this;
320 }
321
322 // Observers.
323
324 /// Dereference the stored pointer.
325 typename add_lvalue_reference<element_type>::type
326 operator*() const
327 {
328 __glibcxx_assert(get() != pointer());
329 return *get();
330 }
331
332 /// Return the stored pointer.
333 pointer
334 operator->() const noexcept
335 {
336 _GLIBCXX_DEBUG_PEDASSERT(get() != pointer());
337 return get();
338 }
339
340 /// Return the stored pointer.
341 pointer
342 get() const noexcept
343 { return _M_t._M_ptr(); }
344
345 /// Return a reference to the stored deleter.
346 deleter_type&
347 get_deleter() noexcept
348 { return _M_t._M_deleter(); }
349
350 /// Return a reference to the stored deleter.
351 const deleter_type&
352 get_deleter() const noexcept
353 { return _M_t._M_deleter(); }
354
355 /// Return @c true if the stored pointer is not null.
356 explicit operator bool() const noexcept
357 { return get() == pointer() ? false : true; }
358
359 // Modifiers.
360
361 /// Release ownership of any stored pointer.
362 pointer
363 release() noexcept
364 {
365 pointer __p = get();
366 _M_t._M_ptr() = pointer();
367 return __p;
368 }
369
370 /** @brief Replace the stored pointer.
371 *
372 * @param __p The new pointer to store.
373 *
374 * The deleter will be invoked if a pointer is already owned.
375 */
376 void
377 reset(pointer __p = pointer()) noexcept
378 {
379 using std::swap;
380 swap(_M_t._M_ptr(), __p);
381 if (__p != pointer())
382 get_deleter()(__p);
383 }
384
385 /// Exchange the pointer and deleter with another object.
386 void
387 swap(unique_ptr& __u) noexcept
388 {
389 using std::swap;
390 swap(_M_t, __u._M_t);
391 }
392
393 // Disable copy from lvalue.
394 unique_ptr(const unique_ptr&) = delete;
395 unique_ptr& operator=(const unique_ptr&) = delete;
396 };
397
398 /// 20.7.1.3 unique_ptr for array objects with a runtime length
399 // [unique.ptr.runtime]
400 // _GLIBCXX_RESOLVE_LIB_DEFECTS
401 // DR 740 - omit specialization for array objects with a compile time length
402 template<typename _Tp, typename _Dp>
403 class unique_ptr<_Tp[], _Dp>
404 {
405 template <typename _Up>
406 using _DeleterConstraint =
407 typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type;
408
409 __uniq_ptr_impl<_Tp, _Dp> _M_t;
410
411 template<typename _Up>
412 using __remove_cv = typename remove_cv<_Up>::type;
413
414 // like is_base_of<_Tp, _Up> but false if unqualified types are the same
415 template<typename _Up>
416 using __is_derived_Tp
417 = __and_< is_base_of<_Tp, _Up>,
418 __not_<is_same<__remove_cv<_Tp>, __remove_cv<_Up>>> >;
419
420 public:
421 using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer;
422 using element_type = _Tp;
423 using deleter_type = _Dp;
424
425 // helper template for detecting a safe conversion from another
426 // unique_ptr
427 template<typename _Up, typename _Ep,
428 typename _Up_up = unique_ptr<_Up, _Ep>,
429 typename _Up_element_type = typename _Up_up::element_type>
430 using __safe_conversion_up = __and_<
431 is_array<_Up>,
432 is_same<pointer, element_type*>,
433 is_same<typename _Up_up::pointer, _Up_element_type*>,
434 is_convertible<_Up_element_type(*)[], element_type(*)[]>,
435 __or_<__and_<is_reference<deleter_type>, is_same<deleter_type, _Ep>>,
436 __and_<__not_<is_reference<deleter_type>>,
437 is_convertible<_Ep, deleter_type>>>
438 >;
439
440 // helper template for detecting a safe conversion from a raw pointer
441 template<typename _Up>
442 using __safe_conversion_raw = __and_<
443 __or_<__or_<is_same<_Up, pointer>,
444 is_same<_Up, nullptr_t>>,
445 __and_<is_pointer<_Up>,
446 is_same<pointer, element_type*>,
447 is_convertible<
448 typename remove_pointer<_Up>::type(*)[],
449 element_type(*)[]>
450 >
451 >
452 >;
453
454 // Constructors.
455
456 /// Default constructor, creates a unique_ptr that owns nothing.
457 template <typename _Up = _Dp,
458 typename = _DeleterConstraint<_Up>>
459 constexpr unique_ptr() noexcept
460 : _M_t()
461 { }
462
463 /** Takes ownership of a pointer.
464 *
465 * @param __p A pointer to an array of a type safely convertible
466 * to an array of @c element_type
467 *
468 * The deleter will be value-initialized.
469 */
470 template<typename _Up,
471 typename _Vp = _Dp,
472 typename = _DeleterConstraint<_Vp>,
473 typename = typename enable_if<
474 __safe_conversion_raw<_Up>::value, bool>::type>
475 explicit
476 unique_ptr(_Up __p) noexcept
477 : _M_t(__p)
478 { }
479
480 /** Takes ownership of a pointer.
481 *
482 * @param __p A pointer to an array of a type safely convertible
483 * to an array of @c element_type
484 * @param __d A reference to a deleter.
485 *
486 * The deleter will be initialized with @p __d
487 */
488 template<typename _Up,
489 typename = typename enable_if<
490 __safe_conversion_raw<_Up>::value, bool>::type>
491 unique_ptr(_Up __p,
492 typename conditional<is_reference<deleter_type>::value,
493 deleter_type, const deleter_type&>::type __d) noexcept
494 : _M_t(__p, __d) { }
495
496 /** Takes ownership of a pointer.
497 *
498 * @param __p A pointer to an array of a type safely convertible
499 * to an array of @c element_type
500 * @param __d A reference to a deleter.
501 *
502 * The deleter will be initialized with @p std::move(__d)
503 */
504 template<typename _Up,
505 typename = typename enable_if<
506 __safe_conversion_raw<_Up>::value, bool>::type>
507 unique_ptr(_Up __p, typename
508 remove_reference<deleter_type>::type&& __d) noexcept
509 : _M_t(std::move(__p), std::move(__d))
510 { static_assert(!is_reference<deleter_type>::value,
511 "rvalue deleter bound to reference"); }
512
513 /// Move constructor.
514 unique_ptr(unique_ptr&& __u) noexcept
515 : _M_t(__u.release(), std::forward<deleter_type>(__u.get_deleter())) { }
516
517 /// Creates a unique_ptr that owns nothing.
518 template <typename _Up = _Dp,
519 typename = _DeleterConstraint<_Up>>
520 constexpr unique_ptr(nullptr_t) noexcept : unique_ptr() { }
521
522 template<typename _Up, typename _Ep,
523 typename = _Require<__safe_conversion_up<_Up, _Ep>>>
524 unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept
525 : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter()))
526 { }
527
528 /// Destructor, invokes the deleter if the stored pointer is not null.
529 ~unique_ptr()
530 {
531 auto& __ptr = _M_t._M_ptr();
532 if (__ptr != nullptr)
533 get_deleter()(__ptr);
534 __ptr = pointer();
535 }
536
537 // Assignment.
538
539 /** @brief Move assignment operator.
540 *
541 * @param __u The object to transfer ownership from.
542 *
543 * Invokes the deleter first if this object owns a pointer.
544 */
545 unique_ptr&
546 operator=(unique_ptr&& __u) noexcept
547 {
548 reset(__u.release());
549 get_deleter() = std::forward<deleter_type>(__u.get_deleter());
550 return *this;
551 }
552
553 /** @brief Assignment from another type.
554 *
555 * @param __u The object to transfer ownership from, which owns a
556 * convertible pointer to an array object.
557 *
558 * Invokes the deleter first if this object owns a pointer.
559 */
560 template<typename _Up, typename _Ep>
561 typename
562 enable_if<__and_<__safe_conversion_up<_Up, _Ep>,
563 is_assignable<deleter_type&, _Ep&&>
564 >::value,
565 unique_ptr&>::type
566 operator=(unique_ptr<_Up, _Ep>&& __u) noexcept
567 {
568 reset(__u.release());
569 get_deleter() = std::forward<_Ep>(__u.get_deleter());
570 return *this;
571 }
572
573 /// Reset the %unique_ptr to empty, invoking the deleter if necessary.
574 unique_ptr&
575 operator=(nullptr_t) noexcept
576 {
577 reset();
578 return *this;
579 }
580
581 // Observers.
582
583 /// Access an element of owned array.
584 typename std::add_lvalue_reference<element_type>::type
585 operator[](size_t __i) const
586 {
587 __glibcxx_assert(get() != pointer());
588 return get()[__i];
589 }
590
591 /// Return the stored pointer.
592 pointer
593 get() const noexcept
594 { return _M_t._M_ptr(); }
595
596 /// Return a reference to the stored deleter.
597 deleter_type&
598 get_deleter() noexcept
599 { return _M_t._M_deleter(); }
600
601 /// Return a reference to the stored deleter.
602 const deleter_type&
603 get_deleter() const noexcept
604 { return _M_t._M_deleter(); }
605
606 /// Return @c true if the stored pointer is not null.
607 explicit operator bool() const noexcept
608 { return get() == pointer() ? false : true; }
609
610 // Modifiers.
611
612 /// Release ownership of any stored pointer.
613 pointer
614 release() noexcept
615 {
616 pointer __p = get();
617 _M_t._M_ptr() = pointer();
618 return __p;
619 }
620
621 /** @brief Replace the stored pointer.
622 *
623 * @param __p The new pointer to store.
624 *
625 * The deleter will be invoked if a pointer is already owned.
626 */
627 template <typename _Up,
628 typename = _Require<
629 __or_<is_same<_Up, pointer>,
630 __and_<is_same<pointer, element_type*>,
631 is_pointer<_Up>,
632 is_convertible<
633 typename remove_pointer<_Up>::type(*)[],
634 element_type(*)[]
635 >
636 >
637 >
638 >>
639 void
640 reset(_Up __p) noexcept
641 {
642 pointer __ptr = __p;
643 using std::swap;
644 swap(_M_t._M_ptr(), __ptr);
645 if (__ptr != nullptr)
646 get_deleter()(__ptr);
647 }
648
649 void reset(nullptr_t = nullptr) noexcept
650 {
651 reset(pointer());
652 }
653
654 /// Exchange the pointer and deleter with another object.
655 void
656 swap(unique_ptr& __u) noexcept
657 {
658 using std::swap;
659 swap(_M_t, __u._M_t);
660 }
661
662 // Disable copy from lvalue.
663 unique_ptr(const unique_ptr&) = delete;
664 unique_ptr& operator=(const unique_ptr&) = delete;
665 };
666
667 template<typename _Tp, typename _Dp>
668 inline
669#if __cplusplus201103L > 201402L || !defined(__STRICT_ANSI__1) // c++1z or gnu++11
670 // Constrained free swap overload, see p0185r1
671 typename enable_if<__is_swappable<_Dp>::value>::type
672#else
673 void
674#endif
675 swap(unique_ptr<_Tp, _Dp>& __x,
676 unique_ptr<_Tp, _Dp>& __y) noexcept
677 { __x.swap(__y); }
678
679#if __cplusplus201103L > 201402L || !defined(__STRICT_ANSI__1) // c++1z or gnu++11
680 template<typename _Tp, typename _Dp>
681 typename enable_if<!__is_swappable<_Dp>::value>::type
682 swap(unique_ptr<_Tp, _Dp>&,
683 unique_ptr<_Tp, _Dp>&) = delete;
684#endif
685
686 template<typename _Tp, typename _Dp,
687 typename _Up, typename _Ep>
688 inline bool
689 operator==(const unique_ptr<_Tp, _Dp>& __x,
690 const unique_ptr<_Up, _Ep>& __y)
691 { return __x.get() == __y.get(); }
692
693 template<typename _Tp, typename _Dp>
694 inline bool
695 operator==(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept
696 { return !__x; }
697
698 template<typename _Tp, typename _Dp>
699 inline bool
700 operator==(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept
701 { return !__x; }
702
703 template<typename _Tp, typename _Dp,
704 typename _Up, typename _Ep>
705 inline bool
706 operator!=(const unique_ptr<_Tp, _Dp>& __x,
707 const unique_ptr<_Up, _Ep>& __y)
708 { return __x.get() != __y.get(); }
709
710 template<typename _Tp, typename _Dp>
711 inline bool
712 operator!=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept
713 { return (bool)__x; }
714
715 template<typename _Tp, typename _Dp>
716 inline bool
717 operator!=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept
718 { return (bool)__x; }
719
720 template<typename _Tp, typename _Dp,
721 typename _Up, typename _Ep>
722 inline bool
723 operator<(const unique_ptr<_Tp, _Dp>& __x,
724 const unique_ptr<_Up, _Ep>& __y)
725 {
726 typedef typename
727 std::common_type<typename unique_ptr<_Tp, _Dp>::pointer,
728 typename unique_ptr<_Up, _Ep>::pointer>::type _CT;
729 return std::less<_CT>()(__x.get(), __y.get());
730 }
731
732 template<typename _Tp, typename _Dp>
733 inline bool
734 operator<(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
735 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(__x.get(),
736 nullptr); }
737
738 template<typename _Tp, typename _Dp>
739 inline bool
740 operator<(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
741 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(nullptr,
742 __x.get()); }
743
744 template<typename _Tp, typename _Dp,
745 typename _Up, typename _Ep>
746 inline bool
747 operator<=(const unique_ptr<_Tp, _Dp>& __x,
748 const unique_ptr<_Up, _Ep>& __y)
749 { return !(__y < __x); }
750
751 template<typename _Tp, typename _Dp>
752 inline bool
753 operator<=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
754 { return !(nullptr < __x); }
755
756 template<typename _Tp, typename _Dp>
757 inline bool
758 operator<=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
759 { return !(__x < nullptr); }
760
761 template<typename _Tp, typename _Dp,
762 typename _Up, typename _Ep>
763 inline bool
764 operator>(const unique_ptr<_Tp, _Dp>& __x,
765 const unique_ptr<_Up, _Ep>& __y)
766 { return (__y < __x); }
767
768 template<typename _Tp, typename _Dp>
769 inline bool
770 operator>(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
771 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(nullptr,
772 __x.get()); }
773
774 template<typename _Tp, typename _Dp>
775 inline bool
776 operator>(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
777 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(__x.get(),
778 nullptr); }
779
780 template<typename _Tp, typename _Dp,
781 typename _Up, typename _Ep>
782 inline bool
783 operator>=(const unique_ptr<_Tp, _Dp>& __x,
784 const unique_ptr<_Up, _Ep>& __y)
785 { return !(__x < __y); }
786
787 template<typename _Tp, typename _Dp>
788 inline bool
789 operator>=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
790 { return !(__x < nullptr); }
791
792 template<typename _Tp, typename _Dp>
793 inline bool
794 operator>=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
795 { return !(nullptr < __x); }
796
797 /// std::hash specialization for unique_ptr.
798 template<typename _Tp, typename _Dp>
799 struct hash<unique_ptr<_Tp, _Dp>>
800 : public __hash_base<size_t, unique_ptr<_Tp, _Dp>>,
801 private __poison_hash<typename unique_ptr<_Tp, _Dp>::pointer>
802 {
803 size_t
804 operator()(const unique_ptr<_Tp, _Dp>& __u) const noexcept
805 {
806 typedef unique_ptr<_Tp, _Dp> _UP;
807 return std::hash<typename _UP::pointer>()(__u.get());
808 }
809 };
810
811#if __cplusplus201103L > 201103L
812
813#define __cpp_lib_make_unique 201304
814
815 template<typename _Tp>
816 struct _MakeUniq
817 { typedef unique_ptr<_Tp> __single_object; };
818
819 template<typename _Tp>
820 struct _MakeUniq<_Tp[]>
821 { typedef unique_ptr<_Tp[]> __array; };
822
823 template<typename _Tp, size_t _Bound>
824 struct _MakeUniq<_Tp[_Bound]>
825 { struct __invalid_type { }; };
826
827 /// std::make_unique for single objects
828 template<typename _Tp, typename... _Args>
829 inline typename _MakeUniq<_Tp>::__single_object
830 make_unique(_Args&&... __args)
831 { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
832
833 /// std::make_unique for arrays of unknown bound
834 template<typename _Tp>
835 inline typename _MakeUniq<_Tp>::__array
836 make_unique(size_t __num)
837 { return unique_ptr<_Tp>(new remove_extent_t<_Tp>[__num]()); }
838
839 /// Disable std::make_unique for arrays of known bound
840 template<typename _Tp, typename... _Args>
841 inline typename _MakeUniq<_Tp>::__invalid_type
842 make_unique(_Args&&...) = delete;
843#endif
844
845 // @} group pointer_abstractions
846
847_GLIBCXX_END_NAMESPACE_VERSION
848} // namespace
849
850#endif /* _UNIQUE_PTR_H */

/build/llvm-toolchain-snapshot-7~svn338205/tools/lld/include/lld/Core/PassManager.h

1//===- lld/Core/PassManager.h - Manage linker passes ----------------------===//
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#ifndef LLD_CORE_PASS_MANAGER_H
11#define LLD_CORE_PASS_MANAGER_H
12
13#include "lld/Common/LLVM.h"
14#include "lld/Core/Pass.h"
15#include "llvm/Support/Error.h"
16#include <memory>
17#include <vector>
18
19namespace lld {
20class SimpleFile;
21class Pass;
22
23/// Owns and runs a collection of passes.
24///
25/// This class is currently just a container for passes and a way to run them.
26///
27/// In the future this should handle timing pass runs, running parallel passes,
28/// and validate/satisfy pass dependencies.
29class PassManager {
30public:
31 void add(std::unique_ptr<Pass> pass) {
32 _passes.push_back(std::move(pass));
33 }
34
35 llvm::Error runOnFile(SimpleFile &file) {
36 for (std::unique_ptr<Pass> &pass : _passes)
37 if (llvm::Error EC = pass->perform(file))
19
Use of memory after it is freed
38 return EC;
39 return llvm::Error::success();
40 }
41
42private:
43 /// Passes in the order they should run.
44 std::vector<std::unique_ptr<Pass>> _passes;
45};
46} // end namespace lld
47
48#endif