Bug Summary

File:include/llvm/Support/Error.h
Warning:line 201, column 5
Potential leak of memory pointed to by 'Payload._M_t._M_head_impl'

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 Darwin.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -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-8/lib/clang/8.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/tools/clang/lib/Driver -I /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver -I /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn350071/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/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-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/tools/clang/lib/Driver -fdebug-prefix-map=/build/llvm-toolchain-snapshot-8~svn350071=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-12-27-042839-1215-1 -x c++ /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp

1//===--- Darwin.cpp - Darwin Tool and ToolChain Implementations -*- 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#include "Darwin.h"
11#include "Arch/ARM.h"
12#include "CommonArgs.h"
13#include "clang/Basic/AlignedAllocation.h"
14#include "clang/Basic/ObjCRuntime.h"
15#include "clang/Driver/Compilation.h"
16#include "clang/Driver/Driver.h"
17#include "clang/Driver/DriverDiagnostic.h"
18#include "clang/Driver/Options.h"
19#include "clang/Driver/SanitizerArgs.h"
20#include "llvm/ADT/StringSwitch.h"
21#include "llvm/Option/ArgList.h"
22#include "llvm/Support/Path.h"
23#include "llvm/Support/ScopedPrinter.h"
24#include "llvm/Support/TargetParser.h"
25#include "llvm/Support/VirtualFileSystem.h"
26#include <cstdlib> // ::getenv
27
28using namespace clang::driver;
29using namespace clang::driver::tools;
30using namespace clang::driver::toolchains;
31using namespace clang;
32using namespace llvm::opt;
33
34llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
35 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
36 // archs which Darwin doesn't use.
37
38 // The matching this routine does is fairly pointless, since it is neither the
39 // complete architecture list, nor a reasonable subset. The problem is that
40 // historically the driver driver accepts this and also ties its -march=
41 // handling to the architecture name, so we need to be careful before removing
42 // support for it.
43
44 // This code must be kept in sync with Clang's Darwin specific argument
45 // translation.
46
47 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
48 .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
49 .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
50 .Case("ppc64", llvm::Triple::ppc64)
51 .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
52 .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
53 llvm::Triple::x86)
54 .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
55 // This is derived from the driver driver.
56 .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
57 .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
58 .Cases("armv7s", "xscale", llvm::Triple::arm)
59 .Case("arm64", llvm::Triple::aarch64)
60 .Case("r600", llvm::Triple::r600)
61 .Case("amdgcn", llvm::Triple::amdgcn)
62 .Case("nvptx", llvm::Triple::nvptx)
63 .Case("nvptx64", llvm::Triple::nvptx64)
64 .Case("amdil", llvm::Triple::amdil)
65 .Case("spir", llvm::Triple::spir)
66 .Default(llvm::Triple::UnknownArch);
67}
68
69void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
70 const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
71 llvm::ARM::ArchKind ArchKind = llvm::ARM::parseArch(Str);
72 T.setArch(Arch);
73
74 if (Str == "x86_64h")
75 T.setArchName(Str);
76 else if (ArchKind == llvm::ARM::ArchKind::ARMV6M ||
77 ArchKind == llvm::ARM::ArchKind::ARMV7M ||
78 ArchKind == llvm::ARM::ArchKind::ARMV7EM) {
79 T.setOS(llvm::Triple::UnknownOS);
80 T.setObjectFormat(llvm::Triple::MachO);
81 }
82}
83
84void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
85 const InputInfo &Output,
86 const InputInfoList &Inputs,
87 const ArgList &Args,
88 const char *LinkingOutput) const {
89 ArgStringList CmdArgs;
90
91 assert(Inputs.size() == 1 && "Unexpected number of inputs.")((Inputs.size() == 1 && "Unexpected number of inputs."
) ? static_cast<void> (0) : __assert_fail ("Inputs.size() == 1 && \"Unexpected number of inputs.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 91, __PRETTY_FUNCTION__))
;
92 const InputInfo &Input = Inputs[0];
93
94 // Determine the original source input.
95 const Action *SourceAction = &JA;
96 while (SourceAction->getKind() != Action::InputClass) {
97 assert(!SourceAction->getInputs().empty() && "unexpected root action!")((!SourceAction->getInputs().empty() && "unexpected root action!"
) ? static_cast<void> (0) : __assert_fail ("!SourceAction->getInputs().empty() && \"unexpected root action!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 97, __PRETTY_FUNCTION__))
;
98 SourceAction = SourceAction->getInputs()[0];
99 }
100
101 // If -fno-integrated-as is used add -Q to the darwin assembler driver to make
102 // sure it runs its system assembler not clang's integrated assembler.
103 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
104 // FIXME: at run-time detect assembler capabilities or rely on version
105 // information forwarded by -target-assembler-version.
106 if (Args.hasArg(options::OPT_fno_integrated_as)) {
107 const llvm::Triple &T(getToolChain().getTriple());
108 if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
109 CmdArgs.push_back("-Q");
110 }
111
112 // Forward -g, assuming we are dealing with an actual assembly file.
113 if (SourceAction->getType() == types::TY_Asm ||
114 SourceAction->getType() == types::TY_PP_Asm) {
115 if (Args.hasArg(options::OPT_gstabs))
116 CmdArgs.push_back("--gstabs");
117 else if (Args.hasArg(options::OPT_g_Group))
118 CmdArgs.push_back("-g");
119 }
120
121 // Derived from asm spec.
122 AddMachOArch(Args, CmdArgs);
123
124 // Use -force_cpusubtype_ALL on x86 by default.
125 if (getToolChain().getArch() == llvm::Triple::x86 ||
126 getToolChain().getArch() == llvm::Triple::x86_64 ||
127 Args.hasArg(options::OPT_force__cpusubtype__ALL))
128 CmdArgs.push_back("-force_cpusubtype_ALL");
129
130 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
131 (((Args.hasArg(options::OPT_mkernel) ||
132 Args.hasArg(options::OPT_fapple_kext)) &&
133 getMachOToolChain().isKernelStatic()) ||
134 Args.hasArg(options::OPT_static)))
135 CmdArgs.push_back("-static");
136
137 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
138
139 assert(Output.isFilename() && "Unexpected lipo output.")((Output.isFilename() && "Unexpected lipo output.") ?
static_cast<void> (0) : __assert_fail ("Output.isFilename() && \"Unexpected lipo output.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 139, __PRETTY_FUNCTION__))
;
140 CmdArgs.push_back("-o");
141 CmdArgs.push_back(Output.getFilename());
142
143 assert(Input.isFilename() && "Invalid input.")((Input.isFilename() && "Invalid input.") ? static_cast
<void> (0) : __assert_fail ("Input.isFilename() && \"Invalid input.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 143, __PRETTY_FUNCTION__))
;
144 CmdArgs.push_back(Input.getFilename());
145
146 // asm_final spec is empty.
147
148 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
149 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
150}
151
152void darwin::MachOTool::anchor() {}
153
154void darwin::MachOTool::AddMachOArch(const ArgList &Args,
155 ArgStringList &CmdArgs) const {
156 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
157
158 // Derived from darwin_arch spec.
159 CmdArgs.push_back("-arch");
160 CmdArgs.push_back(Args.MakeArgString(ArchName));
161
162 // FIXME: Is this needed anymore?
163 if (ArchName == "arm")
164 CmdArgs.push_back("-force_cpusubtype_ALL");
165}
166
167bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
168 // We only need to generate a temp path for LTO if we aren't compiling object
169 // files. When compiling source files, we run 'dsymutil' after linking. We
170 // don't run 'dsymutil' when compiling object files.
171 for (const auto &Input : Inputs)
172 if (Input.getType() != types::TY_Object)
173 return true;
174
175 return false;
176}
177
178/// Pass -no_deduplicate to ld64 under certain conditions:
179///
180/// - Either -O0 or -O1 is explicitly specified
181/// - No -O option is specified *and* this is a compile+link (implicit -O0)
182///
183/// Also do *not* add -no_deduplicate when no -O option is specified and this
184/// is just a link (we can't imply -O0)
185static bool shouldLinkerNotDedup(bool IsLinkerOnlyAction, const ArgList &Args) {
186 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
187 if (A->getOption().matches(options::OPT_O0))
188 return true;
189 if (A->getOption().matches(options::OPT_O))
190 return llvm::StringSwitch<bool>(A->getValue())
191 .Case("1", true)
192 .Default(false);
193 return false; // OPT_Ofast & OPT_O4
194 }
195
196 if (!IsLinkerOnlyAction) // Implicit -O0 for compile+linker only.
197 return true;
198 return false;
199}
200
201void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
202 ArgStringList &CmdArgs,
203 const InputInfoList &Inputs) const {
204 const Driver &D = getToolChain().getDriver();
205 const toolchains::MachO &MachOTC = getMachOToolChain();
206
207 unsigned Version[5] = {0, 0, 0, 0, 0};
208 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
209 if (!Driver::GetReleaseVersion(A->getValue(), Version))
210 D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
211 }
212
213 // Newer linkers support -demangle. Pass it if supported and not disabled by
214 // the user.
215 if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
216 CmdArgs.push_back("-demangle");
217
218 if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
219 CmdArgs.push_back("-export_dynamic");
220
221 // If we are using App Extension restrictions, pass a flag to the linker
222 // telling it that the compiled code has been audited.
223 if (Args.hasFlag(options::OPT_fapplication_extension,
224 options::OPT_fno_application_extension, false))
225 CmdArgs.push_back("-application_extension");
226
227 if (D.isUsingLTO()) {
228 // If we are using LTO, then automatically create a temporary file path for
229 // the linker to use, so that it's lifetime will extend past a possible
230 // dsymutil step.
231 if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
232 const char *TmpPath = C.getArgs().MakeArgString(
233 D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
234 C.addTempFile(TmpPath);
235 CmdArgs.push_back("-object_path_lto");
236 CmdArgs.push_back(TmpPath);
237 }
238 }
239
240 // Use -lto_library option to specify the libLTO.dylib path. Try to find
241 // it in clang installed libraries. ld64 will only look at this argument
242 // when it actually uses LTO, so libLTO.dylib only needs to exist at link
243 // time if ld64 decides that it needs to use LTO.
244 // Since this is passed unconditionally, ld64 will never look for libLTO.dylib
245 // next to it. That's ok since ld64 using a libLTO.dylib not matching the
246 // clang version won't work anyways.
247 if (Version[0] >= 133) {
248 // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
249 StringRef P = llvm::sys::path::parent_path(D.Dir);
250 SmallString<128> LibLTOPath(P);
251 llvm::sys::path::append(LibLTOPath, "lib");
252 llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
253 CmdArgs.push_back("-lto_library");
254 CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
255 }
256
257 // ld64 version 262 and above run the deduplicate pass by default.
258 if (Version[0] >= 262 && shouldLinkerNotDedup(C.getJobs().empty(), Args))
259 CmdArgs.push_back("-no_deduplicate");
260
261 // Derived from the "link" spec.
262 Args.AddAllArgs(CmdArgs, options::OPT_static);
263 if (!Args.hasArg(options::OPT_static))
264 CmdArgs.push_back("-dynamic");
265 if (Args.hasArg(options::OPT_fgnu_runtime)) {
266 // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
267 // here. How do we wish to handle such things?
268 }
269
270 if (!Args.hasArg(options::OPT_dynamiclib)) {
271 AddMachOArch(Args, CmdArgs);
272 // FIXME: Why do this only on this path?
273 Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
274
275 Args.AddLastArg(CmdArgs, options::OPT_bundle);
276 Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
277 Args.AddAllArgs(CmdArgs, options::OPT_client__name);
278
279 Arg *A;
280 if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
281 (A = Args.getLastArg(options::OPT_current__version)) ||
282 (A = Args.getLastArg(options::OPT_install__name)))
283 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
284 << "-dynamiclib";
285
286 Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
287 Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
288 Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
289 } else {
290 CmdArgs.push_back("-dylib");
291
292 Arg *A;
293 if ((A = Args.getLastArg(options::OPT_bundle)) ||
294 (A = Args.getLastArg(options::OPT_bundle__loader)) ||
295 (A = Args.getLastArg(options::OPT_client__name)) ||
296 (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
297 (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
298 (A = Args.getLastArg(options::OPT_private__bundle)))
299 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
300 << "-dynamiclib";
301
302 Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
303 "-dylib_compatibility_version");
304 Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
305 "-dylib_current_version");
306
307 AddMachOArch(Args, CmdArgs);
308
309 Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
310 "-dylib_install_name");
311 }
312
313 Args.AddLastArg(CmdArgs, options::OPT_all__load);
314 Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
315 Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
316 if (MachOTC.isTargetIOSBased())
317 Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
318 Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
319 Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
320 Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
321 Args.AddLastArg(CmdArgs, options::OPT_dynamic);
322 Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
323 Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
324 Args.AddAllArgs(CmdArgs, options::OPT_force__load);
325 Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
326 Args.AddAllArgs(CmdArgs, options::OPT_image__base);
327 Args.AddAllArgs(CmdArgs, options::OPT_init);
328
329 // Add the deployment target.
330 MachOTC.addMinVersionArgs(Args, CmdArgs);
331
332 Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
333 Args.AddLastArg(CmdArgs, options::OPT_multi__module);
334 Args.AddLastArg(CmdArgs, options::OPT_single__module);
335 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
336 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
337
338 if (const Arg *A =
339 Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
340 options::OPT_fno_pie, options::OPT_fno_PIE)) {
341 if (A->getOption().matches(options::OPT_fpie) ||
342 A->getOption().matches(options::OPT_fPIE))
343 CmdArgs.push_back("-pie");
344 else
345 CmdArgs.push_back("-no_pie");
346 }
347
348 // for embed-bitcode, use -bitcode_bundle in linker command
349 if (C.getDriver().embedBitcodeEnabled()) {
350 // Check if the toolchain supports bitcode build flow.
351 if (MachOTC.SupportsEmbeddedBitcode()) {
352 CmdArgs.push_back("-bitcode_bundle");
353 if (C.getDriver().embedBitcodeMarkerOnly() && Version[0] >= 278) {
354 CmdArgs.push_back("-bitcode_process_mode");
355 CmdArgs.push_back("marker");
356 }
357 } else
358 D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
359 }
360
361 Args.AddLastArg(CmdArgs, options::OPT_prebind);
362 Args.AddLastArg(CmdArgs, options::OPT_noprebind);
363 Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
364 Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
365 Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
366 Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
367 Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
368 Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
369 Args.AddAllArgs(CmdArgs, options::OPT_segprot);
370 Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
371 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
372 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
373 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
374 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
375 Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
376 Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
377
378 // Give --sysroot= preference, over the Apple specific behavior to also use
379 // --isysroot as the syslibroot.
380 StringRef sysroot = C.getSysRoot();
381 if (sysroot != "") {
382 CmdArgs.push_back("-syslibroot");
383 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
384 } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
385 CmdArgs.push_back("-syslibroot");
386 CmdArgs.push_back(A->getValue());
387 }
388
389 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
390 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
391 Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
392 Args.AddAllArgs(CmdArgs, options::OPT_undefined);
393 Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
394 Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
395 Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
396 Args.AddAllArgs(CmdArgs, options::OPT_y);
397 Args.AddLastArg(CmdArgs, options::OPT_w);
398 Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
399 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
400 Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
401 Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
402 Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
403 Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
404 Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
405 Args.AddLastArg(CmdArgs, options::OPT_whyload);
406 Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
407 Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
408 Args.AddLastArg(CmdArgs, options::OPT_dylinker);
409 Args.AddLastArg(CmdArgs, options::OPT_Mach);
410}
411
412/// Determine whether we are linking the ObjC runtime.
413static bool isObjCRuntimeLinked(const ArgList &Args) {
414 if (isObjCAutoRefCount(Args)) {
415 Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
416 return true;
417 }
418 return Args.hasArg(options::OPT_fobjc_link_runtime);
419}
420
421void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
422 const InputInfo &Output,
423 const InputInfoList &Inputs,
424 const ArgList &Args,
425 const char *LinkingOutput) const {
426 assert(Output.getType() == types::TY_Image && "Invalid linker output type.")((Output.getType() == types::TY_Image && "Invalid linker output type."
) ? static_cast<void> (0) : __assert_fail ("Output.getType() == types::TY_Image && \"Invalid linker output type.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 426, __PRETTY_FUNCTION__))
;
427
428 // If the number of arguments surpasses the system limits, we will encode the
429 // input files in a separate file, shortening the command line. To this end,
430 // build a list of input file names that can be passed via a file with the
431 // -filelist linker option.
432 llvm::opt::ArgStringList InputFileList;
433
434 // The logic here is derived from gcc's behavior; most of which
435 // comes from specs (starting with link_command). Consult gcc for
436 // more information.
437 ArgStringList CmdArgs;
438
439 /// Hack(tm) to ignore linking errors when we are doing ARC migration.
440 if (Args.hasArg(options::OPT_ccc_arcmt_check,
441 options::OPT_ccc_arcmt_migrate)) {
442 for (const auto &Arg : Args)
443 Arg->claim();
444 const char *Exec =
445 Args.MakeArgString(getToolChain().GetProgramPath("touch"));
446 CmdArgs.push_back(Output.getFilename());
447 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
448 return;
449 }
450
451 // I'm not sure why this particular decomposition exists in gcc, but
452 // we follow suite for ease of comparison.
453 AddLinkArgs(C, Args, CmdArgs, Inputs);
454
455 // For LTO, pass the name of the optimization record file and other
456 // opt-remarks flags.
457 if (Args.hasFlag(options::OPT_fsave_optimization_record,
458 options::OPT_fno_save_optimization_record, false)) {
459 CmdArgs.push_back("-mllvm");
460 CmdArgs.push_back("-lto-pass-remarks-output");
461 CmdArgs.push_back("-mllvm");
462
463 SmallString<128> F;
464 F = Output.getFilename();
465 F += ".opt.yaml";
466 CmdArgs.push_back(Args.MakeArgString(F));
467
468 if (getLastProfileUseArg(Args)) {
469 CmdArgs.push_back("-mllvm");
470 CmdArgs.push_back("-lto-pass-remarks-with-hotness");
471
472 if (const Arg *A =
473 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
474 CmdArgs.push_back("-mllvm");
475 std::string Opt =
476 std::string("-lto-pass-remarks-hotness-threshold=") + A->getValue();
477 CmdArgs.push_back(Args.MakeArgString(Opt));
478 }
479 }
480 }
481
482 // Propagate the -moutline flag to the linker in LTO.
483 if (Args.hasFlag(options::OPT_moutline, options::OPT_mno_outline, false)) {
484 if (getMachOToolChain().getMachOArchName(Args) == "arm64") {
485 CmdArgs.push_back("-mllvm");
486 CmdArgs.push_back("-enable-machine-outliner");
487
488 // Outline from linkonceodr functions by default in LTO.
489 CmdArgs.push_back("-mllvm");
490 CmdArgs.push_back("-enable-linkonceodr-outlining");
491 }
492 }
493
494 // It seems that the 'e' option is completely ignored for dynamic executables
495 // (the default), and with static executables, the last one wins, as expected.
496 Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
497 options::OPT_Z_Flag, options::OPT_u_Group,
498 options::OPT_e, options::OPT_r});
499
500 // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
501 // members of static archive libraries which implement Objective-C classes or
502 // categories.
503 if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
504 CmdArgs.push_back("-ObjC");
505
506 CmdArgs.push_back("-o");
507 CmdArgs.push_back(Output.getFilename());
508
509 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
510 getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
511
512 Args.AddAllArgs(CmdArgs, options::OPT_L);
513
514 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
515 // Build the input file for -filelist (list of linker input files) in case we
516 // need it later
517 for (const auto &II : Inputs) {
518 if (!II.isFilename()) {
519 // This is a linker input argument.
520 // We cannot mix input arguments and file names in a -filelist input, thus
521 // we prematurely stop our list (remaining files shall be passed as
522 // arguments).
523 if (InputFileList.size() > 0)
524 break;
525
526 continue;
527 }
528
529 InputFileList.push_back(II.getFilename());
530 }
531
532 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
533 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
534
535 if (isObjCRuntimeLinked(Args) &&
536 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
537 // We use arclite library for both ARC and subscripting support.
538 getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
539
540 CmdArgs.push_back("-framework");
541 CmdArgs.push_back("Foundation");
542 // Link libobj.
543 CmdArgs.push_back("-lobjc");
544 }
545
546 if (LinkingOutput) {
547 CmdArgs.push_back("-arch_multiple");
548 CmdArgs.push_back("-final_output");
549 CmdArgs.push_back(LinkingOutput);
550 }
551
552 if (Args.hasArg(options::OPT_fnested_functions))
553 CmdArgs.push_back("-allow_stack_execute");
554
555 getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
556
557 if (unsigned Parallelism =
558 getLTOParallelism(Args, getToolChain().getDriver())) {
559 CmdArgs.push_back("-mllvm");
560 CmdArgs.push_back(Args.MakeArgString("-threads=" + Twine(Parallelism)));
561 }
562
563 if (getToolChain().ShouldLinkCXXStdlib(Args))
564 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
565 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
566 // link_ssp spec is empty.
567
568 // Let the tool chain choose which runtime library to link.
569 getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
570
571 // No need to do anything for pthreads. Claim argument to avoid warning.
572 Args.ClaimAllArgs(options::OPT_pthread);
573 Args.ClaimAllArgs(options::OPT_pthreads);
574 }
575
576 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
577 // endfile_spec is empty.
578 }
579
580 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
581 Args.AddAllArgs(CmdArgs, options::OPT_F);
582
583 // -iframework should be forwarded as -F.
584 for (const Arg *A : Args.filtered(options::OPT_iframework))
585 CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
586
587 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
588 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
589 if (A->getValue() == StringRef("Accelerate")) {
590 CmdArgs.push_back("-framework");
591 CmdArgs.push_back("Accelerate");
592 }
593 }
594 }
595
596 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
597 std::unique_ptr<Command> Cmd =
598 llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
599 Cmd->setInputFileList(std::move(InputFileList));
600 C.addCommand(std::move(Cmd));
601}
602
603void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
604 const InputInfo &Output,
605 const InputInfoList &Inputs,
606 const ArgList &Args,
607 const char *LinkingOutput) const {
608 ArgStringList CmdArgs;
609
610 CmdArgs.push_back("-create");
611 assert(Output.isFilename() && "Unexpected lipo output.")((Output.isFilename() && "Unexpected lipo output.") ?
static_cast<void> (0) : __assert_fail ("Output.isFilename() && \"Unexpected lipo output.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 611, __PRETTY_FUNCTION__))
;
612
613 CmdArgs.push_back("-output");
614 CmdArgs.push_back(Output.getFilename());
615
616 for (const auto &II : Inputs) {
617 assert(II.isFilename() && "Unexpected lipo input.")((II.isFilename() && "Unexpected lipo input.") ? static_cast
<void> (0) : __assert_fail ("II.isFilename() && \"Unexpected lipo input.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 617, __PRETTY_FUNCTION__))
;
618 CmdArgs.push_back(II.getFilename());
619 }
620
621 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
622 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
623}
624
625void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
626 const InputInfo &Output,
627 const InputInfoList &Inputs,
628 const ArgList &Args,
629 const char *LinkingOutput) const {
630 ArgStringList CmdArgs;
631
632 CmdArgs.push_back("-o");
633 CmdArgs.push_back(Output.getFilename());
634
635 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.")((Inputs.size() == 1 && "Unable to handle multiple inputs."
) ? static_cast<void> (0) : __assert_fail ("Inputs.size() == 1 && \"Unable to handle multiple inputs.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 635, __PRETTY_FUNCTION__))
;
636 const InputInfo &Input = Inputs[0];
637 assert(Input.isFilename() && "Unexpected dsymutil input.")((Input.isFilename() && "Unexpected dsymutil input.")
? static_cast<void> (0) : __assert_fail ("Input.isFilename() && \"Unexpected dsymutil input.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 637, __PRETTY_FUNCTION__))
;
638 CmdArgs.push_back(Input.getFilename());
639
640 const char *Exec =
641 Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
642 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
643}
644
645void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
646 const InputInfo &Output,
647 const InputInfoList &Inputs,
648 const ArgList &Args,
649 const char *LinkingOutput) const {
650 ArgStringList CmdArgs;
651 CmdArgs.push_back("--verify");
652 CmdArgs.push_back("--debug-info");
653 CmdArgs.push_back("--eh-frame");
654 CmdArgs.push_back("--quiet");
655
656 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.")((Inputs.size() == 1 && "Unable to handle multiple inputs."
) ? static_cast<void> (0) : __assert_fail ("Inputs.size() == 1 && \"Unable to handle multiple inputs.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 656, __PRETTY_FUNCTION__))
;
657 const InputInfo &Input = Inputs[0];
658 assert(Input.isFilename() && "Unexpected verify input")((Input.isFilename() && "Unexpected verify input") ? static_cast
<void> (0) : __assert_fail ("Input.isFilename() && \"Unexpected verify input\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 658, __PRETTY_FUNCTION__))
;
659
660 // Grabbing the output of the earlier dsymutil run.
661 CmdArgs.push_back(Input.getFilename());
662
663 const char *Exec =
664 Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
665 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
666}
667
668MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
669 : ToolChain(D, Triple, Args) {
670 // We expect 'as', 'ld', etc. to be adjacent to our install dir.
671 getProgramPaths().push_back(getDriver().getInstalledDir());
672 if (getDriver().getInstalledDir() != getDriver().Dir)
673 getProgramPaths().push_back(getDriver().Dir);
674}
675
676/// Darwin - Darwin tool chain for i386 and x86_64.
677Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
678 : MachO(D, Triple, Args), TargetInitialized(false),
679 CudaInstallation(D, Triple, Args) {}
680
681types::ID MachO::LookupTypeForExtension(StringRef Ext) const {
682 types::ID Ty = types::lookupTypeForExtension(Ext);
683
684 // Darwin always preprocesses assembly files (unless -x is used explicitly).
685 if (Ty == types::TY_PP_Asm)
686 return types::TY_Asm;
687
688 return Ty;
689}
690
691bool MachO::HasNativeLLVMSupport() const { return true; }
692
693ToolChain::CXXStdlibType Darwin::GetDefaultCXXStdlibType() const {
694 // Default to use libc++ on OS X 10.9+ and iOS 7+.
695 if ((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
696 (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0)) ||
697 isTargetWatchOSBased())
698 return ToolChain::CST_Libcxx;
699
700 return ToolChain::CST_Libstdcxx;
701}
702
703/// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
704ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
705 if (isTargetWatchOSBased())
706 return ObjCRuntime(ObjCRuntime::WatchOS, TargetVersion);
707 if (isTargetIOSBased())
708 return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
709 if (isNonFragile)
710 return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
711 return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
712}
713
714/// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
715bool Darwin::hasBlocksRuntime() const {
716 if (isTargetWatchOSBased())
717 return true;
718 else if (isTargetIOSBased())
719 return !isIPhoneOSVersionLT(3, 2);
720 else {
721 assert(isTargetMacOS() && "unexpected darwin target")((isTargetMacOS() && "unexpected darwin target") ? static_cast
<void> (0) : __assert_fail ("isTargetMacOS() && \"unexpected darwin target\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 721, __PRETTY_FUNCTION__))
;
722 return !isMacosxVersionLT(10, 6);
723 }
724}
725
726void Darwin::AddCudaIncludeArgs(const ArgList &DriverArgs,
727 ArgStringList &CC1Args) const {
728 CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
729}
730
731// This is just a MachO name translation routine and there's no
732// way to join this into ARMTargetParser without breaking all
733// other assumptions. Maybe MachO should consider standardising
734// their nomenclature.
735static const char *ArmMachOArchName(StringRef Arch) {
736 return llvm::StringSwitch<const char *>(Arch)
737 .Case("armv6k", "armv6")
738 .Case("armv6m", "armv6m")
739 .Case("armv5tej", "armv5")
740 .Case("xscale", "xscale")
741 .Case("armv4t", "armv4t")
742 .Case("armv7", "armv7")
743 .Cases("armv7a", "armv7-a", "armv7")
744 .Cases("armv7r", "armv7-r", "armv7")
745 .Cases("armv7em", "armv7e-m", "armv7em")
746 .Cases("armv7k", "armv7-k", "armv7k")
747 .Cases("armv7m", "armv7-m", "armv7m")
748 .Cases("armv7s", "armv7-s", "armv7s")
749 .Default(nullptr);
750}
751
752static const char *ArmMachOArchNameCPU(StringRef CPU) {
753 llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);
754 if (ArchKind == llvm::ARM::ArchKind::INVALID)
755 return nullptr;
756 StringRef Arch = llvm::ARM::getArchName(ArchKind);
757
758 // FIXME: Make sure this MachO triple mangling is really necessary.
759 // ARMv5* normalises to ARMv5.
760 if (Arch.startswith("armv5"))
761 Arch = Arch.substr(0, 5);
762 // ARMv6*, except ARMv6M, normalises to ARMv6.
763 else if (Arch.startswith("armv6") && !Arch.endswith("6m"))
764 Arch = Arch.substr(0, 5);
765 // ARMv7A normalises to ARMv7.
766 else if (Arch.endswith("v7a"))
767 Arch = Arch.substr(0, 5);
768 return Arch.data();
769}
770
771StringRef MachO::getMachOArchName(const ArgList &Args) const {
772 switch (getTriple().getArch()) {
773 default:
774 return getDefaultUniversalArchName();
775
776 case llvm::Triple::aarch64:
777 return "arm64";
778
779 case llvm::Triple::thumb:
780 case llvm::Triple::arm:
781 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ))
782 if (const char *Arch = ArmMachOArchName(A->getValue()))
783 return Arch;
784
785 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
786 if (const char *Arch = ArmMachOArchNameCPU(A->getValue()))
787 return Arch;
788
789 return "arm";
790 }
791}
792
793Darwin::~Darwin() {}
794
795MachO::~MachO() {}
796
797std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
798 types::ID InputType) const {
799 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
800
801 // If the target isn't initialized (e.g., an unknown Darwin platform, return
802 // the default triple).
803 if (!isTargetInitialized())
804 return Triple.getTriple();
805
806 SmallString<16> Str;
807 if (isTargetWatchOSBased())
808 Str += "watchos";
809 else if (isTargetTvOSBased())
810 Str += "tvos";
811 else if (isTargetIOSBased())
812 Str += "ios";
813 else
814 Str += "macosx";
815 Str += getTargetVersion().getAsString();
816 Triple.setOSName(Str);
817
818 return Triple.getTriple();
819}
820
821Tool *MachO::getTool(Action::ActionClass AC) const {
822 switch (AC) {
823 case Action::LipoJobClass:
824 if (!Lipo)
825 Lipo.reset(new tools::darwin::Lipo(*this));
826 return Lipo.get();
827 case Action::DsymutilJobClass:
828 if (!Dsymutil)
829 Dsymutil.reset(new tools::darwin::Dsymutil(*this));
830 return Dsymutil.get();
831 case Action::VerifyDebugInfoJobClass:
832 if (!VerifyDebug)
833 VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
834 return VerifyDebug.get();
835 default:
836 return ToolChain::getTool(AC);
837 }
838}
839
840Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
841
842Tool *MachO::buildAssembler() const {
843 return new tools::darwin::Assembler(*this);
844}
845
846DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
847 const ArgList &Args)
848 : Darwin(D, Triple, Args) {}
849
850void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
851 // For modern targets, promote certain warnings to errors.
852 if (isTargetWatchOSBased() || getTriple().isArch64Bit()) {
853 // Always enable -Wdeprecated-objc-isa-usage and promote it
854 // to an error.
855 CC1Args.push_back("-Wdeprecated-objc-isa-usage");
856 CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
857
858 // For iOS and watchOS, also error about implicit function declarations,
859 // as that can impact calling conventions.
860 if (!isTargetMacOS())
861 CC1Args.push_back("-Werror=implicit-function-declaration");
862 }
863}
864
865void DarwinClang::AddLinkARCArgs(const ArgList &Args,
866 ArgStringList &CmdArgs) const {
867 // Avoid linking compatibility stubs on i386 mac.
868 if (isTargetMacOS() && getArch() == llvm::Triple::x86)
869 return;
870
871 ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
872
873 if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
874 runtime.hasSubscripting())
875 return;
876
877 CmdArgs.push_back("-force_load");
878 SmallString<128> P(getDriver().ClangExecutable);
879 llvm::sys::path::remove_filename(P); // 'clang'
880 llvm::sys::path::remove_filename(P); // 'bin'
881 llvm::sys::path::append(P, "lib", "arc", "libarclite_");
882 // Mash in the platform.
883 if (isTargetWatchOSSimulator())
884 P += "watchsimulator";
885 else if (isTargetWatchOS())
886 P += "watchos";
887 else if (isTargetTvOSSimulator())
888 P += "appletvsimulator";
889 else if (isTargetTvOS())
890 P += "appletvos";
891 else if (isTargetIOSSimulator())
892 P += "iphonesimulator";
893 else if (isTargetIPhoneOS())
894 P += "iphoneos";
895 else
896 P += "macosx";
897 P += ".a";
898
899 CmdArgs.push_back(Args.MakeArgString(P));
900}
901
902unsigned DarwinClang::GetDefaultDwarfVersion() const {
903 // Default to use DWARF 2 on OS X 10.10 / iOS 8 and lower.
904 if ((isTargetMacOS() && isMacosxVersionLT(10, 11)) ||
905 (isTargetIOSBased() && isIPhoneOSVersionLT(9)))
906 return 2;
907 return 4;
908}
909
910void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
911 StringRef Component, RuntimeLinkOptions Opts,
912 bool IsShared) const {
913 SmallString<64> DarwinLibName = StringRef("libclang_rt.");
914 // an Darwin the builtins compomnent is not in the library name
915 if (Component != "builtins") {
916 DarwinLibName += Component;
917 if (!(Opts & RLO_IsEmbedded))
918 DarwinLibName += "_";
919 DarwinLibName += getOSLibraryNameSuffix();
920 } else
921 DarwinLibName += getOSLibraryNameSuffix(true);
922
923 DarwinLibName += IsShared ? "_dynamic.dylib" : ".a";
924 SmallString<128> Dir(getDriver().ResourceDir);
925 llvm::sys::path::append(
926 Dir, "lib", (Opts & RLO_IsEmbedded) ? "macho_embedded" : "darwin");
927
928 SmallString<128> P(Dir);
929 llvm::sys::path::append(P, DarwinLibName);
930
931 // For now, allow missing resource libraries to support developers who may
932 // not have compiler-rt checked out or integrated into their build (unless
933 // we explicitly force linking with this library).
934 if ((Opts & RLO_AlwaysLink) || getVFS().exists(P)) {
935 const char *LibArg = Args.MakeArgString(P);
936 if (Opts & RLO_FirstLink)
937 CmdArgs.insert(CmdArgs.begin(), LibArg);
938 else
939 CmdArgs.push_back(LibArg);
940 }
941
942 // Adding the rpaths might negatively interact when other rpaths are involved,
943 // so we should make sure we add the rpaths last, after all user-specified
944 // rpaths. This is currently true from this place, but we need to be
945 // careful if this function is ever called before user's rpaths are emitted.
946 if (Opts & RLO_AddRPath) {
947 assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library")((DarwinLibName.endswith(".dylib") && "must be a dynamic library"
) ? static_cast<void> (0) : __assert_fail ("DarwinLibName.endswith(\".dylib\") && \"must be a dynamic library\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 947, __PRETTY_FUNCTION__))
;
948
949 // Add @executable_path to rpath to support having the dylib copied with
950 // the executable.
951 CmdArgs.push_back("-rpath");
952 CmdArgs.push_back("@executable_path");
953
954 // Add the path to the resource dir to rpath to support using the dylib
955 // from the default location without copying.
956 CmdArgs.push_back("-rpath");
957 CmdArgs.push_back(Args.MakeArgString(Dir));
958 }
959}
960
961StringRef Darwin::getPlatformFamily() const {
962 switch (TargetPlatform) {
963 case DarwinPlatformKind::MacOS:
964 return "MacOSX";
965 case DarwinPlatformKind::IPhoneOS:
966 return "iPhone";
967 case DarwinPlatformKind::TvOS:
968 return "AppleTV";
969 case DarwinPlatformKind::WatchOS:
970 return "Watch";
971 }
972 llvm_unreachable("Unsupported platform")::llvm::llvm_unreachable_internal("Unsupported platform", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 972)
;
973}
974
975StringRef Darwin::getSDKName(StringRef isysroot) {
976 // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
977 llvm::sys::path::const_iterator SDKDir;
978 auto BeginSDK = llvm::sys::path::begin(isysroot);
979 auto EndSDK = llvm::sys::path::end(isysroot);
980 for (auto IT = BeginSDK; IT != EndSDK; ++IT) {
981 StringRef SDK = *IT;
982 if (SDK.endswith(".sdk"))
983 return SDK.slice(0, SDK.size() - 4);
984 }
985 return "";
986}
987
988StringRef Darwin::getOSLibraryNameSuffix(bool IgnoreSim) const {
989 switch (TargetPlatform) {
990 case DarwinPlatformKind::MacOS:
991 return "osx";
992 case DarwinPlatformKind::IPhoneOS:
993 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "ios"
994 : "iossim";
995 case DarwinPlatformKind::TvOS:
996 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "tvos"
997 : "tvossim";
998 case DarwinPlatformKind::WatchOS:
999 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "watchos"
1000 : "watchossim";
1001 }
1002 llvm_unreachable("Unsupported platform")::llvm::llvm_unreachable_internal("Unsupported platform", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 1002)
;
1003}
1004
1005/// Check if the link command contains a symbol export directive.
1006static bool hasExportSymbolDirective(const ArgList &Args) {
1007 for (Arg *A : Args) {
1008 if (A->getOption().matches(options::OPT_exported__symbols__list))
1009 return true;
1010 if (!A->getOption().matches(options::OPT_Wl_COMMA) &&
1011 !A->getOption().matches(options::OPT_Xlinker))
1012 continue;
1013 if (A->containsValue("-exported_symbols_list") ||
1014 A->containsValue("-exported_symbol"))
1015 return true;
1016 }
1017 return false;
1018}
1019
1020/// Add an export directive for \p Symbol to the link command.
1021static void addExportedSymbol(ArgStringList &CmdArgs, const char *Symbol) {
1022 CmdArgs.push_back("-exported_symbol");
1023 CmdArgs.push_back(Symbol);
1024}
1025
1026void Darwin::addProfileRTLibs(const ArgList &Args,
1027 ArgStringList &CmdArgs) const {
1028 if (!needsProfileRT(Args)) return;
1029
1030 AddLinkRuntimeLib(Args, CmdArgs, "profile",
1031 RuntimeLinkOptions(RLO_AlwaysLink | RLO_FirstLink));
1032
1033 // If we have a symbol export directive and we're linking in the profile
1034 // runtime, automatically export symbols necessary to implement some of the
1035 // runtime's functionality.
1036 if (hasExportSymbolDirective(Args)) {
1037 if (needsGCovInstrumentation(Args)) {
1038 addExportedSymbol(CmdArgs, "___gcov_flush");
1039 addExportedSymbol(CmdArgs, "_flush_fn_list");
1040 addExportedSymbol(CmdArgs, "_writeout_fn_list");
1041 } else {
1042 addExportedSymbol(CmdArgs, "___llvm_profile_filename");
1043 addExportedSymbol(CmdArgs, "___llvm_profile_raw_version");
1044 addExportedSymbol(CmdArgs, "_lprofCurFilename");
1045 addExportedSymbol(CmdArgs, "_lprofMergeValueProfData");
1046 }
1047 addExportedSymbol(CmdArgs, "_lprofDirMode");
1048 }
1049}
1050
1051void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
1052 ArgStringList &CmdArgs,
1053 StringRef Sanitizer,
1054 bool Shared) const {
1055 auto RLO = RuntimeLinkOptions(RLO_AlwaysLink | (Shared ? RLO_AddRPath : 0U));
1056 AddLinkRuntimeLib(Args, CmdArgs, Sanitizer, RLO, Shared);
1057}
1058
1059ToolChain::RuntimeLibType DarwinClang::GetRuntimeLibType(
1060 const ArgList &Args) const {
1061 if (Arg* A = Args.getLastArg(options::OPT_rtlib_EQ)) {
1062 StringRef Value = A->getValue();
1063 if (Value != "compiler-rt")
1064 getDriver().Diag(clang::diag::err_drv_unsupported_rtlib_for_platform)
1065 << Value << "darwin";
1066 }
1067
1068 return ToolChain::RLT_CompilerRT;
1069}
1070
1071void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
1072 ArgStringList &CmdArgs) const {
1073 // Call once to ensure diagnostic is printed if wrong value was specified
1074 GetRuntimeLibType(Args);
1075
1076 // Darwin doesn't support real static executables, don't link any runtime
1077 // libraries with -static.
1078 if (Args.hasArg(options::OPT_static) ||
1079 Args.hasArg(options::OPT_fapple_kext) ||
1080 Args.hasArg(options::OPT_mkernel))
1081 return;
1082
1083 // Reject -static-libgcc for now, we can deal with this when and if someone
1084 // cares. This is useful in situations where someone wants to statically link
1085 // something like libstdc++, and needs its runtime support routines.
1086 if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
1087 getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
1088 return;
1089 }
1090
1091 const SanitizerArgs &Sanitize = getSanitizerArgs();
1092 if (Sanitize.needsAsanRt())
1093 AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
1094 if (Sanitize.needsLsanRt())
1095 AddLinkSanitizerLibArgs(Args, CmdArgs, "lsan");
1096 if (Sanitize.needsUbsanRt())
1097 AddLinkSanitizerLibArgs(Args, CmdArgs,
1098 Sanitize.requiresMinimalRuntime() ? "ubsan_minimal"
1099 : "ubsan",
1100 Sanitize.needsSharedRt());
1101 if (Sanitize.needsTsanRt())
1102 AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan");
1103 if (Sanitize.needsFuzzer() && !Args.hasArg(options::OPT_dynamiclib)) {
1104 AddLinkSanitizerLibArgs(Args, CmdArgs, "fuzzer", /*shared=*/false);
1105
1106 // Libfuzzer is written in C++ and requires libcxx.
1107 AddCXXStdlibLibArgs(Args, CmdArgs);
1108 }
1109 if (Sanitize.needsStatsRt()) {
1110 AddLinkRuntimeLib(Args, CmdArgs, "stats_client", RLO_AlwaysLink);
1111 AddLinkSanitizerLibArgs(Args, CmdArgs, "stats");
1112 }
1113 if (Sanitize.needsEsanRt())
1114 AddLinkSanitizerLibArgs(Args, CmdArgs, "esan");
1115
1116 const XRayArgs &XRay = getXRayArgs();
1117 if (XRay.needsXRayRt()) {
1118 AddLinkRuntimeLib(Args, CmdArgs, "xray");
1119 AddLinkRuntimeLib(Args, CmdArgs, "xray-basic");
1120 AddLinkRuntimeLib(Args, CmdArgs, "xray-fdr");
1121 }
1122
1123 // Otherwise link libSystem, then the dynamic runtime library, and finally any
1124 // target specific static runtime library.
1125 CmdArgs.push_back("-lSystem");
1126
1127 // Select the dynamic runtime library and the target specific static library.
1128 if (isTargetIOSBased()) {
1129 // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
1130 // it never went into the SDK.
1131 // Linking against libgcc_s.1 isn't needed for iOS 5.0+
1132 if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
1133 getTriple().getArch() != llvm::Triple::aarch64)
1134 CmdArgs.push_back("-lgcc_s.1");
1135 }
1136 AddLinkRuntimeLib(Args, CmdArgs, "builtins");
1137}
1138
1139/// Returns the most appropriate macOS target version for the current process.
1140///
1141/// If the macOS SDK version is the same or earlier than the system version,
1142/// then the SDK version is returned. Otherwise the system version is returned.
1143static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion) {
1144 unsigned Major, Minor, Micro;
1145 llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
1146 if (!SystemTriple.isMacOSX())
1147 return MacOSSDKVersion;
1148 SystemTriple.getMacOSXVersion(Major, Minor, Micro);
1149 VersionTuple SystemVersion(Major, Minor, Micro);
1150 bool HadExtra;
1151 if (!Driver::GetReleaseVersion(MacOSSDKVersion, Major, Minor, Micro,
1152 HadExtra))
1153 return MacOSSDKVersion;
1154 VersionTuple SDKVersion(Major, Minor, Micro);
1155 if (SDKVersion > SystemVersion)
1156 return SystemVersion.getAsString();
1157 return MacOSSDKVersion;
1158}
1159
1160namespace {
1161
1162/// The Darwin OS that was selected or inferred from arguments / environment.
1163struct DarwinPlatform {
1164 enum SourceKind {
1165 /// The OS was specified using the -target argument.
1166 TargetArg,
1167 /// The OS was specified using the -m<os>-version-min argument.
1168 OSVersionArg,
1169 /// The OS was specified using the OS_DEPLOYMENT_TARGET environment.
1170 DeploymentTargetEnv,
1171 /// The OS was inferred from the SDK.
1172 InferredFromSDK,
1173 /// The OS was inferred from the -arch.
1174 InferredFromArch
1175 };
1176
1177 using DarwinPlatformKind = Darwin::DarwinPlatformKind;
1178 using DarwinEnvironmentKind = Darwin::DarwinEnvironmentKind;
1179
1180 DarwinPlatformKind getPlatform() const { return Platform; }
1181
1182 DarwinEnvironmentKind getEnvironment() const { return Environment; }
1183
1184 void setEnvironment(DarwinEnvironmentKind Kind) {
1185 Environment = Kind;
1186 InferSimulatorFromArch = false;
1187 }
1188
1189 StringRef getOSVersion() const {
1190 if (Kind == OSVersionArg)
1191 return Argument->getValue();
1192 return OSVersion;
1193 }
1194
1195 void setOSVersion(StringRef S) {
1196 assert(Kind == TargetArg && "Unexpected kind!")((Kind == TargetArg && "Unexpected kind!") ? static_cast
<void> (0) : __assert_fail ("Kind == TargetArg && \"Unexpected kind!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 1196, __PRETTY_FUNCTION__))
;
1197 OSVersion = S;
1198 }
1199
1200 bool hasOSVersion() const { return HasOSVersion; }
1201
1202 /// Returns true if the target OS was explicitly specified.
1203 bool isExplicitlySpecified() const { return Kind <= DeploymentTargetEnv; }
1204
1205 /// Returns true if the simulator environment can be inferred from the arch.
1206 bool canInferSimulatorFromArch() const { return InferSimulatorFromArch; }
1207
1208 /// Adds the -m<os>-version-min argument to the compiler invocation.
1209 void addOSVersionMinArgument(DerivedArgList &Args, const OptTable &Opts) {
1210 if (Argument)
1211 return;
1212 assert(Kind != TargetArg && Kind != OSVersionArg && "Invalid kind")((Kind != TargetArg && Kind != OSVersionArg &&
"Invalid kind") ? static_cast<void> (0) : __assert_fail
("Kind != TargetArg && Kind != OSVersionArg && \"Invalid kind\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 1212, __PRETTY_FUNCTION__))
;
1213 options::ID Opt;
1214 switch (Platform) {
1215 case DarwinPlatformKind::MacOS:
1216 Opt = options::OPT_mmacosx_version_min_EQ;
1217 break;
1218 case DarwinPlatformKind::IPhoneOS:
1219 Opt = options::OPT_miphoneos_version_min_EQ;
1220 break;
1221 case DarwinPlatformKind::TvOS:
1222 Opt = options::OPT_mtvos_version_min_EQ;
1223 break;
1224 case DarwinPlatformKind::WatchOS:
1225 Opt = options::OPT_mwatchos_version_min_EQ;
1226 break;
1227 }
1228 Argument = Args.MakeJoinedArg(nullptr, Opts.getOption(Opt), OSVersion);
1229 Args.append(Argument);
1230 }
1231
1232 /// Returns the OS version with the argument / environment variable that
1233 /// specified it.
1234 std::string getAsString(DerivedArgList &Args, const OptTable &Opts) {
1235 switch (Kind) {
1236 case TargetArg:
1237 case OSVersionArg:
1238 case InferredFromSDK:
1239 case InferredFromArch:
1240 assert(Argument && "OS version argument not yet inferred")((Argument && "OS version argument not yet inferred")
? static_cast<void> (0) : __assert_fail ("Argument && \"OS version argument not yet inferred\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 1240, __PRETTY_FUNCTION__))
;
1241 return Argument->getAsString(Args);
1242 case DeploymentTargetEnv:
1243 return (llvm::Twine(EnvVarName) + "=" + OSVersion).str();
1244 }
1245 llvm_unreachable("Unsupported Darwin Source Kind")::llvm::llvm_unreachable_internal("Unsupported Darwin Source Kind"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 1245)
;
1246 }
1247
1248 static DarwinPlatform createFromTarget(const llvm::Triple &TT,
1249 StringRef OSVersion, Arg *A) {
1250 DarwinPlatform Result(TargetArg, getPlatformFromOS(TT.getOS()), OSVersion,
1251 A);
1252 switch (TT.getEnvironment()) {
1253 case llvm::Triple::Simulator:
1254 Result.Environment = DarwinEnvironmentKind::Simulator;
1255 break;
1256 default:
1257 break;
1258 }
1259 unsigned Major, Minor, Micro;
1260 TT.getOSVersion(Major, Minor, Micro);
1261 if (Major == 0)
1262 Result.HasOSVersion = false;
1263 return Result;
1264 }
1265 static DarwinPlatform createOSVersionArg(DarwinPlatformKind Platform,
1266 Arg *A) {
1267 return DarwinPlatform(OSVersionArg, Platform, A);
1268 }
1269 static DarwinPlatform createDeploymentTargetEnv(DarwinPlatformKind Platform,
1270 StringRef EnvVarName,
1271 StringRef Value) {
1272 DarwinPlatform Result(DeploymentTargetEnv, Platform, Value);
1273 Result.EnvVarName = EnvVarName;
1274 return Result;
1275 }
1276 static DarwinPlatform createFromSDK(DarwinPlatformKind Platform,
1277 StringRef Value,
1278 bool IsSimulator = false) {
1279 DarwinPlatform Result(InferredFromSDK, Platform, Value);
1280 if (IsSimulator)
1281 Result.Environment = DarwinEnvironmentKind::Simulator;
1282 Result.InferSimulatorFromArch = false;
1283 return Result;
1284 }
1285 static DarwinPlatform createFromArch(llvm::Triple::OSType OS,
1286 StringRef Value) {
1287 return DarwinPlatform(InferredFromArch, getPlatformFromOS(OS), Value);
1288 }
1289
1290 /// Constructs an inferred SDKInfo value based on the version inferred from
1291 /// the SDK path itself. Only works for values that were created by inferring
1292 /// the platform from the SDKPath.
1293 DarwinSDKInfo inferSDKInfo() {
1294 assert(Kind == InferredFromSDK && "can infer SDK info only")((Kind == InferredFromSDK && "can infer SDK info only"
) ? static_cast<void> (0) : __assert_fail ("Kind == InferredFromSDK && \"can infer SDK info only\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 1294, __PRETTY_FUNCTION__))
;
1295 llvm::VersionTuple Version;
1296 bool IsValid = !Version.tryParse(OSVersion);
1297 (void)IsValid;
1298 assert(IsValid && "invalid SDK version")((IsValid && "invalid SDK version") ? static_cast<
void> (0) : __assert_fail ("IsValid && \"invalid SDK version\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 1298, __PRETTY_FUNCTION__))
;
1299 return DarwinSDKInfo(Version);
1300 }
1301
1302private:
1303 DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, Arg *Argument)
1304 : Kind(Kind), Platform(Platform), Argument(Argument) {}
1305 DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, StringRef Value,
1306 Arg *Argument = nullptr)
1307 : Kind(Kind), Platform(Platform), OSVersion(Value), Argument(Argument) {}
1308
1309 static DarwinPlatformKind getPlatformFromOS(llvm::Triple::OSType OS) {
1310 switch (OS) {
1311 case llvm::Triple::Darwin:
1312 case llvm::Triple::MacOSX:
1313 return DarwinPlatformKind::MacOS;
1314 case llvm::Triple::IOS:
1315 return DarwinPlatformKind::IPhoneOS;
1316 case llvm::Triple::TvOS:
1317 return DarwinPlatformKind::TvOS;
1318 case llvm::Triple::WatchOS:
1319 return DarwinPlatformKind::WatchOS;
1320 default:
1321 llvm_unreachable("Unable to infer Darwin variant")::llvm::llvm_unreachable_internal("Unable to infer Darwin variant"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 1321)
;
1322 }
1323 }
1324
1325 SourceKind Kind;
1326 DarwinPlatformKind Platform;
1327 DarwinEnvironmentKind Environment = DarwinEnvironmentKind::NativeEnvironment;
1328 std::string OSVersion;
1329 bool HasOSVersion = true, InferSimulatorFromArch = true;
1330 Arg *Argument;
1331 StringRef EnvVarName;
1332};
1333
1334/// Returns the deployment target that's specified using the -m<os>-version-min
1335/// argument.
1336Optional<DarwinPlatform>
1337getDeploymentTargetFromOSVersionArg(DerivedArgList &Args,
1338 const Driver &TheDriver) {
1339 Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
1340 Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ,
1341 options::OPT_mios_simulator_version_min_EQ);
1342 Arg *TvOSVersion =
1343 Args.getLastArg(options::OPT_mtvos_version_min_EQ,
1344 options::OPT_mtvos_simulator_version_min_EQ);
1345 Arg *WatchOSVersion =
1346 Args.getLastArg(options::OPT_mwatchos_version_min_EQ,
1347 options::OPT_mwatchos_simulator_version_min_EQ);
1348 if (OSXVersion) {
1349 if (iOSVersion || TvOSVersion || WatchOSVersion) {
1350 TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1351 << OSXVersion->getAsString(Args)
1352 << (iOSVersion ? iOSVersion
1353 : TvOSVersion ? TvOSVersion : WatchOSVersion)
1354 ->getAsString(Args);
1355 }
1356 return DarwinPlatform::createOSVersionArg(Darwin::MacOS, OSXVersion);
1357 } else if (iOSVersion) {
1358 if (TvOSVersion || WatchOSVersion) {
1359 TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1360 << iOSVersion->getAsString(Args)
1361 << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
1362 }
1363 return DarwinPlatform::createOSVersionArg(Darwin::IPhoneOS, iOSVersion);
1364 } else if (TvOSVersion) {
1365 if (WatchOSVersion) {
1366 TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1367 << TvOSVersion->getAsString(Args)
1368 << WatchOSVersion->getAsString(Args);
1369 }
1370 return DarwinPlatform::createOSVersionArg(Darwin::TvOS, TvOSVersion);
1371 } else if (WatchOSVersion)
1372 return DarwinPlatform::createOSVersionArg(Darwin::WatchOS, WatchOSVersion);
1373 return None;
1374}
1375
1376/// Returns the deployment target that's specified using the
1377/// OS_DEPLOYMENT_TARGET environment variable.
1378Optional<DarwinPlatform>
1379getDeploymentTargetFromEnvironmentVariables(const Driver &TheDriver,
1380 const llvm::Triple &Triple) {
1381 std::string Targets[Darwin::LastDarwinPlatform + 1];
1382 const char *EnvVars[] = {
1383 "MACOSX_DEPLOYMENT_TARGET",
1384 "IPHONEOS_DEPLOYMENT_TARGET",
1385 "TVOS_DEPLOYMENT_TARGET",
1386 "WATCHOS_DEPLOYMENT_TARGET",
1387 };
1388 static_assert(llvm::array_lengthof(EnvVars) == Darwin::LastDarwinPlatform + 1,
1389 "Missing platform");
1390 for (const auto &I : llvm::enumerate(llvm::makeArrayRef(EnvVars))) {
1391 if (char *Env = ::getenv(I.value()))
1392 Targets[I.index()] = Env;
1393 }
1394
1395 // Do not allow conflicts with the watchOS target.
1396 if (!Targets[Darwin::WatchOS].empty() &&
1397 (!Targets[Darwin::IPhoneOS].empty() || !Targets[Darwin::TvOS].empty())) {
1398 TheDriver.Diag(diag::err_drv_conflicting_deployment_targets)
1399 << "WATCHOS_DEPLOYMENT_TARGET"
1400 << (!Targets[Darwin::IPhoneOS].empty() ? "IPHONEOS_DEPLOYMENT_TARGET"
1401 : "TVOS_DEPLOYMENT_TARGET");
1402 }
1403
1404 // Do not allow conflicts with the tvOS target.
1405 if (!Targets[Darwin::TvOS].empty() && !Targets[Darwin::IPhoneOS].empty()) {
1406 TheDriver.Diag(diag::err_drv_conflicting_deployment_targets)
1407 << "TVOS_DEPLOYMENT_TARGET"
1408 << "IPHONEOS_DEPLOYMENT_TARGET";
1409 }
1410
1411 // Allow conflicts among OSX and iOS for historical reasons, but choose the
1412 // default platform.
1413 if (!Targets[Darwin::MacOS].empty() &&
1414 (!Targets[Darwin::IPhoneOS].empty() ||
1415 !Targets[Darwin::WatchOS].empty() || !Targets[Darwin::TvOS].empty())) {
1416 if (Triple.getArch() == llvm::Triple::arm ||
1417 Triple.getArch() == llvm::Triple::aarch64 ||
1418 Triple.getArch() == llvm::Triple::thumb)
1419 Targets[Darwin::MacOS] = "";
1420 else
1421 Targets[Darwin::IPhoneOS] = Targets[Darwin::WatchOS] =
1422 Targets[Darwin::TvOS] = "";
1423 }
1424
1425 for (const auto &Target : llvm::enumerate(llvm::makeArrayRef(Targets))) {
1426 if (!Target.value().empty())
1427 return DarwinPlatform::createDeploymentTargetEnv(
1428 (Darwin::DarwinPlatformKind)Target.index(), EnvVars[Target.index()],
1429 Target.value());
1430 }
1431 return None;
1432}
1433
1434/// Tries to infer the deployment target from the SDK specified by -isysroot
1435/// (or SDKROOT). Uses the version specified in the SDKSettings.json file if
1436/// it's available.
1437Optional<DarwinPlatform>
1438inferDeploymentTargetFromSDK(DerivedArgList &Args,
1439 const Optional<DarwinSDKInfo> &SDKInfo) {
1440 const Arg *A = Args.getLastArg(options::OPT_isysroot);
1441 if (!A)
1442 return None;
1443 StringRef isysroot = A->getValue();
1444 StringRef SDK = Darwin::getSDKName(isysroot);
1445 if (!SDK.size())
1446 return None;
1447
1448 std::string Version;
1449 if (SDKInfo) {
1450 // Get the version from the SDKSettings.json if it's available.
1451 Version = SDKInfo->getVersion().getAsString();
1452 } else {
1453 // Slice the version number out.
1454 // Version number is between the first and the last number.
1455 size_t StartVer = SDK.find_first_of("0123456789");
1456 size_t EndVer = SDK.find_last_of("0123456789");
1457 if (StartVer != StringRef::npos && EndVer > StartVer)
1458 Version = SDK.slice(StartVer, EndVer + 1);
1459 }
1460 if (Version.empty())
1461 return None;
1462
1463 if (SDK.startswith("iPhoneOS") || SDK.startswith("iPhoneSimulator"))
1464 return DarwinPlatform::createFromSDK(
1465 Darwin::IPhoneOS, Version,
1466 /*IsSimulator=*/SDK.startswith("iPhoneSimulator"));
1467 else if (SDK.startswith("MacOSX"))
1468 return DarwinPlatform::createFromSDK(Darwin::MacOS,
1469 getSystemOrSDKMacOSVersion(Version));
1470 else if (SDK.startswith("WatchOS") || SDK.startswith("WatchSimulator"))
1471 return DarwinPlatform::createFromSDK(
1472 Darwin::WatchOS, Version,
1473 /*IsSimulator=*/SDK.startswith("WatchSimulator"));
1474 else if (SDK.startswith("AppleTVOS") || SDK.startswith("AppleTVSimulator"))
1475 return DarwinPlatform::createFromSDK(
1476 Darwin::TvOS, Version,
1477 /*IsSimulator=*/SDK.startswith("AppleTVSimulator"));
1478 return None;
1479}
1480
1481std::string getOSVersion(llvm::Triple::OSType OS, const llvm::Triple &Triple,
1482 const Driver &TheDriver) {
1483 unsigned Major, Minor, Micro;
1484 llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
1485 switch (OS) {
1486 case llvm::Triple::Darwin:
1487 case llvm::Triple::MacOSX:
1488 // If there is no version specified on triple, and both host and target are
1489 // macos, use the host triple to infer OS version.
1490 if (Triple.isMacOSX() && SystemTriple.isMacOSX() &&
1491 !Triple.getOSMajorVersion())
1492 SystemTriple.getMacOSXVersion(Major, Minor, Micro);
1493 else if (!Triple.getMacOSXVersion(Major, Minor, Micro))
1494 TheDriver.Diag(diag::err_drv_invalid_darwin_version)
1495 << Triple.getOSName();
1496 break;
1497 case llvm::Triple::IOS:
1498 Triple.getiOSVersion(Major, Minor, Micro);
1499 break;
1500 case llvm::Triple::TvOS:
1501 Triple.getOSVersion(Major, Minor, Micro);
1502 break;
1503 case llvm::Triple::WatchOS:
1504 Triple.getWatchOSVersion(Major, Minor, Micro);
1505 break;
1506 default:
1507 llvm_unreachable("Unexpected OS type")::llvm::llvm_unreachable_internal("Unexpected OS type", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 1507)
;
1508 break;
1509 }
1510
1511 std::string OSVersion;
1512 llvm::raw_string_ostream(OSVersion) << Major << '.' << Minor << '.' << Micro;
1513 return OSVersion;
1514}
1515
1516/// Tries to infer the target OS from the -arch.
1517Optional<DarwinPlatform>
1518inferDeploymentTargetFromArch(DerivedArgList &Args, const Darwin &Toolchain,
1519 const llvm::Triple &Triple,
1520 const Driver &TheDriver) {
1521 llvm::Triple::OSType OSTy = llvm::Triple::UnknownOS;
1522
1523 StringRef MachOArchName = Toolchain.getMachOArchName(Args);
1524 if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
1525 MachOArchName == "arm64")
1526 OSTy = llvm::Triple::IOS;
1527 else if (MachOArchName == "armv7k")
1528 OSTy = llvm::Triple::WatchOS;
1529 else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
1530 MachOArchName != "armv7em")
1531 OSTy = llvm::Triple::MacOSX;
1532
1533 if (OSTy == llvm::Triple::UnknownOS)
1534 return None;
1535 return DarwinPlatform::createFromArch(OSTy,
1536 getOSVersion(OSTy, Triple, TheDriver));
1537}
1538
1539/// Returns the deployment target that's specified using the -target option.
1540Optional<DarwinPlatform> getDeploymentTargetFromTargetArg(
1541 DerivedArgList &Args, const llvm::Triple &Triple, const Driver &TheDriver) {
1542 if (!Args.hasArg(options::OPT_target))
1543 return None;
1544 if (Triple.getOS() == llvm::Triple::Darwin ||
1545 Triple.getOS() == llvm::Triple::UnknownOS)
1546 return None;
1547 std::string OSVersion = getOSVersion(Triple.getOS(), Triple, TheDriver);
1548 return DarwinPlatform::createFromTarget(Triple, OSVersion,
1549 Args.getLastArg(options::OPT_target));
1550}
1551
1552Optional<DarwinSDKInfo> parseSDKSettings(llvm::vfs::FileSystem &VFS,
1553 const ArgList &Args,
1554 const Driver &TheDriver) {
1555 const Arg *A = Args.getLastArg(options::OPT_isysroot);
1556 if (!A)
9
Assuming 'A' is non-null
10
Taking false branch
1557 return None;
1558 StringRef isysroot = A->getValue();
1559 auto SDKInfoOrErr = driver::parseDarwinSDKInfo(VFS, isysroot);
1560 if (!SDKInfoOrErr) {
11
Taking true branch
1561 llvm::consumeError(SDKInfoOrErr.takeError());
12
Calling 'consumeError'
1562 TheDriver.Diag(diag::warn_drv_darwin_sdk_invalid_settings);
1563 return None;
1564 }
1565 return *SDKInfoOrErr;
1566}
1567
1568} // namespace
1569
1570void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
1571 const OptTable &Opts = getDriver().getOpts();
1572
1573 // Support allowing the SDKROOT environment variable used by xcrun and other
1574 // Xcode tools to define the default sysroot, by making it the default for
1575 // isysroot.
1576 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
4
Assuming 'A' is null
5
Taking false branch
1577 // Warn if the path does not exist.
1578 if (!getVFS().exists(A->getValue()))
1579 getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
1580 } else {
1581 if (char *env = ::getenv("SDKROOT")) {
6
Assuming 'env' is null
7
Taking false branch
1582 // We only use this value as the default if it is an absolute path,
1583 // exists, and it is not the root path.
1584 if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
1585 StringRef(env) != "/") {
1586 Args.append(Args.MakeSeparateArg(
1587 nullptr, Opts.getOption(options::OPT_isysroot), env));
1588 }
1589 }
1590 }
1591
1592 // Read the SDKSettings.json file for more information, like the SDK version
1593 // that we can pass down to the compiler.
1594 SDKInfo = parseSDKSettings(getVFS(), Args, getDriver());
8
Calling 'parseSDKSettings'
1595
1596 // The OS and the version can be specified using the -target argument.
1597 Optional<DarwinPlatform> OSTarget =
1598 getDeploymentTargetFromTargetArg(Args, getTriple(), getDriver());
1599 if (OSTarget) {
1600 Optional<DarwinPlatform> OSVersionArgTarget =
1601 getDeploymentTargetFromOSVersionArg(Args, getDriver());
1602 if (OSVersionArgTarget) {
1603 unsigned TargetMajor, TargetMinor, TargetMicro;
1604 bool TargetExtra;
1605 unsigned ArgMajor, ArgMinor, ArgMicro;
1606 bool ArgExtra;
1607 if (OSTarget->getPlatform() != OSVersionArgTarget->getPlatform() ||
1608 (Driver::GetReleaseVersion(OSTarget->getOSVersion(), TargetMajor,
1609 TargetMinor, TargetMicro, TargetExtra) &&
1610 Driver::GetReleaseVersion(OSVersionArgTarget->getOSVersion(),
1611 ArgMajor, ArgMinor, ArgMicro, ArgExtra) &&
1612 (VersionTuple(TargetMajor, TargetMinor, TargetMicro) !=
1613 VersionTuple(ArgMajor, ArgMinor, ArgMicro) ||
1614 TargetExtra != ArgExtra))) {
1615 // Select the OS version from the -m<os>-version-min argument when
1616 // the -target does not include an OS version.
1617 if (OSTarget->getPlatform() == OSVersionArgTarget->getPlatform() &&
1618 !OSTarget->hasOSVersion()) {
1619 OSTarget->setOSVersion(OSVersionArgTarget->getOSVersion());
1620 } else {
1621 // Warn about -m<os>-version-min that doesn't match the OS version
1622 // that's specified in the target.
1623 std::string OSVersionArg =
1624 OSVersionArgTarget->getAsString(Args, Opts);
1625 std::string TargetArg = OSTarget->getAsString(Args, Opts);
1626 getDriver().Diag(clang::diag::warn_drv_overriding_flag_option)
1627 << OSVersionArg << TargetArg;
1628 }
1629 }
1630 }
1631 } else {
1632 // The OS target can be specified using the -m<os>version-min argument.
1633 OSTarget = getDeploymentTargetFromOSVersionArg(Args, getDriver());
1634 // If no deployment target was specified on the command line, check for
1635 // environment defines.
1636 if (!OSTarget) {
1637 OSTarget =
1638 getDeploymentTargetFromEnvironmentVariables(getDriver(), getTriple());
1639 if (OSTarget) {
1640 // Don't infer simulator from the arch when the SDK is also specified.
1641 Optional<DarwinPlatform> SDKTarget =
1642 inferDeploymentTargetFromSDK(Args, SDKInfo);
1643 if (SDKTarget)
1644 OSTarget->setEnvironment(SDKTarget->getEnvironment());
1645 }
1646 }
1647 // If there is no command-line argument to specify the Target version and
1648 // no environment variable defined, see if we can set the default based
1649 // on -isysroot using SDKSettings.json if it exists.
1650 if (!OSTarget) {
1651 OSTarget = inferDeploymentTargetFromSDK(Args, SDKInfo);
1652 /// If the target was successfully constructed from the SDK path, try to
1653 /// infer the SDK info if the SDK doesn't have it.
1654 if (OSTarget && !SDKInfo)
1655 SDKInfo = OSTarget->inferSDKInfo();
1656 }
1657 // If no OS targets have been specified, try to guess platform from -target
1658 // or arch name and compute the version from the triple.
1659 if (!OSTarget)
1660 OSTarget =
1661 inferDeploymentTargetFromArch(Args, *this, getTriple(), getDriver());
1662 }
1663
1664 assert(OSTarget && "Unable to infer Darwin variant")((OSTarget && "Unable to infer Darwin variant") ? static_cast
<void> (0) : __assert_fail ("OSTarget && \"Unable to infer Darwin variant\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 1664, __PRETTY_FUNCTION__))
;
1665 OSTarget->addOSVersionMinArgument(Args, Opts);
1666 DarwinPlatformKind Platform = OSTarget->getPlatform();
1667
1668 unsigned Major, Minor, Micro;
1669 bool HadExtra;
1670 // Set the tool chain target information.
1671 if (Platform == MacOS) {
1672 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1673 Micro, HadExtra) ||
1674 HadExtra || Major != 10 || Minor >= 100 || Micro >= 100)
1675 getDriver().Diag(diag::err_drv_invalid_version_number)
1676 << OSTarget->getAsString(Args, Opts);
1677 } else if (Platform == IPhoneOS) {
1678 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1679 Micro, HadExtra) ||
1680 HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
1681 getDriver().Diag(diag::err_drv_invalid_version_number)
1682 << OSTarget->getAsString(Args, Opts);
1683 ;
1684 // For 32-bit targets, the deployment target for iOS has to be earlier than
1685 // iOS 11.
1686 if (getTriple().isArch32Bit() && Major >= 11) {
1687 // If the deployment target is explicitly specified, print a diagnostic.
1688 if (OSTarget->isExplicitlySpecified()) {
1689 getDriver().Diag(diag::warn_invalid_ios_deployment_target)
1690 << OSTarget->getAsString(Args, Opts);
1691 // Otherwise, set it to 10.99.99.
1692 } else {
1693 Major = 10;
1694 Minor = 99;
1695 Micro = 99;
1696 }
1697 }
1698 } else if (Platform == TvOS) {
1699 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1700 Micro, HadExtra) ||
1701 HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
1702 getDriver().Diag(diag::err_drv_invalid_version_number)
1703 << OSTarget->getAsString(Args, Opts);
1704 } else if (Platform == WatchOS) {
1705 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1706 Micro, HadExtra) ||
1707 HadExtra || Major >= 10 || Minor >= 100 || Micro >= 100)
1708 getDriver().Diag(diag::err_drv_invalid_version_number)
1709 << OSTarget->getAsString(Args, Opts);
1710 } else
1711 llvm_unreachable("unknown kind of Darwin platform")::llvm::llvm_unreachable_internal("unknown kind of Darwin platform"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 1711)
;
1712
1713 DarwinEnvironmentKind Environment = OSTarget->getEnvironment();
1714 // Recognize iOS targets with an x86 architecture as the iOS simulator.
1715 if (Environment == NativeEnvironment && Platform != MacOS &&
1716 OSTarget->canInferSimulatorFromArch() &&
1717 (getTriple().getArch() == llvm::Triple::x86 ||
1718 getTriple().getArch() == llvm::Triple::x86_64))
1719 Environment = Simulator;
1720
1721 setTarget(Platform, Environment, Major, Minor, Micro);
1722
1723 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1724 StringRef SDK = getSDKName(A->getValue());
1725 if (SDK.size() > 0) {
1726 size_t StartVer = SDK.find_first_of("0123456789");
1727 StringRef SDKName = SDK.slice(0, StartVer);
1728 if (!SDKName.startswith(getPlatformFamily()))
1729 getDriver().Diag(diag::warn_incompatible_sysroot)
1730 << SDKName << getPlatformFamily();
1731 }
1732 }
1733}
1734
1735void DarwinClang::AddClangCXXStdlibIncludeArgs(
1736 const llvm::opt::ArgList &DriverArgs,
1737 llvm::opt::ArgStringList &CC1Args) const {
1738 // The implementation from a base class will pass through the -stdlib to
1739 // CC1Args.
1740 // FIXME: this should not be necessary, remove usages in the frontend
1741 // (e.g. HeaderSearchOptions::UseLibcxx) and don't pipe -stdlib.
1742 ToolChain::AddClangCXXStdlibIncludeArgs(DriverArgs, CC1Args);
1743
1744 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1745 DriverArgs.hasArg(options::OPT_nostdincxx))
1746 return;
1747
1748 switch (GetCXXStdlibType(DriverArgs)) {
1749 case ToolChain::CST_Libcxx: {
1750 llvm::StringRef InstallDir = getDriver().getInstalledDir();
1751 if (InstallDir.empty())
1752 break;
1753 // On Darwin, libc++ may be installed alongside the compiler in
1754 // include/c++/v1.
1755 // Get from 'foo/bin' to 'foo'.
1756 SmallString<128> P = llvm::sys::path::parent_path(InstallDir);
1757 // Get to 'foo/include/c++/v1'.
1758 llvm::sys::path::append(P, "include", "c++", "v1");
1759 addSystemInclude(DriverArgs, CC1Args, P);
1760 break;
1761 }
1762 case ToolChain::CST_Libstdcxx:
1763 // FIXME: should we do something about it?
1764 break;
1765 }
1766}
1767void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
1768 ArgStringList &CmdArgs) const {
1769 CXXStdlibType Type = GetCXXStdlibType(Args);
1770
1771 switch (Type) {
1772 case ToolChain::CST_Libcxx:
1773 CmdArgs.push_back("-lc++");
1774 break;
1775
1776 case ToolChain::CST_Libstdcxx:
1777 // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
1778 // it was previously found in the gcc lib dir. However, for all the Darwin
1779 // platforms we care about it was -lstdc++.6, so we search for that
1780 // explicitly if we can't see an obvious -lstdc++ candidate.
1781
1782 // Check in the sysroot first.
1783 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1784 SmallString<128> P(A->getValue());
1785 llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
1786
1787 if (!getVFS().exists(P)) {
1788 llvm::sys::path::remove_filename(P);
1789 llvm::sys::path::append(P, "libstdc++.6.dylib");
1790 if (getVFS().exists(P)) {
1791 CmdArgs.push_back(Args.MakeArgString(P));
1792 return;
1793 }
1794 }
1795 }
1796
1797 // Otherwise, look in the root.
1798 // FIXME: This should be removed someday when we don't have to care about
1799 // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
1800 if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
1801 getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
1802 CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
1803 return;
1804 }
1805
1806 // Otherwise, let the linker search.
1807 CmdArgs.push_back("-lstdc++");
1808 break;
1809 }
1810}
1811
1812void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
1813 ArgStringList &CmdArgs) const {
1814 // For Darwin platforms, use the compiler-rt-based support library
1815 // instead of the gcc-provided one (which is also incidentally
1816 // only present in the gcc lib dir, which makes it hard to find).
1817
1818 SmallString<128> P(getDriver().ResourceDir);
1819 llvm::sys::path::append(P, "lib", "darwin");
1820
1821 // Use the newer cc_kext for iOS ARM after 6.0.
1822 if (isTargetWatchOS()) {
1823 llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
1824 } else if (isTargetTvOS()) {
1825 llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
1826 } else if (isTargetIPhoneOS()) {
1827 llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
1828 } else {
1829 llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
1830 }
1831
1832 // For now, allow missing resource libraries to support developers who may
1833 // not have compiler-rt checked out or integrated into their build.
1834 if (getVFS().exists(P))
1835 CmdArgs.push_back(Args.MakeArgString(P));
1836}
1837
1838DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
1839 StringRef BoundArch,
1840 Action::OffloadKind) const {
1841 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1842 const OptTable &Opts = getDriver().getOpts();
1843
1844 // FIXME: We really want to get out of the tool chain level argument
1845 // translation business, as it makes the driver functionality much
1846 // more opaque. For now, we follow gcc closely solely for the
1847 // purpose of easily achieving feature parity & testability. Once we
1848 // have something that works, we should reevaluate each translation
1849 // and try to push it down into tool specific logic.
1850
1851 for (Arg *A : Args) {
1852 if (A->getOption().matches(options::OPT_Xarch__)) {
1853 // Skip this argument unless the architecture matches either the toolchain
1854 // triple arch, or the arch being bound.
1855 llvm::Triple::ArchType XarchArch =
1856 tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
1857 if (!(XarchArch == getArch() ||
1858 (!BoundArch.empty() &&
1859 XarchArch ==
1860 tools::darwin::getArchTypeForMachOArchName(BoundArch))))
1861 continue;
1862
1863 Arg *OriginalArg = A;
1864 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1865 unsigned Prev = Index;
1866 std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
1867
1868 // If the argument parsing failed or more than one argument was
1869 // consumed, the -Xarch_ argument's parameter tried to consume
1870 // extra arguments. Emit an error and ignore.
1871 //
1872 // We also want to disallow any options which would alter the
1873 // driver behavior; that isn't going to work in our model. We
1874 // use isDriverOption() as an approximation, although things
1875 // like -O4 are going to slip through.
1876 if (!XarchArg || Index > Prev + 1) {
1877 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
1878 << A->getAsString(Args);
1879 continue;
1880 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
1881 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
1882 << A->getAsString(Args);
1883 continue;
1884 }
1885
1886 XarchArg->setBaseArg(A);
1887
1888 A = XarchArg.release();
1889 DAL->AddSynthesizedArg(A);
1890
1891 // Linker input arguments require custom handling. The problem is that we
1892 // have already constructed the phase actions, so we can not treat them as
1893 // "input arguments".
1894 if (A->getOption().hasFlag(options::LinkerInput)) {
1895 // Convert the argument into individual Zlinker_input_args.
1896 for (const char *Value : A->getValues()) {
1897 DAL->AddSeparateArg(
1898 OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
1899 }
1900 continue;
1901 }
1902 }
1903
1904 // Sob. These is strictly gcc compatible for the time being. Apple
1905 // gcc translates options twice, which means that self-expanding
1906 // options add duplicates.
1907 switch ((options::ID)A->getOption().getID()) {
1908 default:
1909 DAL->append(A);
1910 break;
1911
1912 case options::OPT_mkernel:
1913 case options::OPT_fapple_kext:
1914 DAL->append(A);
1915 DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
1916 break;
1917
1918 case options::OPT_dependency_file:
1919 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
1920 break;
1921
1922 case options::OPT_gfull:
1923 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
1924 DAL->AddFlagArg(
1925 A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
1926 break;
1927
1928 case options::OPT_gused:
1929 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
1930 DAL->AddFlagArg(
1931 A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
1932 break;
1933
1934 case options::OPT_shared:
1935 DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
1936 break;
1937
1938 case options::OPT_fconstant_cfstrings:
1939 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
1940 break;
1941
1942 case options::OPT_fno_constant_cfstrings:
1943 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
1944 break;
1945
1946 case options::OPT_Wnonportable_cfstrings:
1947 DAL->AddFlagArg(A,
1948 Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
1949 break;
1950
1951 case options::OPT_Wno_nonportable_cfstrings:
1952 DAL->AddFlagArg(
1953 A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
1954 break;
1955
1956 case options::OPT_fpascal_strings:
1957 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
1958 break;
1959
1960 case options::OPT_fno_pascal_strings:
1961 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
1962 break;
1963 }
1964 }
1965
1966 if (getTriple().getArch() == llvm::Triple::x86 ||
1967 getTriple().getArch() == llvm::Triple::x86_64)
1968 if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
1969 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
1970 "core2");
1971
1972 // Add the arch options based on the particular spelling of -arch, to match
1973 // how the driver driver works.
1974 if (!BoundArch.empty()) {
1975 StringRef Name = BoundArch;
1976 const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
1977 const Option MArch = Opts.getOption(clang::driver::options::OPT_march_EQ);
1978
1979 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
1980 // which defines the list of which architectures we accept.
1981 if (Name == "ppc")
1982 ;
1983 else if (Name == "ppc601")
1984 DAL->AddJoinedArg(nullptr, MCpu, "601");
1985 else if (Name == "ppc603")
1986 DAL->AddJoinedArg(nullptr, MCpu, "603");
1987 else if (Name == "ppc604")
1988 DAL->AddJoinedArg(nullptr, MCpu, "604");
1989 else if (Name == "ppc604e")
1990 DAL->AddJoinedArg(nullptr, MCpu, "604e");
1991 else if (Name == "ppc750")
1992 DAL->AddJoinedArg(nullptr, MCpu, "750");
1993 else if (Name == "ppc7400")
1994 DAL->AddJoinedArg(nullptr, MCpu, "7400");
1995 else if (Name == "ppc7450")
1996 DAL->AddJoinedArg(nullptr, MCpu, "7450");
1997 else if (Name == "ppc970")
1998 DAL->AddJoinedArg(nullptr, MCpu, "970");
1999
2000 else if (Name == "ppc64" || Name == "ppc64le")
2001 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
2002
2003 else if (Name == "i386")
2004 ;
2005 else if (Name == "i486")
2006 DAL->AddJoinedArg(nullptr, MArch, "i486");
2007 else if (Name == "i586")
2008 DAL->AddJoinedArg(nullptr, MArch, "i586");
2009 else if (Name == "i686")
2010 DAL->AddJoinedArg(nullptr, MArch, "i686");
2011 else if (Name == "pentium")
2012 DAL->AddJoinedArg(nullptr, MArch, "pentium");
2013 else if (Name == "pentium2")
2014 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
2015 else if (Name == "pentpro")
2016 DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
2017 else if (Name == "pentIIm3")
2018 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
2019
2020 else if (Name == "x86_64" || Name == "x86_64h")
2021 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
2022
2023 else if (Name == "arm")
2024 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
2025 else if (Name == "armv4t")
2026 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
2027 else if (Name == "armv5")
2028 DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
2029 else if (Name == "xscale")
2030 DAL->AddJoinedArg(nullptr, MArch, "xscale");
2031 else if (Name == "armv6")
2032 DAL->AddJoinedArg(nullptr, MArch, "armv6k");
2033 else if (Name == "armv6m")
2034 DAL->AddJoinedArg(nullptr, MArch, "armv6m");
2035 else if (Name == "armv7")
2036 DAL->AddJoinedArg(nullptr, MArch, "armv7a");
2037 else if (Name == "armv7em")
2038 DAL->AddJoinedArg(nullptr, MArch, "armv7em");
2039 else if (Name == "armv7k")
2040 DAL->AddJoinedArg(nullptr, MArch, "armv7k");
2041 else if (Name == "armv7m")
2042 DAL->AddJoinedArg(nullptr, MArch, "armv7m");
2043 else if (Name == "armv7s")
2044 DAL->AddJoinedArg(nullptr, MArch, "armv7s");
2045 }
2046
2047 return DAL;
2048}
2049
2050void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
2051 ArgStringList &CmdArgs) const {
2052 // Embedded targets are simple at the moment, not supporting sanitizers and
2053 // with different libraries for each member of the product { static, PIC } x
2054 // { hard-float, soft-float }
2055 llvm::SmallString<32> CompilerRT = StringRef("");
2056 CompilerRT +=
2057 (tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard)
2058 ? "hard"
2059 : "soft";
2060 CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic" : "_static";
2061
2062 AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, RLO_IsEmbedded);
2063}
2064
2065bool Darwin::isAlignedAllocationUnavailable() const {
2066 llvm::Triple::OSType OS;
2067
2068 switch (TargetPlatform) {
2069 case MacOS: // Earlier than 10.13.
2070 OS = llvm::Triple::MacOSX;
2071 break;
2072 case IPhoneOS:
2073 OS = llvm::Triple::IOS;
2074 break;
2075 case TvOS: // Earlier than 11.0.
2076 OS = llvm::Triple::TvOS;
2077 break;
2078 case WatchOS: // Earlier than 4.0.
2079 OS = llvm::Triple::WatchOS;
2080 break;
2081 }
2082
2083 return TargetVersion < alignedAllocMinVersion(OS);
2084}
2085
2086void Darwin::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
2087 llvm::opt::ArgStringList &CC1Args,
2088 Action::OffloadKind DeviceOffloadKind) const {
2089 // Pass "-faligned-alloc-unavailable" only when the user hasn't manually
2090 // enabled or disabled aligned allocations.
2091 if (!DriverArgs.hasArgNoClaim(options::OPT_faligned_allocation,
2092 options::OPT_fno_aligned_allocation) &&
2093 isAlignedAllocationUnavailable())
2094 CC1Args.push_back("-faligned-alloc-unavailable");
2095
2096 if (SDKInfo) {
2097 /// Pass the SDK version to the compiler when the SDK information is
2098 /// available.
2099 std::string Arg;
2100 llvm::raw_string_ostream OS(Arg);
2101 OS << "-target-sdk-version=" << SDKInfo->getVersion();
2102 CC1Args.push_back(DriverArgs.MakeArgString(OS.str()));
2103 }
2104}
2105
2106DerivedArgList *
2107Darwin::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
2108 Action::OffloadKind DeviceOffloadKind) const {
2109 // First get the generic Apple args, before moving onto Darwin-specific ones.
2110 DerivedArgList *DAL =
2111 MachO::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
2112 const OptTable &Opts = getDriver().getOpts();
2113
2114 // If no architecture is bound, none of the translations here are relevant.
2115 if (BoundArch.empty())
1
Assuming the condition is false
2
Taking false branch
2116 return DAL;
2117
2118 // Add an explicit version min argument for the deployment target. We do this
2119 // after argument translation because -Xarch_ arguments may add a version min
2120 // argument.
2121 AddDeploymentTarget(*DAL);
3
Calling 'Darwin::AddDeploymentTarget'
2122
2123 // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
2124 // FIXME: It would be far better to avoid inserting those -static arguments,
2125 // but we can't check the deployment target in the translation code until
2126 // it is set here.
2127 if (isTargetWatchOSBased() ||
2128 (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
2129 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
2130 Arg *A = *it;
2131 ++it;
2132 if (A->getOption().getID() != options::OPT_mkernel &&
2133 A->getOption().getID() != options::OPT_fapple_kext)
2134 continue;
2135 assert(it != ie && "unexpected argument translation")((it != ie && "unexpected argument translation") ? static_cast
<void> (0) : __assert_fail ("it != ie && \"unexpected argument translation\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 2135, __PRETTY_FUNCTION__))
;
2136 A = *it;
2137 assert(A->getOption().getID() == options::OPT_static &&((A->getOption().getID() == options::OPT_static &&
"missing expected -static argument") ? static_cast<void>
(0) : __assert_fail ("A->getOption().getID() == options::OPT_static && \"missing expected -static argument\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 2138, __PRETTY_FUNCTION__))
2138 "missing expected -static argument")((A->getOption().getID() == options::OPT_static &&
"missing expected -static argument") ? static_cast<void>
(0) : __assert_fail ("A->getOption().getID() == options::OPT_static && \"missing expected -static argument\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 2138, __PRETTY_FUNCTION__))
;
2139 *it = nullptr;
2140 ++it;
2141 }
2142 }
2143
2144 if (!Args.getLastArg(options::OPT_stdlib_EQ) &&
2145 GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2146 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
2147 "libc++");
2148
2149 // Validate the C++ standard library choice.
2150 CXXStdlibType Type = GetCXXStdlibType(*DAL);
2151 if (Type == ToolChain::CST_Libcxx) {
2152 // Check whether the target provides libc++.
2153 StringRef where;
2154
2155 // Complain about targeting iOS < 5.0 in any way.
2156 if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
2157 where = "iOS 5.0";
2158
2159 if (where != StringRef()) {
2160 getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
2161 }
2162 }
2163
2164 auto Arch = tools::darwin::getArchTypeForMachOArchName(BoundArch);
2165 if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) {
2166 if (Args.hasFlag(options::OPT_fomit_frame_pointer,
2167 options::OPT_fno_omit_frame_pointer, false))
2168 getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target)
2169 << "-fomit-frame-pointer" << BoundArch;
2170 }
2171
2172 return DAL;
2173}
2174
2175bool MachO::IsUnwindTablesDefault(const ArgList &Args) const {
2176 // Unwind tables are not emitted if -fno-exceptions is supplied (except when
2177 // targeting x86_64).
2178 return getArch() == llvm::Triple::x86_64 ||
2179 (GetExceptionModel(Args) != llvm::ExceptionHandling::SjLj &&
2180 Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2181 true));
2182}
2183
2184bool MachO::UseDwarfDebugFlags() const {
2185 if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
2186 return S[0] != '\0';
2187 return false;
2188}
2189
2190llvm::ExceptionHandling Darwin::GetExceptionModel(const ArgList &Args) const {
2191 // Darwin uses SjLj exceptions on ARM.
2192 if (getTriple().getArch() != llvm::Triple::arm &&
2193 getTriple().getArch() != llvm::Triple::thumb)
2194 return llvm::ExceptionHandling::None;
2195
2196 // Only watchOS uses the new DWARF/Compact unwinding method.
2197 llvm::Triple Triple(ComputeLLVMTriple(Args));
2198 if (Triple.isWatchABI())
2199 return llvm::ExceptionHandling::DwarfCFI;
2200
2201 return llvm::ExceptionHandling::SjLj;
2202}
2203
2204bool Darwin::SupportsEmbeddedBitcode() const {
2205 assert(TargetInitialized && "Target not initialized!")((TargetInitialized && "Target not initialized!") ? static_cast
<void> (0) : __assert_fail ("TargetInitialized && \"Target not initialized!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 2205, __PRETTY_FUNCTION__))
;
2206 if (isTargetIPhoneOS() && isIPhoneOSVersionLT(6, 0))
2207 return false;
2208 return true;
2209}
2210
2211bool MachO::isPICDefault() const { return true; }
2212
2213bool MachO::isPIEDefault() const { return false; }
2214
2215bool MachO::isPICDefaultForced() const {
2216 return (getArch() == llvm::Triple::x86_64 ||
2217 getArch() == llvm::Triple::aarch64);
2218}
2219
2220bool MachO::SupportsProfiling() const {
2221 // Profiling instrumentation is only supported on x86.
2222 return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
2223}
2224
2225void Darwin::addMinVersionArgs(const ArgList &Args,
2226 ArgStringList &CmdArgs) const {
2227 VersionTuple TargetVersion = getTargetVersion();
2228
2229 if (isTargetWatchOS())
2230 CmdArgs.push_back("-watchos_version_min");
2231 else if (isTargetWatchOSSimulator())
2232 CmdArgs.push_back("-watchos_simulator_version_min");
2233 else if (isTargetTvOS())
2234 CmdArgs.push_back("-tvos_version_min");
2235 else if (isTargetTvOSSimulator())
2236 CmdArgs.push_back("-tvos_simulator_version_min");
2237 else if (isTargetIOSSimulator())
2238 CmdArgs.push_back("-ios_simulator_version_min");
2239 else if (isTargetIOSBased())
2240 CmdArgs.push_back("-iphoneos_version_min");
2241 else {
2242 assert(isTargetMacOS() && "unexpected target")((isTargetMacOS() && "unexpected target") ? static_cast
<void> (0) : __assert_fail ("isTargetMacOS() && \"unexpected target\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Driver/ToolChains/Darwin.cpp"
, 2242, __PRETTY_FUNCTION__))
;
2243 CmdArgs.push_back("-macosx_version_min");
2244 }
2245
2246 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
2247}
2248
2249void Darwin::addStartObjectFileArgs(const ArgList &Args,
2250 ArgStringList &CmdArgs) const {
2251 // Derived from startfile spec.
2252 if (Args.hasArg(options::OPT_dynamiclib)) {
2253 // Derived from darwin_dylib1 spec.
2254 if (isTargetWatchOSBased()) {
2255 ; // watchOS does not need dylib1.o.
2256 } else if (isTargetIOSSimulator()) {
2257 ; // iOS simulator does not need dylib1.o.
2258 } else if (isTargetIPhoneOS()) {
2259 if (isIPhoneOSVersionLT(3, 1))
2260 CmdArgs.push_back("-ldylib1.o");
2261 } else {
2262 if (isMacosxVersionLT(10, 5))
2263 CmdArgs.push_back("-ldylib1.o");
2264 else if (isMacosxVersionLT(10, 6))
2265 CmdArgs.push_back("-ldylib1.10.5.o");
2266 }
2267 } else {
2268 if (Args.hasArg(options::OPT_bundle)) {
2269 if (!Args.hasArg(options::OPT_static)) {
2270 // Derived from darwin_bundle1 spec.
2271 if (isTargetWatchOSBased()) {
2272 ; // watchOS does not need bundle1.o.
2273 } else if (isTargetIOSSimulator()) {
2274 ; // iOS simulator does not need bundle1.o.
2275 } else if (isTargetIPhoneOS()) {
2276 if (isIPhoneOSVersionLT(3, 1))
2277 CmdArgs.push_back("-lbundle1.o");
2278 } else {
2279 if (isMacosxVersionLT(10, 6))
2280 CmdArgs.push_back("-lbundle1.o");
2281 }
2282 }
2283 } else {
2284 if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
2285 if (Args.hasArg(options::OPT_static) ||
2286 Args.hasArg(options::OPT_object) ||
2287 Args.hasArg(options::OPT_preload)) {
2288 CmdArgs.push_back("-lgcrt0.o");
2289 } else {
2290 CmdArgs.push_back("-lgcrt1.o");
2291
2292 // darwin_crt2 spec is empty.
2293 }
2294 // By default on OS X 10.8 and later, we don't link with a crt1.o
2295 // file and the linker knows to use _main as the entry point. But,
2296 // when compiling with -pg, we need to link with the gcrt1.o file,
2297 // so pass the -no_new_main option to tell the linker to use the
2298 // "start" symbol as the entry point.
2299 if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
2300 CmdArgs.push_back("-no_new_main");
2301 } else {
2302 if (Args.hasArg(options::OPT_static) ||
2303 Args.hasArg(options::OPT_object) ||
2304 Args.hasArg(options::OPT_preload)) {
2305 CmdArgs.push_back("-lcrt0.o");
2306 } else {
2307 // Derived from darwin_crt1 spec.
2308 if (isTargetWatchOSBased()) {
2309 ; // watchOS does not need crt1.o.
2310 } else if (isTargetIOSSimulator()) {
2311 ; // iOS simulator does not need crt1.o.
2312 } else if (isTargetIPhoneOS()) {
2313 if (getArch() == llvm::Triple::aarch64)
2314 ; // iOS does not need any crt1 files for arm64
2315 else if (isIPhoneOSVersionLT(3, 1))
2316 CmdArgs.push_back("-lcrt1.o");
2317 else if (isIPhoneOSVersionLT(6, 0))
2318 CmdArgs.push_back("-lcrt1.3.1.o");
2319 } else {
2320 if (isMacosxVersionLT(10, 5))
2321 CmdArgs.push_back("-lcrt1.o");
2322 else if (isMacosxVersionLT(10, 6))
2323 CmdArgs.push_back("-lcrt1.10.5.o");
2324 else if (isMacosxVersionLT(10, 8))
2325 CmdArgs.push_back("-lcrt1.10.6.o");
2326
2327 // darwin_crt2 spec is empty.
2328 }
2329 }
2330 }
2331 }
2332 }
2333
2334 if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
2335 !isTargetWatchOS() && isMacosxVersionLT(10, 5)) {
2336 const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
2337 CmdArgs.push_back(Str);
2338 }
2339}
2340
2341void Darwin::CheckObjCARC() const {
2342 if (isTargetIOSBased() || isTargetWatchOSBased() ||
2343 (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
2344 return;
2345 getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
2346}
2347
2348SanitizerMask Darwin::getSupportedSanitizers() const {
2349 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
2350 SanitizerMask Res = ToolChain::getSupportedSanitizers();
2351 Res |= SanitizerKind::Address;
2352 Res |= SanitizerKind::Leak;
2353 Res |= SanitizerKind::Fuzzer;
2354 Res |= SanitizerKind::FuzzerNoLink;
2355 Res |= SanitizerKind::Function;
2356
2357 // Prior to 10.9, macOS shipped a version of the C++ standard library without
2358 // C++11 support. The same is true of iOS prior to version 5. These OS'es are
2359 // incompatible with -fsanitize=vptr.
2360 if (!(isTargetMacOS() && isMacosxVersionLT(10, 9))
2361 && !(isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0)))
2362 Res |= SanitizerKind::Vptr;
2363
2364 if (isTargetMacOS()) {
2365 if (IsX86_64)
2366 Res |= SanitizerKind::Thread;
2367 } else if (isTargetIOSSimulator() || isTargetTvOSSimulator()) {
2368 if (IsX86_64)
2369 Res |= SanitizerKind::Thread;
2370 }
2371 return Res;
2372}
2373
2374void Darwin::printVerboseInfo(raw_ostream &OS) const {
2375 CudaInstallation.print(OS);
2376}

/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h

1//===- llvm/Support/Error.h - Recoverable error handling --------*- 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 defines an API used to report recoverable errors.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_ERROR_H
15#define LLVM_SUPPORT_ERROR_H
16
17#include "llvm-c/Error.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/ADT/Twine.h"
22#include "llvm/Config/abi-breaking.h"
23#include "llvm/Support/AlignOf.h"
24#include "llvm/Support/Compiler.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/ErrorOr.h"
28#include "llvm/Support/Format.h"
29#include "llvm/Support/raw_ostream.h"
30#include <algorithm>
31#include <cassert>
32#include <cstdint>
33#include <cstdlib>
34#include <functional>
35#include <memory>
36#include <new>
37#include <string>
38#include <system_error>
39#include <type_traits>
40#include <utility>
41#include <vector>
42
43namespace llvm {
44
45class ErrorSuccess;
46
47/// Base class for error info classes. Do not extend this directly: Extend
48/// the ErrorInfo template subclass instead.
49class ErrorInfoBase {
50public:
51 virtual ~ErrorInfoBase() = default;
52
53 /// Print an error message to an output stream.
54 virtual void log(raw_ostream &OS) const = 0;
55
56 /// Return the error message as a string.
57 virtual std::string message() const {
58 std::string Msg;
59 raw_string_ostream OS(Msg);
60 log(OS);
61 return OS.str();
62 }
63
64 /// Convert this error to a std::error_code.
65 ///
66 /// This is a temporary crutch to enable interaction with code still
67 /// using std::error_code. It will be removed in the future.
68 virtual std::error_code convertToErrorCode() const = 0;
69
70 // Returns the class ID for this type.
71 static const void *classID() { return &ID; }
72
73 // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
74 virtual const void *dynamicClassID() const = 0;
75
76 // Check whether this instance is a subclass of the class identified by
77 // ClassID.
78 virtual bool isA(const void *const ClassID) const {
79 return ClassID == classID();
80 }
81
82 // Check whether this instance is a subclass of ErrorInfoT.
83 template <typename ErrorInfoT> bool isA() const {
84 return isA(ErrorInfoT::classID());
85 }
86
87private:
88 virtual void anchor();
89
90 static char ID;
91};
92
93/// Lightweight error class with error context and mandatory checking.
94///
95/// Instances of this class wrap a ErrorInfoBase pointer. Failure states
96/// are represented by setting the pointer to a ErrorInfoBase subclass
97/// instance containing information describing the failure. Success is
98/// represented by a null pointer value.
99///
100/// Instances of Error also contains a 'Checked' flag, which must be set
101/// before the destructor is called, otherwise the destructor will trigger a
102/// runtime error. This enforces at runtime the requirement that all Error
103/// instances be checked or returned to the caller.
104///
105/// There are two ways to set the checked flag, depending on what state the
106/// Error instance is in. For Error instances indicating success, it
107/// is sufficient to invoke the boolean conversion operator. E.g.:
108///
109/// @code{.cpp}
110/// Error foo(<...>);
111///
112/// if (auto E = foo(<...>))
113/// return E; // <- Return E if it is in the error state.
114/// // We have verified that E was in the success state. It can now be safely
115/// // destroyed.
116/// @endcode
117///
118/// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
119/// without testing the return value will raise a runtime error, even if foo
120/// returns success.
121///
122/// For Error instances representing failure, you must use either the
123/// handleErrors or handleAllErrors function with a typed handler. E.g.:
124///
125/// @code{.cpp}
126/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
127/// // Custom error info.
128/// };
129///
130/// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
131///
132/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
133/// auto NewE =
134/// handleErrors(E,
135/// [](const MyErrorInfo &M) {
136/// // Deal with the error.
137/// },
138/// [](std::unique_ptr<OtherError> M) -> Error {
139/// if (canHandle(*M)) {
140/// // handle error.
141/// return Error::success();
142/// }
143/// // Couldn't handle this error instance. Pass it up the stack.
144/// return Error(std::move(M));
145/// );
146/// // Note - we must check or return NewE in case any of the handlers
147/// // returned a new error.
148/// @endcode
149///
150/// The handleAllErrors function is identical to handleErrors, except
151/// that it has a void return type, and requires all errors to be handled and
152/// no new errors be returned. It prevents errors (assuming they can all be
153/// handled) from having to be bubbled all the way to the top-level.
154///
155/// *All* Error instances must be checked before destruction, even if
156/// they're moved-assigned or constructed from Success values that have already
157/// been checked. This enforces checking through all levels of the call stack.
158class LLVM_NODISCARD[[clang::warn_unused_result]] Error {
159 // Both ErrorList and FileError need to be able to yank ErrorInfoBase
160 // pointers out of this class to add to the error list.
161 friend class ErrorList;
162 friend class FileError;
163
164 // handleErrors needs to be able to set the Checked flag.
165 template <typename... HandlerTs>
166 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
167
168 // Expected<T> needs to be able to steal the payload when constructed from an
169 // error.
170 template <typename T> friend class Expected;
171
172 // wrap needs to be able to steal the payload.
173 friend LLVMErrorRef wrap(Error);
174
175protected:
176 /// Create a success value. Prefer using 'Error::success()' for readability
177 Error() {
178 setPtr(nullptr);
179 setChecked(false);
180 }
181
182public:
183 /// Create a success value.
184 static ErrorSuccess success();
185
186 // Errors are not copy-constructable.
187 Error(const Error &Other) = delete;
188
189 /// Move-construct an error value. The newly constructed error is considered
190 /// unchecked, even if the source error had been checked. The original error
191 /// becomes a checked Success value, regardless of its original state.
192 Error(Error &&Other) {
193 setChecked(true);
194 *this = std::move(Other);
195 }
196
197 /// Create an error value. Prefer using the 'make_error' function, but
198 /// this constructor can be useful when "re-throwing" errors from handlers.
199 Error(std::unique_ptr<ErrorInfoBase> Payload) {
200 setPtr(Payload.release());
201 setChecked(false);
27
Potential leak of memory pointed to by 'Payload._M_t._M_head_impl'
202 }
203
204 // Errors are not copy-assignable.
205 Error &operator=(const Error &Other) = delete;
206
207 /// Move-assign an error value. The current error must represent success, you
208 /// you cannot overwrite an unhandled error. The current error is then
209 /// considered unchecked. The source error becomes a checked success value,
210 /// regardless of its original state.
211 Error &operator=(Error &&Other) {
212 // Don't allow overwriting of unchecked values.
213 assertIsChecked();
214 setPtr(Other.getPtr());
215
216 // This Error is unchecked, even if the source error was checked.
217 setChecked(false);
218
219 // Null out Other's payload and set its checked bit.
220 Other.setPtr(nullptr);
221 Other.setChecked(true);
222
223 return *this;
224 }
225
226 /// Destroy a Error. Fails with a call to abort() if the error is
227 /// unchecked.
228 ~Error() {
229 assertIsChecked();
230 delete getPtr();
231 }
232
233 /// Bool conversion. Returns true if this Error is in a failure state,
234 /// and false if it is in an accept state. If the error is in a Success state
235 /// it will be considered checked.
236 explicit operator bool() {
237 setChecked(getPtr() == nullptr);
238 return getPtr() != nullptr;
239 }
240
241 /// Check whether one error is a subclass of another.
242 template <typename ErrT> bool isA() const {
243 return getPtr() && getPtr()->isA(ErrT::classID());
244 }
245
246 /// Returns the dynamic class id of this error, or null if this is a success
247 /// value.
248 const void* dynamicClassID() const {
249 if (!getPtr())
250 return nullptr;
251 return getPtr()->dynamicClassID();
252 }
253
254private:
255#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
256 // assertIsChecked() happens very frequently, but under normal circumstances
257 // is supposed to be a no-op. So we want it to be inlined, but having a bunch
258 // of debug prints can cause the function to be too large for inlining. So
259 // it's important that we define this function out of line so that it can't be
260 // inlined.
261 LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn))
262 void fatalUncheckedError() const;
263#endif
264
265 void assertIsChecked() {
266#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
267 if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false))
268 fatalUncheckedError();
269#endif
270 }
271
272 ErrorInfoBase *getPtr() const {
273 return reinterpret_cast<ErrorInfoBase*>(
274 reinterpret_cast<uintptr_t>(Payload) &
275 ~static_cast<uintptr_t>(0x1));
276 }
277
278 void setPtr(ErrorInfoBase *EI) {
279#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
280 Payload = reinterpret_cast<ErrorInfoBase*>(
281 (reinterpret_cast<uintptr_t>(EI) &
282 ~static_cast<uintptr_t>(0x1)) |
283 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
284#else
285 Payload = EI;
286#endif
287 }
288
289 bool getChecked() const {
290#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
291 return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
292#else
293 return true;
294#endif
295 }
296
297 void setChecked(bool V) {
298 Payload = reinterpret_cast<ErrorInfoBase*>(
299 (reinterpret_cast<uintptr_t>(Payload) &
300 ~static_cast<uintptr_t>(0x1)) |
301 (V ? 0 : 1));
302 }
303
304 std::unique_ptr<ErrorInfoBase> takePayload() {
305 std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
306 setPtr(nullptr);
307 setChecked(true);
308 return Tmp;
309 }
310
311 friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
312 if (auto P = E.getPtr())
313 P->log(OS);
314 else
315 OS << "success";
316 return OS;
317 }
318
319 ErrorInfoBase *Payload = nullptr;
320};
321
322/// Subclass of Error for the sole purpose of identifying the success path in
323/// the type system. This allows to catch invalid conversion to Expected<T> at
324/// compile time.
325class ErrorSuccess final : public Error {};
326
327inline ErrorSuccess Error::success() { return ErrorSuccess(); }
328
329/// Make a Error instance representing failure using the given error info
330/// type.
331template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
332 return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
333}
334
335/// Base class for user error types. Users should declare their error types
336/// like:
337///
338/// class MyError : public ErrorInfo<MyError> {
339/// ....
340/// };
341///
342/// This class provides an implementation of the ErrorInfoBase::kind
343/// method, which is used by the Error RTTI system.
344template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
345class ErrorInfo : public ParentErrT {
346public:
347 using ParentErrT::ParentErrT; // inherit constructors
348
349 static const void *classID() { return &ThisErrT::ID; }
350
351 const void *dynamicClassID() const override { return &ThisErrT::ID; }
352
353 bool isA(const void *const ClassID) const override {
354 return ClassID == classID() || ParentErrT::isA(ClassID);
355 }
356};
357
358/// Special ErrorInfo subclass representing a list of ErrorInfos.
359/// Instances of this class are constructed by joinError.
360class ErrorList final : public ErrorInfo<ErrorList> {
361 // handleErrors needs to be able to iterate the payload list of an
362 // ErrorList.
363 template <typename... HandlerTs>
364 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
365
366 // joinErrors is implemented in terms of join.
367 friend Error joinErrors(Error, Error);
368
369public:
370 void log(raw_ostream &OS) const override {
371 OS << "Multiple errors:\n";
372 for (auto &ErrPayload : Payloads) {
373 ErrPayload->log(OS);
374 OS << "\n";
375 }
376 }
377
378 std::error_code convertToErrorCode() const override;
379
380 // Used by ErrorInfo::classID.
381 static char ID;
382
383private:
384 ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
385 std::unique_ptr<ErrorInfoBase> Payload2) {
386 assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&((!Payload1->isA<ErrorList>() && !Payload2->
isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors"
) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 387, __PRETTY_FUNCTION__))
387 "ErrorList constructor payloads should be singleton errors")((!Payload1->isA<ErrorList>() && !Payload2->
isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors"
) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 387, __PRETTY_FUNCTION__))
;
388 Payloads.push_back(std::move(Payload1));
389 Payloads.push_back(std::move(Payload2));
390 }
391
392 static Error join(Error E1, Error E2) {
393 if (!E1)
19
Taking false branch
394 return E2;
395 if (!E2)
20
Taking false branch
396 return E1;
397 if (E1.isA<ErrorList>()) {
21
Assuming the condition is false
22
Taking false branch
398 auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
399 if (E2.isA<ErrorList>()) {
400 auto E2Payload = E2.takePayload();
401 auto &E2List = static_cast<ErrorList &>(*E2Payload);
402 for (auto &Payload : E2List.Payloads)
403 E1List.Payloads.push_back(std::move(Payload));
404 } else
405 E1List.Payloads.push_back(E2.takePayload());
406
407 return E1;
408 }
409 if (E2.isA<ErrorList>()) {
23
Assuming the condition is false
24
Taking false branch
410 auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
411 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
412 return E2;
413 }
414 return Error(std::unique_ptr<ErrorList>(
26
Calling constructor for 'Error'
415 new ErrorList(E1.takePayload(), E2.takePayload())));
25
Memory is allocated
416 }
417
418 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
419};
420
421/// Concatenate errors. The resulting Error is unchecked, and contains the
422/// ErrorInfo(s), if any, contained in E1, followed by the
423/// ErrorInfo(s), if any, contained in E2.
424inline Error joinErrors(Error E1, Error E2) {
425 return ErrorList::join(std::move(E1), std::move(E2));
426}
427
428/// Tagged union holding either a T or a Error.
429///
430/// This class parallels ErrorOr, but replaces error_code with Error. Since
431/// Error cannot be copied, this class replaces getError() with
432/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
433/// error class type.
434template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected {
435 template <class T1> friend class ExpectedAsOutParameter;
436 template <class OtherT> friend class Expected;
437
438 static const bool isRef = std::is_reference<T>::value;
439
440 using wrap = std::reference_wrapper<typename std::remove_reference<T>::type>;
441
442 using error_type = std::unique_ptr<ErrorInfoBase>;
443
444public:
445 using storage_type = typename std::conditional<isRef, wrap, T>::type;
446 using value_type = T;
447
448private:
449 using reference = typename std::remove_reference<T>::type &;
450 using const_reference = const typename std::remove_reference<T>::type &;
451 using pointer = typename std::remove_reference<T>::type *;
452 using const_pointer = const typename std::remove_reference<T>::type *;
453
454public:
455 /// Create an Expected<T> error value from the given Error.
456 Expected(Error Err)
457 : HasError(true)
458#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
459 // Expected is unchecked upon construction in Debug builds.
460 , Unchecked(true)
461#endif
462 {
463 assert(Err && "Cannot create Expected<T> from Error success value.")((Err && "Cannot create Expected<T> from Error success value."
) ? static_cast<void> (0) : __assert_fail ("Err && \"Cannot create Expected<T> from Error success value.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 463, __PRETTY_FUNCTION__))
;
464 new (getErrorStorage()) error_type(Err.takePayload());
465 }
466
467 /// Forbid to convert from Error::success() implicitly, this avoids having
468 /// Expected<T> foo() { return Error::success(); } which compiles otherwise
469 /// but triggers the assertion above.
470 Expected(ErrorSuccess) = delete;
471
472 /// Create an Expected<T> success value from the given OtherT value, which
473 /// must be convertible to T.
474 template <typename OtherT>
475 Expected(OtherT &&Val,
476 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
477 * = nullptr)
478 : HasError(false)
479#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
480 // Expected is unchecked upon construction in Debug builds.
481 , Unchecked(true)
482#endif
483 {
484 new (getStorage()) storage_type(std::forward<OtherT>(Val));
485 }
486
487 /// Move construct an Expected<T> value.
488 Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
489
490 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
491 /// must be convertible to T.
492 template <class OtherT>
493 Expected(Expected<OtherT> &&Other,
494 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
495 * = nullptr) {
496 moveConstruct(std::move(Other));
497 }
498
499 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
500 /// isn't convertible to T.
501 template <class OtherT>
502 explicit Expected(
503 Expected<OtherT> &&Other,
504 typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * =
505 nullptr) {
506 moveConstruct(std::move(Other));
507 }
508
509 /// Move-assign from another Expected<T>.
510 Expected &operator=(Expected &&Other) {
511 moveAssign(std::move(Other));
512 return *this;
513 }
514
515 /// Destroy an Expected<T>.
516 ~Expected() {
517 assertIsChecked();
518 if (!HasError)
519 getStorage()->~storage_type();
520 else
521 getErrorStorage()->~error_type();
522 }
523
524 /// Return false if there is an error.
525 explicit operator bool() {
526#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
527 Unchecked = HasError;
528#endif
529 return !HasError;
530 }
531
532 /// Returns a reference to the stored T value.
533 reference get() {
534 assertIsChecked();
535 return *getStorage();
536 }
537
538 /// Returns a const reference to the stored T value.
539 const_reference get() const {
540 assertIsChecked();
541 return const_cast<Expected<T> *>(this)->get();
542 }
543
544 /// Check that this Expected<T> is an error of type ErrT.
545 template <typename ErrT> bool errorIsA() const {
546 return HasError && (*getErrorStorage())->template isA<ErrT>();
547 }
548
549 /// Take ownership of the stored error.
550 /// After calling this the Expected<T> is in an indeterminate state that can
551 /// only be safely destructed. No further calls (beside the destructor) should
552 /// be made on the Expected<T> vaule.
553 Error takeError() {
554#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
555 Unchecked = false;
556#endif
557 return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
558 }
559
560 /// Returns a pointer to the stored T value.
561 pointer operator->() {
562 assertIsChecked();
563 return toPointer(getStorage());
564 }
565
566 /// Returns a const pointer to the stored T value.
567 const_pointer operator->() const {
568 assertIsChecked();
569 return toPointer(getStorage());
570 }
571
572 /// Returns a reference to the stored T value.
573 reference operator*() {
574 assertIsChecked();
575 return *getStorage();
576 }
577
578 /// Returns a const reference to the stored T value.
579 const_reference operator*() const {
580 assertIsChecked();
581 return *getStorage();
582 }
583
584private:
585 template <class T1>
586 static bool compareThisIfSameType(const T1 &a, const T1 &b) {
587 return &a == &b;
588 }
589
590 template <class T1, class T2>
591 static bool compareThisIfSameType(const T1 &a, const T2 &b) {
592 return false;
593 }
594
595 template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
596 HasError = Other.HasError;
597#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
598 Unchecked = true;
599 Other.Unchecked = false;
600#endif
601
602 if (!HasError)
603 new (getStorage()) storage_type(std::move(*Other.getStorage()));
604 else
605 new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
606 }
607
608 template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
609 assertIsChecked();
610
611 if (compareThisIfSameType(*this, Other))
612 return;
613
614 this->~Expected();
615 new (this) Expected(std::move(Other));
616 }
617
618 pointer toPointer(pointer Val) { return Val; }
619
620 const_pointer toPointer(const_pointer Val) const { return Val; }
621
622 pointer toPointer(wrap *Val) { return &Val->get(); }
623
624 const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
625
626 storage_type *getStorage() {
627 assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!"
) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 627, __PRETTY_FUNCTION__))
;
628 return reinterpret_cast<storage_type *>(TStorage.buffer);
629 }
630
631 const storage_type *getStorage() const {
632 assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!"
) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 632, __PRETTY_FUNCTION__))
;
633 return reinterpret_cast<const storage_type *>(TStorage.buffer);
634 }
635
636 error_type *getErrorStorage() {
637 assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!"
) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 637, __PRETTY_FUNCTION__))
;
638 return reinterpret_cast<error_type *>(ErrorStorage.buffer);
639 }
640
641 const error_type *getErrorStorage() const {
642 assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!"
) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 642, __PRETTY_FUNCTION__))
;
643 return reinterpret_cast<const error_type *>(ErrorStorage.buffer);
644 }
645
646 // Used by ExpectedAsOutParameter to reset the checked flag.
647 void setUnchecked() {
648#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
649 Unchecked = true;
650#endif
651 }
652
653#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
654 LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn))
655 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline))
656 void fatalUncheckedExpected() const {
657 dbgs() << "Expected<T> must be checked before access or destruction.\n";
658 if (HasError) {
659 dbgs() << "Unchecked Expected<T> contained error:\n";
660 (*getErrorStorage())->log(dbgs());
661 } else
662 dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
663 "values in success mode must still be checked prior to being "
664 "destroyed).\n";
665 abort();
666 }
667#endif
668
669 void assertIsChecked() {
670#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
671 if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false))
672 fatalUncheckedExpected();
673#endif
674 }
675
676 union {
677 AlignedCharArrayUnion<storage_type> TStorage;
678 AlignedCharArrayUnion<error_type> ErrorStorage;
679 };
680 bool HasError : 1;
681#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
682 bool Unchecked : 1;
683#endif
684};
685
686/// Report a serious error, calling any installed error handler. See
687/// ErrorHandling.h.
688LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void report_fatal_error(Error Err,
689 bool gen_crash_diag = true);
690
691/// Report a fatal error if Err is a failure value.
692///
693/// This function can be used to wrap calls to fallible functions ONLY when it
694/// is known that the Error will always be a success value. E.g.
695///
696/// @code{.cpp}
697/// // foo only attempts the fallible operation if DoFallibleOperation is
698/// // true. If DoFallibleOperation is false then foo always returns
699/// // Error::success().
700/// Error foo(bool DoFallibleOperation);
701///
702/// cantFail(foo(false));
703/// @endcode
704inline void cantFail(Error Err, const char *Msg = nullptr) {
705 if (Err) {
706 if (!Msg)
707 Msg = "Failure value returned from cantFail wrapped call";
708 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 708)
;
709 }
710}
711
712/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
713/// returns the contained value.
714///
715/// This function can be used to wrap calls to fallible functions ONLY when it
716/// is known that the Error will always be a success value. E.g.
717///
718/// @code{.cpp}
719/// // foo only attempts the fallible operation if DoFallibleOperation is
720/// // true. If DoFallibleOperation is false then foo always returns an int.
721/// Expected<int> foo(bool DoFallibleOperation);
722///
723/// int X = cantFail(foo(false));
724/// @endcode
725template <typename T>
726T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
727 if (ValOrErr)
728 return std::move(*ValOrErr);
729 else {
730 if (!Msg)
731 Msg = "Failure value returned from cantFail wrapped call";
732 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 732)
;
733 }
734}
735
736/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
737/// returns the contained reference.
738///
739/// This function can be used to wrap calls to fallible functions ONLY when it
740/// is known that the Error will always be a success value. E.g.
741///
742/// @code{.cpp}
743/// // foo only attempts the fallible operation if DoFallibleOperation is
744/// // true. If DoFallibleOperation is false then foo always returns a Bar&.
745/// Expected<Bar&> foo(bool DoFallibleOperation);
746///
747/// Bar &X = cantFail(foo(false));
748/// @endcode
749template <typename T>
750T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
751 if (ValOrErr)
752 return *ValOrErr;
753 else {
754 if (!Msg)
755 Msg = "Failure value returned from cantFail wrapped call";
756 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 756)
;
757 }
758}
759
760/// Helper for testing applicability of, and applying, handlers for
761/// ErrorInfo types.
762template <typename HandlerT>
763class ErrorHandlerTraits
764 : public ErrorHandlerTraits<decltype(
765 &std::remove_reference<HandlerT>::type::operator())> {};
766
767// Specialization functions of the form 'Error (const ErrT&)'.
768template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
769public:
770 static bool appliesTo(const ErrorInfoBase &E) {
771 return E.template isA<ErrT>();
772 }
773
774 template <typename HandlerT>
775 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
776 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 776, __PRETTY_FUNCTION__))
;
777 return H(static_cast<ErrT &>(*E));
778 }
779};
780
781// Specialization functions of the form 'void (const ErrT&)'.
782template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
783public:
784 static bool appliesTo(const ErrorInfoBase &E) {
785 return E.template isA<ErrT>();
786 }
787
788 template <typename HandlerT>
789 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
790 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 790, __PRETTY_FUNCTION__))
;
791 H(static_cast<ErrT &>(*E));
792 return Error::success();
793 }
794};
795
796/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
797template <typename ErrT>
798class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
799public:
800 static bool appliesTo(const ErrorInfoBase &E) {
801 return E.template isA<ErrT>();
802 }
803
804 template <typename HandlerT>
805 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
806 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 806, __PRETTY_FUNCTION__))
;
807 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
808 return H(std::move(SubE));
809 }
810};
811
812/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
813template <typename ErrT>
814class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
815public:
816 static bool appliesTo(const ErrorInfoBase &E) {
817 return E.template isA<ErrT>();
818 }
819
820 template <typename HandlerT>
821 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
822 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 822, __PRETTY_FUNCTION__))
;
823 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
824 H(std::move(SubE));
825 return Error::success();
826 }
827};
828
829// Specialization for member functions of the form 'RetT (const ErrT&)'.
830template <typename C, typename RetT, typename ErrT>
831class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
832 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
833
834// Specialization for member functions of the form 'RetT (const ErrT&) const'.
835template <typename C, typename RetT, typename ErrT>
836class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
837 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
838
839// Specialization for member functions of the form 'RetT (const ErrT&)'.
840template <typename C, typename RetT, typename ErrT>
841class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
842 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
843
844// Specialization for member functions of the form 'RetT (const ErrT&) const'.
845template <typename C, typename RetT, typename ErrT>
846class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
847 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
848
849/// Specialization for member functions of the form
850/// 'RetT (std::unique_ptr<ErrT>)'.
851template <typename C, typename RetT, typename ErrT>
852class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
853 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
854
855/// Specialization for member functions of the form
856/// 'RetT (std::unique_ptr<ErrT>) const'.
857template <typename C, typename RetT, typename ErrT>
858class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
859 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
860
861inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
862 return Error(std::move(Payload));
863}
864
865template <typename HandlerT, typename... HandlerTs>
866Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
867 HandlerT &&Handler, HandlerTs &&... Handlers) {
868 if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
869 return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
870 std::move(Payload));
871 return handleErrorImpl(std::move(Payload),
872 std::forward<HandlerTs>(Handlers)...);
873}
874
875/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
876/// unhandled errors (or Errors returned by handlers) are re-concatenated and
877/// returned.
878/// Because this function returns an error, its result must also be checked
879/// or returned. If you intend to handle all errors use handleAllErrors
880/// (which returns void, and will abort() on unhandled errors) instead.
881template <typename... HandlerTs>
882Error handleErrors(Error E, HandlerTs &&... Hs) {
883 if (!E)
15
Taking false branch
884 return Error::success();
885
886 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
887
888 if (Payload->isA<ErrorList>()) {
16
Assuming the condition is true
17
Taking true branch
889 ErrorList &List = static_cast<ErrorList &>(*Payload);
890 Error R;
891 for (auto &P : List.Payloads)
892 R = ErrorList::join(
18
Calling 'ErrorList::join'
893 std::move(R),
894 handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
895 return R;
896 }
897
898 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
899}
900
901/// Behaves the same as handleErrors, except that by contract all errors
902/// *must* be handled by the given handlers (i.e. there must be no remaining
903/// errors after running the handlers, or llvm_unreachable is called).
904template <typename... HandlerTs>
905void handleAllErrors(Error E, HandlerTs &&... Handlers) {
906 cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
14
Calling 'handleErrors<(lambda at /build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h:983:35)>'
907}
908
909/// Check that E is a non-error, then drop it.
910/// If E is an error, llvm_unreachable will be called.
911inline void handleAllErrors(Error E) {
912 cantFail(std::move(E));
913}
914
915/// Handle any errors (if present) in an Expected<T>, then try a recovery path.
916///
917/// If the incoming value is a success value it is returned unmodified. If it
918/// is a failure value then it the contained error is passed to handleErrors.
919/// If handleErrors is able to handle the error then the RecoveryPath functor
920/// is called to supply the final result. If handleErrors is not able to
921/// handle all errors then the unhandled errors are returned.
922///
923/// This utility enables the follow pattern:
924///
925/// @code{.cpp}
926/// enum FooStrategy { Aggressive, Conservative };
927/// Expected<Foo> foo(FooStrategy S);
928///
929/// auto ResultOrErr =
930/// handleExpected(
931/// foo(Aggressive),
932/// []() { return foo(Conservative); },
933/// [](AggressiveStrategyError&) {
934/// // Implicitly conusme this - we'll recover by using a conservative
935/// // strategy.
936/// });
937///
938/// @endcode
939template <typename T, typename RecoveryFtor, typename... HandlerTs>
940Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
941 HandlerTs &&... Handlers) {
942 if (ValOrErr)
943 return ValOrErr;
944
945 if (auto Err = handleErrors(ValOrErr.takeError(),
946 std::forward<HandlerTs>(Handlers)...))
947 return std::move(Err);
948
949 return RecoveryPath();
950}
951
952/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
953/// will be printed before the first one is logged. A newline will be printed
954/// after each error.
955///
956/// This function is compatible with the helpers from Support/WithColor.h. You
957/// can pass any of them as the OS. Please consider using them instead of
958/// including 'error: ' in the ErrorBanner.
959///
960/// This is useful in the base level of your program to allow clean termination
961/// (allowing clean deallocation of resources, etc.), while reporting error
962/// information to the user.
963void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {});
964
965/// Write all error messages (if any) in E to a string. The newline character
966/// is used to separate error messages.
967inline std::string toString(Error E) {
968 SmallVector<std::string, 2> Errors;
969 handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
970 Errors.push_back(EI.message());
971 });
972 return join(Errors.begin(), Errors.end(), "\n");
973}
974
975/// Consume a Error without doing anything. This method should be used
976/// only where an error can be considered a reasonable and expected return
977/// value.
978///
979/// Uses of this method are potentially indicative of design problems: If it's
980/// legitimate to do nothing while processing an "error", the error-producer
981/// might be more clearly refactored to return an Optional<T>.
982inline void consumeError(Error Err) {
983 handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
13
Calling 'handleAllErrors<(lambda at /build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h:983:35)>'
984}
985
986/// Helper for converting an Error to a bool.
987///
988/// This method returns true if Err is in an error state, or false if it is
989/// in a success state. Puts Err in a checked state in both cases (unlike
990/// Error::operator bool(), which only does this for success states).
991inline bool errorToBool(Error Err) {
992 bool IsError = static_cast<bool>(Err);
993 if (IsError)
994 consumeError(std::move(Err));
995 return IsError;
996}
997
998/// Helper for Errors used as out-parameters.
999///
1000/// This helper is for use with the Error-as-out-parameter idiom, where an error
1001/// is passed to a function or method by reference, rather than being returned.
1002/// In such cases it is helpful to set the checked bit on entry to the function
1003/// so that the error can be written to (unchecked Errors abort on assignment)
1004/// and clear the checked bit on exit so that clients cannot accidentally forget
1005/// to check the result. This helper performs these actions automatically using
1006/// RAII:
1007///
1008/// @code{.cpp}
1009/// Result foo(Error &Err) {
1010/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
1011/// // <body of foo>
1012/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
1013/// }
1014/// @endcode
1015///
1016/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
1017/// used with optional Errors (Error pointers that are allowed to be null). If
1018/// ErrorAsOutParameter took an Error reference, an instance would have to be
1019/// created inside every condition that verified that Error was non-null. By
1020/// taking an Error pointer we can just create one instance at the top of the
1021/// function.
1022class ErrorAsOutParameter {
1023public:
1024 ErrorAsOutParameter(Error *Err) : Err(Err) {
1025 // Raise the checked bit if Err is success.
1026 if (Err)
1027 (void)!!*Err;
1028 }
1029
1030 ~ErrorAsOutParameter() {
1031 // Clear the checked bit.
1032 if (Err && !*Err)
1033 *Err = Error::success();
1034 }
1035
1036private:
1037 Error *Err;
1038};
1039
1040/// Helper for Expected<T>s used as out-parameters.
1041///
1042/// See ErrorAsOutParameter.
1043template <typename T>
1044class ExpectedAsOutParameter {
1045public:
1046 ExpectedAsOutParameter(Expected<T> *ValOrErr)
1047 : ValOrErr(ValOrErr) {
1048 if (ValOrErr)
1049 (void)!!*ValOrErr;
1050 }
1051
1052 ~ExpectedAsOutParameter() {
1053 if (ValOrErr)
1054 ValOrErr->setUnchecked();
1055 }
1056
1057private:
1058 Expected<T> *ValOrErr;
1059};
1060
1061/// This class wraps a std::error_code in a Error.
1062///
1063/// This is useful if you're writing an interface that returns a Error
1064/// (or Expected) and you want to call code that still returns
1065/// std::error_codes.
1066class ECError : public ErrorInfo<ECError> {
1067 friend Error errorCodeToError(std::error_code);
1068
1069public:
1070 void setErrorCode(std::error_code EC) { this->EC = EC; }
1071 std::error_code convertToErrorCode() const override { return EC; }
1072 void log(raw_ostream &OS) const override { OS << EC.message(); }
1073
1074 // Used by ErrorInfo::classID.
1075 static char ID;
1076
1077protected:
1078 ECError() = default;
1079 ECError(std::error_code EC) : EC(EC) {}
1080
1081 std::error_code EC;
1082};
1083
1084/// The value returned by this function can be returned from convertToErrorCode
1085/// for Error values where no sensible translation to std::error_code exists.
1086/// It should only be used in this situation, and should never be used where a
1087/// sensible conversion to std::error_code is available, as attempts to convert
1088/// to/from this error will result in a fatal error. (i.e. it is a programmatic
1089///error to try to convert such a value).
1090std::error_code inconvertibleErrorCode();
1091
1092/// Helper for converting an std::error_code to a Error.
1093Error errorCodeToError(std::error_code EC);
1094
1095/// Helper for converting an ECError to a std::error_code.
1096///
1097/// This method requires that Err be Error() or an ECError, otherwise it
1098/// will trigger a call to abort().
1099std::error_code errorToErrorCode(Error Err);
1100
1101/// Convert an ErrorOr<T> to an Expected<T>.
1102template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1103 if (auto EC = EO.getError())
1104 return errorCodeToError(EC);
1105 return std::move(*EO);
1106}
1107
1108/// Convert an Expected<T> to an ErrorOr<T>.
1109template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1110 if (auto Err = E.takeError())
1111 return errorToErrorCode(std::move(Err));
1112 return std::move(*E);
1113}
1114
1115/// This class wraps a string in an Error.
1116///
1117/// StringError is useful in cases where the client is not expected to be able
1118/// to consume the specific error message programmatically (for example, if the
1119/// error message is to be presented to the user).
1120///
1121/// StringError can also be used when additional information is to be printed
1122/// along with a error_code message. Depending on the constructor called, this
1123/// class can either display:
1124/// 1. the error_code message (ECError behavior)
1125/// 2. a string
1126/// 3. the error_code message and a string
1127///
1128/// These behaviors are useful when subtyping is required; for example, when a
1129/// specific library needs an explicit error type. In the example below,
1130/// PDBError is derived from StringError:
1131///
1132/// @code{.cpp}
1133/// Expected<int> foo() {
1134/// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading,
1135/// "Additional information");
1136/// }
1137/// @endcode
1138///
1139class StringError : public ErrorInfo<StringError> {
1140public:
1141 static char ID;
1142
1143 // Prints EC + S and converts to EC
1144 StringError(std::error_code EC, const Twine &S = Twine());
1145
1146 // Prints S and converts to EC
1147 StringError(const Twine &S, std::error_code EC);
1148
1149 void log(raw_ostream &OS) const override;
1150 std::error_code convertToErrorCode() const override;
1151
1152 const std::string &getMessage() const { return Msg; }
1153
1154private:
1155 std::string Msg;
1156 std::error_code EC;
1157 const bool PrintMsgOnly = false;
1158};
1159
1160/// Create formatted StringError object.
1161template <typename... Ts>
1162Error createStringError(std::error_code EC, char const *Fmt,
1163 const Ts &... Vals) {
1164 std::string Buffer;
1165 raw_string_ostream Stream(Buffer);
1166 Stream << format(Fmt, Vals...);
1167 return make_error<StringError>(Stream.str(), EC);
1168}
1169
1170Error createStringError(std::error_code EC, char const *Msg);
1171
1172/// This class wraps a filename and another Error.
1173///
1174/// In some cases, an error needs to live along a 'source' name, in order to
1175/// show more detailed information to the user.
1176class FileError final : public ErrorInfo<FileError> {
1177
1178 friend Error createFileError(std::string, Error);
1179
1180public:
1181 void log(raw_ostream &OS) const override {
1182 assert(Err && !FileName.empty() && "Trying to log after takeError().")((Err && !FileName.empty() && "Trying to log after takeError()."
) ? static_cast<void> (0) : __assert_fail ("Err && !FileName.empty() && \"Trying to log after takeError().\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 1182, __PRETTY_FUNCTION__))
;
1183 OS << "'" << FileName << "': ";
1184 Err->log(OS);
1185 }
1186
1187 Error takeError() { return Error(std::move(Err)); }
1188
1189 std::error_code convertToErrorCode() const override;
1190
1191 // Used by ErrorInfo::classID.
1192 static char ID;
1193
1194private:
1195 FileError(std::string F, std::unique_ptr<ErrorInfoBase> E) {
1196 assert(E && "Cannot create FileError from Error success value.")((E && "Cannot create FileError from Error success value."
) ? static_cast<void> (0) : __assert_fail ("E && \"Cannot create FileError from Error success value.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 1196, __PRETTY_FUNCTION__))
;
1197 assert(!F.empty() &&((!F.empty() && "The file name provided to FileError must not be empty."
) ? static_cast<void> (0) : __assert_fail ("!F.empty() && \"The file name provided to FileError must not be empty.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 1198, __PRETTY_FUNCTION__))
1198 "The file name provided to FileError must not be empty.")((!F.empty() && "The file name provided to FileError must not be empty."
) ? static_cast<void> (0) : __assert_fail ("!F.empty() && \"The file name provided to FileError must not be empty.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/include/llvm/Support/Error.h"
, 1198, __PRETTY_FUNCTION__))
;
1199 FileName = F;
1200 Err = std::move(E);
1201 }
1202
1203 static Error build(std::string F, Error E) {
1204 return Error(std::unique_ptr<FileError>(new FileError(F, E.takePayload())));
1205 }
1206
1207 std::string FileName;
1208 std::unique_ptr<ErrorInfoBase> Err;
1209};
1210
1211/// Concatenate a source file path and/or name with an Error. The resulting
1212/// Error is unchecked.
1213inline Error createFileError(std::string F, Error E) {
1214 return FileError::build(F, std::move(E));
1215}
1216
1217Error createFileError(std::string F, ErrorSuccess) = delete;
1218
1219/// Helper for check-and-exit error handling.
1220///
1221/// For tool use only. NOT FOR USE IN LIBRARY CODE.
1222///
1223class ExitOnError {
1224public:
1225 /// Create an error on exit helper.
1226 ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1227 : Banner(std::move(Banner)),
1228 GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1229
1230 /// Set the banner string for any errors caught by operator().
1231 void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1232
1233 /// Set the exit-code mapper function.
1234 void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1235 this->GetExitCode = std::move(GetExitCode);
1236 }
1237
1238 /// Check Err. If it's in a failure state log the error(s) and exit.
1239 void operator()(Error Err) const { checkError(std::move(Err)); }
1240
1241 /// Check E. If it's in a success state then return the contained value. If
1242 /// it's in a failure state log the error(s) and exit.
1243 template <typename T> T operator()(Expected<T> &&E) const {
1244 checkError(E.takeError());
1245 return std::move(*E);
1246 }
1247
1248 /// Check E. If it's in a success state then return the contained reference. If
1249 /// it's in a failure state log the error(s) and exit.
1250 template <typename T> T& operator()(Expected<T&> &&E) const {
1251 checkError(E.takeError());
1252 return *E;
1253 }
1254
1255private:
1256 void checkError(Error Err) const {
1257 if (Err) {
1258 int ExitCode = GetExitCode(Err);
1259 logAllUnhandledErrors(std::move(Err), errs(), Banner);
1260 exit(ExitCode);
1261 }
1262 }
1263
1264 std::string Banner;
1265 std::function<int(const Error &)> GetExitCode;
1266};
1267
1268/// Conversion from Error to LLVMErrorRef for C error bindings.
1269inline LLVMErrorRef wrap(Error Err) {
1270 return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
1271}
1272
1273/// Conversion from LLVMErrorRef to Error for C error bindings.
1274inline Error unwrap(LLVMErrorRef ErrRef) {
1275 return Error(std::unique_ptr<ErrorInfoBase>(
1276 reinterpret_cast<ErrorInfoBase *>(ErrRef)));
1277}
1278
1279} // end namespace llvm
1280
1281#endif // LLVM_SUPPORT_ERROR_H