File: | include/llvm/Support/Error.h |
Warning: | line 200, column 5 Potential leak of memory pointed to by 'Payload._M_t._M_head_impl' |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- Darwin.cpp - Darwin Tool and ToolChain Implementations -*- C++ -*-===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | ||||
9 | #include "Darwin.h" | |||
10 | #include "Arch/ARM.h" | |||
11 | #include "CommonArgs.h" | |||
12 | #include "clang/Basic/AlignedAllocation.h" | |||
13 | #include "clang/Basic/ObjCRuntime.h" | |||
14 | #include "clang/Config/config.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 | ||||
28 | using namespace clang::driver; | |||
29 | using namespace clang::driver::tools; | |||
30 | using namespace clang::driver::toolchains; | |||
31 | using namespace clang; | |||
32 | using namespace llvm::opt; | |||
33 | ||||
34 | llvm::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 | ||||
69 | void 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 | ||||
84 | void 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-9~svn362543/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-9~svn362543/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-9~svn362543/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-9~svn362543/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 | ||||
152 | void darwin::MachOTool::anchor() {} | |||
153 | ||||
154 | void 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 | ||||
167 | bool 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) | |||
185 | static 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 | ||||
201 | void 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() && Version[0] >= 116 && NeedsTempPath(Inputs)) { | |||
228 | std::string TmpPathName; | |||
229 | if (D.getLTOMode() == LTOK_Full) { | |||
230 | // If we are using full LTO, then automatically create a temporary file | |||
231 | // path for the linker to use, so that it's lifetime will extend past a | |||
232 | // possible dsymutil step. | |||
233 | TmpPathName = | |||
234 | D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)); | |||
235 | } else if (D.getLTOMode() == LTOK_Thin) | |||
236 | // If we are using thin LTO, then create a directory instead. | |||
237 | TmpPathName = D.GetTemporaryDirectory("thinlto"); | |||
238 | ||||
239 | if (!TmpPathName.empty()) { | |||
240 | auto *TmpPath = C.getArgs().MakeArgString(TmpPathName); | |||
241 | C.addTempFile(TmpPath); | |||
242 | CmdArgs.push_back("-object_path_lto"); | |||
243 | CmdArgs.push_back(TmpPath); | |||
244 | } | |||
245 | } | |||
246 | ||||
247 | // Use -lto_library option to specify the libLTO.dylib path. Try to find | |||
248 | // it in clang installed libraries. ld64 will only look at this argument | |||
249 | // when it actually uses LTO, so libLTO.dylib only needs to exist at link | |||
250 | // time if ld64 decides that it needs to use LTO. | |||
251 | // Since this is passed unconditionally, ld64 will never look for libLTO.dylib | |||
252 | // next to it. That's ok since ld64 using a libLTO.dylib not matching the | |||
253 | // clang version won't work anyways. | |||
254 | if (Version[0] >= 133) { | |||
255 | // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib | |||
256 | StringRef P = llvm::sys::path::parent_path(D.Dir); | |||
257 | SmallString<128> LibLTOPath(P); | |||
258 | llvm::sys::path::append(LibLTOPath, "lib"); | |||
259 | llvm::sys::path::append(LibLTOPath, "libLTO.dylib"); | |||
260 | CmdArgs.push_back("-lto_library"); | |||
261 | CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath)); | |||
262 | } | |||
263 | ||||
264 | // ld64 version 262 and above run the deduplicate pass by default. | |||
265 | if (Version[0] >= 262 && shouldLinkerNotDedup(C.getJobs().empty(), Args)) | |||
266 | CmdArgs.push_back("-no_deduplicate"); | |||
267 | ||||
268 | // Derived from the "link" spec. | |||
269 | Args.AddAllArgs(CmdArgs, options::OPT_static); | |||
270 | if (!Args.hasArg(options::OPT_static)) | |||
271 | CmdArgs.push_back("-dynamic"); | |||
272 | if (Args.hasArg(options::OPT_fgnu_runtime)) { | |||
273 | // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu | |||
274 | // here. How do we wish to handle such things? | |||
275 | } | |||
276 | ||||
277 | if (!Args.hasArg(options::OPT_dynamiclib)) { | |||
278 | AddMachOArch(Args, CmdArgs); | |||
279 | // FIXME: Why do this only on this path? | |||
280 | Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL); | |||
281 | ||||
282 | Args.AddLastArg(CmdArgs, options::OPT_bundle); | |||
283 | Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader); | |||
284 | Args.AddAllArgs(CmdArgs, options::OPT_client__name); | |||
285 | ||||
286 | Arg *A; | |||
287 | if ((A = Args.getLastArg(options::OPT_compatibility__version)) || | |||
288 | (A = Args.getLastArg(options::OPT_current__version)) || | |||
289 | (A = Args.getLastArg(options::OPT_install__name))) | |||
290 | D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args) | |||
291 | << "-dynamiclib"; | |||
292 | ||||
293 | Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace); | |||
294 | Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs); | |||
295 | Args.AddLastArg(CmdArgs, options::OPT_private__bundle); | |||
296 | } else { | |||
297 | CmdArgs.push_back("-dylib"); | |||
298 | ||||
299 | Arg *A; | |||
300 | if ((A = Args.getLastArg(options::OPT_bundle)) || | |||
301 | (A = Args.getLastArg(options::OPT_bundle__loader)) || | |||
302 | (A = Args.getLastArg(options::OPT_client__name)) || | |||
303 | (A = Args.getLastArg(options::OPT_force__flat__namespace)) || | |||
304 | (A = Args.getLastArg(options::OPT_keep__private__externs)) || | |||
305 | (A = Args.getLastArg(options::OPT_private__bundle))) | |||
306 | D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args) | |||
307 | << "-dynamiclib"; | |||
308 | ||||
309 | Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version, | |||
310 | "-dylib_compatibility_version"); | |||
311 | Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version, | |||
312 | "-dylib_current_version"); | |||
313 | ||||
314 | AddMachOArch(Args, CmdArgs); | |||
315 | ||||
316 | Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name, | |||
317 | "-dylib_install_name"); | |||
318 | } | |||
319 | ||||
320 | Args.AddLastArg(CmdArgs, options::OPT_all__load); | |||
321 | Args.AddAllArgs(CmdArgs, options::OPT_allowable__client); | |||
322 | Args.AddLastArg(CmdArgs, options::OPT_bind__at__load); | |||
323 | if (MachOTC.isTargetIOSBased()) | |||
324 | Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal); | |||
325 | Args.AddLastArg(CmdArgs, options::OPT_dead__strip); | |||
326 | Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms); | |||
327 | Args.AddAllArgs(CmdArgs, options::OPT_dylib__file); | |||
328 | Args.AddLastArg(CmdArgs, options::OPT_dynamic); | |||
329 | Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list); | |||
330 | Args.AddLastArg(CmdArgs, options::OPT_flat__namespace); | |||
331 | Args.AddAllArgs(CmdArgs, options::OPT_force__load); | |||
332 | Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names); | |||
333 | Args.AddAllArgs(CmdArgs, options::OPT_image__base); | |||
334 | Args.AddAllArgs(CmdArgs, options::OPT_init); | |||
335 | ||||
336 | // Add the deployment target. | |||
337 | MachOTC.addMinVersionArgs(Args, CmdArgs); | |||
338 | ||||
339 | Args.AddLastArg(CmdArgs, options::OPT_nomultidefs); | |||
340 | Args.AddLastArg(CmdArgs, options::OPT_multi__module); | |||
341 | Args.AddLastArg(CmdArgs, options::OPT_single__module); | |||
342 | Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined); | |||
343 | Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused); | |||
344 | ||||
345 | if (const Arg *A = | |||
346 | Args.getLastArg(options::OPT_fpie, options::OPT_fPIE, | |||
347 | options::OPT_fno_pie, options::OPT_fno_PIE)) { | |||
348 | if (A->getOption().matches(options::OPT_fpie) || | |||
349 | A->getOption().matches(options::OPT_fPIE)) | |||
350 | CmdArgs.push_back("-pie"); | |||
351 | else | |||
352 | CmdArgs.push_back("-no_pie"); | |||
353 | } | |||
354 | ||||
355 | // for embed-bitcode, use -bitcode_bundle in linker command | |||
356 | if (C.getDriver().embedBitcodeEnabled()) { | |||
357 | // Check if the toolchain supports bitcode build flow. | |||
358 | if (MachOTC.SupportsEmbeddedBitcode()) { | |||
359 | CmdArgs.push_back("-bitcode_bundle"); | |||
360 | if (C.getDriver().embedBitcodeMarkerOnly() && Version[0] >= 278) { | |||
361 | CmdArgs.push_back("-bitcode_process_mode"); | |||
362 | CmdArgs.push_back("marker"); | |||
363 | } | |||
364 | } else | |||
365 | D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain); | |||
366 | } | |||
367 | ||||
368 | Args.AddLastArg(CmdArgs, options::OPT_prebind); | |||
369 | Args.AddLastArg(CmdArgs, options::OPT_noprebind); | |||
370 | Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding); | |||
371 | Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules); | |||
372 | Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs); | |||
373 | Args.AddAllArgs(CmdArgs, options::OPT_sectcreate); | |||
374 | Args.AddAllArgs(CmdArgs, options::OPT_sectorder); | |||
375 | Args.AddAllArgs(CmdArgs, options::OPT_seg1addr); | |||
376 | Args.AddAllArgs(CmdArgs, options::OPT_segprot); | |||
377 | Args.AddAllArgs(CmdArgs, options::OPT_segaddr); | |||
378 | Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr); | |||
379 | Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr); | |||
380 | Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table); | |||
381 | Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename); | |||
382 | Args.AddAllArgs(CmdArgs, options::OPT_sub__library); | |||
383 | Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella); | |||
384 | ||||
385 | // Give --sysroot= preference, over the Apple specific behavior to also use | |||
386 | // --isysroot as the syslibroot. | |||
387 | StringRef sysroot = C.getSysRoot(); | |||
388 | if (sysroot != "") { | |||
389 | CmdArgs.push_back("-syslibroot"); | |||
390 | CmdArgs.push_back(C.getArgs().MakeArgString(sysroot)); | |||
391 | } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) { | |||
392 | CmdArgs.push_back("-syslibroot"); | |||
393 | CmdArgs.push_back(A->getValue()); | |||
394 | } | |||
395 | ||||
396 | Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace); | |||
397 | Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints); | |||
398 | Args.AddAllArgs(CmdArgs, options::OPT_umbrella); | |||
399 | Args.AddAllArgs(CmdArgs, options::OPT_undefined); | |||
400 | Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list); | |||
401 | Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches); | |||
402 | Args.AddLastArg(CmdArgs, options::OPT_X_Flag); | |||
403 | Args.AddAllArgs(CmdArgs, options::OPT_y); | |||
404 | Args.AddLastArg(CmdArgs, options::OPT_w); | |||
405 | Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size); | |||
406 | Args.AddAllArgs(CmdArgs, options::OPT_segs__read__); | |||
407 | Args.AddLastArg(CmdArgs, options::OPT_seglinkedit); | |||
408 | Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit); | |||
409 | Args.AddAllArgs(CmdArgs, options::OPT_sectalign); | |||
410 | Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols); | |||
411 | Args.AddAllArgs(CmdArgs, options::OPT_segcreate); | |||
412 | Args.AddLastArg(CmdArgs, options::OPT_whyload); | |||
413 | Args.AddLastArg(CmdArgs, options::OPT_whatsloaded); | |||
414 | Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name); | |||
415 | Args.AddLastArg(CmdArgs, options::OPT_dylinker); | |||
416 | Args.AddLastArg(CmdArgs, options::OPT_Mach); | |||
417 | } | |||
418 | ||||
419 | /// Determine whether we are linking the ObjC runtime. | |||
420 | static bool isObjCRuntimeLinked(const ArgList &Args) { | |||
421 | if (isObjCAutoRefCount(Args)) { | |||
422 | Args.ClaimAllArgs(options::OPT_fobjc_link_runtime); | |||
423 | return true; | |||
424 | } | |||
425 | return Args.hasArg(options::OPT_fobjc_link_runtime); | |||
426 | } | |||
427 | ||||
428 | void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA, | |||
429 | const InputInfo &Output, | |||
430 | const InputInfoList &Inputs, | |||
431 | const ArgList &Args, | |||
432 | const char *LinkingOutput) const { | |||
433 | 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-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 433, __PRETTY_FUNCTION__)); | |||
434 | ||||
435 | // If the number of arguments surpasses the system limits, we will encode the | |||
436 | // input files in a separate file, shortening the command line. To this end, | |||
437 | // build a list of input file names that can be passed via a file with the | |||
438 | // -filelist linker option. | |||
439 | llvm::opt::ArgStringList InputFileList; | |||
440 | ||||
441 | // The logic here is derived from gcc's behavior; most of which | |||
442 | // comes from specs (starting with link_command). Consult gcc for | |||
443 | // more information. | |||
444 | ArgStringList CmdArgs; | |||
445 | ||||
446 | /// Hack(tm) to ignore linking errors when we are doing ARC migration. | |||
447 | if (Args.hasArg(options::OPT_ccc_arcmt_check, | |||
448 | options::OPT_ccc_arcmt_migrate)) { | |||
449 | for (const auto &Arg : Args) | |||
450 | Arg->claim(); | |||
451 | const char *Exec = | |||
452 | Args.MakeArgString(getToolChain().GetProgramPath("touch")); | |||
453 | CmdArgs.push_back(Output.getFilename()); | |||
454 | C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None)); | |||
455 | return; | |||
456 | } | |||
457 | ||||
458 | // I'm not sure why this particular decomposition exists in gcc, but | |||
459 | // we follow suite for ease of comparison. | |||
460 | AddLinkArgs(C, Args, CmdArgs, Inputs); | |||
461 | ||||
462 | // For LTO, pass the name of the optimization record file and other | |||
463 | // opt-remarks flags. | |||
464 | if (Args.hasFlag(options::OPT_fsave_optimization_record, | |||
465 | options::OPT_fno_save_optimization_record, false)) { | |||
466 | CmdArgs.push_back("-mllvm"); | |||
467 | CmdArgs.push_back("-lto-pass-remarks-output"); | |||
468 | CmdArgs.push_back("-mllvm"); | |||
469 | ||||
470 | SmallString<128> F; | |||
471 | F = Output.getFilename(); | |||
472 | F += ".opt.yaml"; | |||
473 | CmdArgs.push_back(Args.MakeArgString(F)); | |||
474 | ||||
475 | if (getLastProfileUseArg(Args)) { | |||
476 | CmdArgs.push_back("-mllvm"); | |||
477 | CmdArgs.push_back("-lto-pass-remarks-with-hotness"); | |||
478 | ||||
479 | if (const Arg *A = | |||
480 | Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) { | |||
481 | CmdArgs.push_back("-mllvm"); | |||
482 | std::string Opt = | |||
483 | std::string("-lto-pass-remarks-hotness-threshold=") + A->getValue(); | |||
484 | CmdArgs.push_back(Args.MakeArgString(Opt)); | |||
485 | } | |||
486 | } | |||
487 | ||||
488 | if (const Arg *A = | |||
489 | Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) { | |||
490 | CmdArgs.push_back("-mllvm"); | |||
491 | std::string Passes = | |||
492 | std::string("-lto-pass-remarks-filter=") + A->getValue(); | |||
493 | CmdArgs.push_back(Args.MakeArgString(Passes)); | |||
494 | } | |||
495 | } | |||
496 | ||||
497 | // Propagate the -moutline flag to the linker in LTO. | |||
498 | if (Arg *A = | |||
499 | Args.getLastArg(options::OPT_moutline, options::OPT_mno_outline)) { | |||
500 | if (A->getOption().matches(options::OPT_moutline)) { | |||
501 | if (getMachOToolChain().getMachOArchName(Args) == "arm64") { | |||
502 | CmdArgs.push_back("-mllvm"); | |||
503 | CmdArgs.push_back("-enable-machine-outliner"); | |||
504 | ||||
505 | // Outline from linkonceodr functions by default in LTO. | |||
506 | CmdArgs.push_back("-mllvm"); | |||
507 | CmdArgs.push_back("-enable-linkonceodr-outlining"); | |||
508 | } | |||
509 | } else { | |||
510 | // Disable all outlining behaviour if we have mno-outline. We need to do | |||
511 | // this explicitly, because targets which support default outlining will | |||
512 | // try to do work if we don't. | |||
513 | CmdArgs.push_back("-mllvm"); | |||
514 | CmdArgs.push_back("-enable-machine-outliner=never"); | |||
515 | } | |||
516 | } | |||
517 | ||||
518 | // Setup statistics file output. | |||
519 | SmallString<128> StatsFile = | |||
520 | getStatsFileName(Args, Output, Inputs[0], getToolChain().getDriver()); | |||
521 | if (!StatsFile.empty()) { | |||
522 | CmdArgs.push_back("-mllvm"); | |||
523 | CmdArgs.push_back(Args.MakeArgString("-lto-stats-file=" + StatsFile.str())); | |||
524 | } | |||
525 | ||||
526 | // It seems that the 'e' option is completely ignored for dynamic executables | |||
527 | // (the default), and with static executables, the last one wins, as expected. | |||
528 | Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t, | |||
529 | options::OPT_Z_Flag, options::OPT_u_Group, | |||
530 | options::OPT_e, options::OPT_r}); | |||
531 | ||||
532 | // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading | |||
533 | // members of static archive libraries which implement Objective-C classes or | |||
534 | // categories. | |||
535 | if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX)) | |||
536 | CmdArgs.push_back("-ObjC"); | |||
537 | ||||
538 | CmdArgs.push_back("-o"); | |||
539 | CmdArgs.push_back(Output.getFilename()); | |||
540 | ||||
541 | if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) | |||
542 | getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs); | |||
543 | ||||
544 | Args.AddAllArgs(CmdArgs, options::OPT_L); | |||
545 | ||||
546 | AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA); | |||
547 | // Build the input file for -filelist (list of linker input files) in case we | |||
548 | // need it later | |||
549 | for (const auto &II : Inputs) { | |||
550 | if (!II.isFilename()) { | |||
551 | // This is a linker input argument. | |||
552 | // We cannot mix input arguments and file names in a -filelist input, thus | |||
553 | // we prematurely stop our list (remaining files shall be passed as | |||
554 | // arguments). | |||
555 | if (InputFileList.size() > 0) | |||
556 | break; | |||
557 | ||||
558 | continue; | |||
559 | } | |||
560 | ||||
561 | InputFileList.push_back(II.getFilename()); | |||
562 | } | |||
563 | ||||
564 | if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) | |||
565 | addOpenMPRuntime(CmdArgs, getToolChain(), Args); | |||
566 | ||||
567 | if (isObjCRuntimeLinked(Args) && | |||
568 | !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) { | |||
569 | // We use arclite library for both ARC and subscripting support. | |||
570 | getMachOToolChain().AddLinkARCArgs(Args, CmdArgs); | |||
571 | ||||
572 | CmdArgs.push_back("-framework"); | |||
573 | CmdArgs.push_back("Foundation"); | |||
574 | // Link libobj. | |||
575 | CmdArgs.push_back("-lobjc"); | |||
576 | } | |||
577 | ||||
578 | if (LinkingOutput) { | |||
579 | CmdArgs.push_back("-arch_multiple"); | |||
580 | CmdArgs.push_back("-final_output"); | |||
581 | CmdArgs.push_back(LinkingOutput); | |||
582 | } | |||
583 | ||||
584 | if (Args.hasArg(options::OPT_fnested_functions)) | |||
585 | CmdArgs.push_back("-allow_stack_execute"); | |||
586 | ||||
587 | getMachOToolChain().addProfileRTLibs(Args, CmdArgs); | |||
588 | ||||
589 | if (unsigned Parallelism = | |||
590 | getLTOParallelism(Args, getToolChain().getDriver())) { | |||
591 | CmdArgs.push_back("-mllvm"); | |||
592 | CmdArgs.push_back(Args.MakeArgString("-threads=" + Twine(Parallelism))); | |||
593 | } | |||
594 | ||||
595 | if (getToolChain().ShouldLinkCXXStdlib(Args)) | |||
596 | getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs); | |||
597 | ||||
598 | bool NoStdOrDefaultLibs = | |||
599 | Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs); | |||
600 | bool ForceLinkBuiltins = Args.hasArg(options::OPT_fapple_link_rtlib); | |||
601 | if (!NoStdOrDefaultLibs || ForceLinkBuiltins) { | |||
602 | // link_ssp spec is empty. | |||
603 | ||||
604 | // If we have both -nostdlib/nodefaultlibs and -fapple-link-rtlib then | |||
605 | // we just want to link the builtins, not the other libs like libSystem. | |||
606 | if (NoStdOrDefaultLibs && ForceLinkBuiltins) { | |||
607 | getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs, "builtins"); | |||
608 | } else { | |||
609 | // Let the tool chain choose which runtime library to link. | |||
610 | getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs, | |||
611 | ForceLinkBuiltins); | |||
612 | ||||
613 | // No need to do anything for pthreads. Claim argument to avoid warning. | |||
614 | Args.ClaimAllArgs(options::OPT_pthread); | |||
615 | Args.ClaimAllArgs(options::OPT_pthreads); | |||
616 | } | |||
617 | } | |||
618 | ||||
619 | if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) { | |||
620 | // endfile_spec is empty. | |||
621 | } | |||
622 | ||||
623 | Args.AddAllArgs(CmdArgs, options::OPT_T_Group); | |||
624 | Args.AddAllArgs(CmdArgs, options::OPT_F); | |||
625 | ||||
626 | // -iframework should be forwarded as -F. | |||
627 | for (const Arg *A : Args.filtered(options::OPT_iframework)) | |||
628 | CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue())); | |||
629 | ||||
630 | if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) { | |||
631 | if (Arg *A = Args.getLastArg(options::OPT_fveclib)) { | |||
632 | if (A->getValue() == StringRef("Accelerate")) { | |||
633 | CmdArgs.push_back("-framework"); | |||
634 | CmdArgs.push_back("Accelerate"); | |||
635 | } | |||
636 | } | |||
637 | } | |||
638 | ||||
639 | const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath()); | |||
640 | std::unique_ptr<Command> Cmd = | |||
641 | llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs); | |||
642 | Cmd->setInputFileList(std::move(InputFileList)); | |||
643 | C.addCommand(std::move(Cmd)); | |||
644 | } | |||
645 | ||||
646 | void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA, | |||
647 | const InputInfo &Output, | |||
648 | const InputInfoList &Inputs, | |||
649 | const ArgList &Args, | |||
650 | const char *LinkingOutput) const { | |||
651 | ArgStringList CmdArgs; | |||
652 | ||||
653 | CmdArgs.push_back("-create"); | |||
654 | 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-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 654, __PRETTY_FUNCTION__)); | |||
655 | ||||
656 | CmdArgs.push_back("-output"); | |||
657 | CmdArgs.push_back(Output.getFilename()); | |||
658 | ||||
659 | for (const auto &II : Inputs) { | |||
660 | 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-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 660, __PRETTY_FUNCTION__)); | |||
661 | CmdArgs.push_back(II.getFilename()); | |||
662 | } | |||
663 | ||||
664 | const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo")); | |||
665 | C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs)); | |||
666 | } | |||
667 | ||||
668 | void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA, | |||
669 | const InputInfo &Output, | |||
670 | const InputInfoList &Inputs, | |||
671 | const ArgList &Args, | |||
672 | const char *LinkingOutput) const { | |||
673 | ArgStringList CmdArgs; | |||
674 | ||||
675 | CmdArgs.push_back("-o"); | |||
676 | CmdArgs.push_back(Output.getFilename()); | |||
677 | ||||
678 | 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-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 678, __PRETTY_FUNCTION__)); | |||
679 | const InputInfo &Input = Inputs[0]; | |||
680 | 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-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 680, __PRETTY_FUNCTION__)); | |||
681 | CmdArgs.push_back(Input.getFilename()); | |||
682 | ||||
683 | const char *Exec = | |||
684 | Args.MakeArgString(getToolChain().GetProgramPath("dsymutil")); | |||
685 | C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs)); | |||
686 | } | |||
687 | ||||
688 | void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA, | |||
689 | const InputInfo &Output, | |||
690 | const InputInfoList &Inputs, | |||
691 | const ArgList &Args, | |||
692 | const char *LinkingOutput) const { | |||
693 | ArgStringList CmdArgs; | |||
694 | CmdArgs.push_back("--verify"); | |||
695 | CmdArgs.push_back("--debug-info"); | |||
696 | CmdArgs.push_back("--eh-frame"); | |||
697 | CmdArgs.push_back("--quiet"); | |||
698 | ||||
699 | 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-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 699, __PRETTY_FUNCTION__)); | |||
700 | const InputInfo &Input = Inputs[0]; | |||
701 | 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-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 701, __PRETTY_FUNCTION__)); | |||
702 | ||||
703 | // Grabbing the output of the earlier dsymutil run. | |||
704 | CmdArgs.push_back(Input.getFilename()); | |||
705 | ||||
706 | const char *Exec = | |||
707 | Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump")); | |||
708 | C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs)); | |||
709 | } | |||
710 | ||||
711 | MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) | |||
712 | : ToolChain(D, Triple, Args) { | |||
713 | // We expect 'as', 'ld', etc. to be adjacent to our install dir. | |||
714 | getProgramPaths().push_back(getDriver().getInstalledDir()); | |||
715 | if (getDriver().getInstalledDir() != getDriver().Dir) | |||
716 | getProgramPaths().push_back(getDriver().Dir); | |||
717 | } | |||
718 | ||||
719 | /// Darwin - Darwin tool chain for i386 and x86_64. | |||
720 | Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) | |||
721 | : MachO(D, Triple, Args), TargetInitialized(false), | |||
722 | CudaInstallation(D, Triple, Args) {} | |||
723 | ||||
724 | types::ID MachO::LookupTypeForExtension(StringRef Ext) const { | |||
725 | types::ID Ty = types::lookupTypeForExtension(Ext); | |||
726 | ||||
727 | // Darwin always preprocesses assembly files (unless -x is used explicitly). | |||
728 | if (Ty == types::TY_PP_Asm) | |||
729 | return types::TY_Asm; | |||
730 | ||||
731 | return Ty; | |||
732 | } | |||
733 | ||||
734 | bool MachO::HasNativeLLVMSupport() const { return true; } | |||
735 | ||||
736 | ToolChain::CXXStdlibType Darwin::GetDefaultCXXStdlibType() const { | |||
737 | // Default to use libc++ on OS X 10.9+ and iOS 7+. | |||
738 | if ((isTargetMacOS() && !isMacosxVersionLT(10, 9)) || | |||
739 | (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0)) || | |||
740 | isTargetWatchOSBased()) | |||
741 | return ToolChain::CST_Libcxx; | |||
742 | ||||
743 | return ToolChain::CST_Libstdcxx; | |||
744 | } | |||
745 | ||||
746 | /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0. | |||
747 | ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const { | |||
748 | if (isTargetWatchOSBased()) | |||
749 | return ObjCRuntime(ObjCRuntime::WatchOS, TargetVersion); | |||
750 | if (isTargetIOSBased()) | |||
751 | return ObjCRuntime(ObjCRuntime::iOS, TargetVersion); | |||
752 | if (isNonFragile) | |||
753 | return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion); | |||
754 | return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion); | |||
755 | } | |||
756 | ||||
757 | /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2. | |||
758 | bool Darwin::hasBlocksRuntime() const { | |||
759 | if (isTargetWatchOSBased()) | |||
760 | return true; | |||
761 | else if (isTargetIOSBased()) | |||
762 | return !isIPhoneOSVersionLT(3, 2); | |||
763 | else { | |||
764 | assert(isTargetMacOS() && "unexpected darwin target")((isTargetMacOS() && "unexpected darwin target") ? static_cast <void> (0) : __assert_fail ("isTargetMacOS() && \"unexpected darwin target\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 764, __PRETTY_FUNCTION__)); | |||
765 | return !isMacosxVersionLT(10, 6); | |||
766 | } | |||
767 | } | |||
768 | ||||
769 | void Darwin::AddCudaIncludeArgs(const ArgList &DriverArgs, | |||
770 | ArgStringList &CC1Args) const { | |||
771 | CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args); | |||
772 | } | |||
773 | ||||
774 | // This is just a MachO name translation routine and there's no | |||
775 | // way to join this into ARMTargetParser without breaking all | |||
776 | // other assumptions. Maybe MachO should consider standardising | |||
777 | // their nomenclature. | |||
778 | static const char *ArmMachOArchName(StringRef Arch) { | |||
779 | return llvm::StringSwitch<const char *>(Arch) | |||
780 | .Case("armv6k", "armv6") | |||
781 | .Case("armv6m", "armv6m") | |||
782 | .Case("armv5tej", "armv5") | |||
783 | .Case("xscale", "xscale") | |||
784 | .Case("armv4t", "armv4t") | |||
785 | .Case("armv7", "armv7") | |||
786 | .Cases("armv7a", "armv7-a", "armv7") | |||
787 | .Cases("armv7r", "armv7-r", "armv7") | |||
788 | .Cases("armv7em", "armv7e-m", "armv7em") | |||
789 | .Cases("armv7k", "armv7-k", "armv7k") | |||
790 | .Cases("armv7m", "armv7-m", "armv7m") | |||
791 | .Cases("armv7s", "armv7-s", "armv7s") | |||
792 | .Default(nullptr); | |||
793 | } | |||
794 | ||||
795 | static const char *ArmMachOArchNameCPU(StringRef CPU) { | |||
796 | llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU); | |||
797 | if (ArchKind == llvm::ARM::ArchKind::INVALID) | |||
798 | return nullptr; | |||
799 | StringRef Arch = llvm::ARM::getArchName(ArchKind); | |||
800 | ||||
801 | // FIXME: Make sure this MachO triple mangling is really necessary. | |||
802 | // ARMv5* normalises to ARMv5. | |||
803 | if (Arch.startswith("armv5")) | |||
804 | Arch = Arch.substr(0, 5); | |||
805 | // ARMv6*, except ARMv6M, normalises to ARMv6. | |||
806 | else if (Arch.startswith("armv6") && !Arch.endswith("6m")) | |||
807 | Arch = Arch.substr(0, 5); | |||
808 | // ARMv7A normalises to ARMv7. | |||
809 | else if (Arch.endswith("v7a")) | |||
810 | Arch = Arch.substr(0, 5); | |||
811 | return Arch.data(); | |||
812 | } | |||
813 | ||||
814 | StringRef MachO::getMachOArchName(const ArgList &Args) const { | |||
815 | switch (getTriple().getArch()) { | |||
816 | default: | |||
817 | return getDefaultUniversalArchName(); | |||
818 | ||||
819 | case llvm::Triple::aarch64: | |||
820 | return "arm64"; | |||
821 | ||||
822 | case llvm::Triple::thumb: | |||
823 | case llvm::Triple::arm: | |||
824 | if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ)) | |||
825 | if (const char *Arch = ArmMachOArchName(A->getValue())) | |||
826 | return Arch; | |||
827 | ||||
828 | if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) | |||
829 | if (const char *Arch = ArmMachOArchNameCPU(A->getValue())) | |||
830 | return Arch; | |||
831 | ||||
832 | return "arm"; | |||
833 | } | |||
834 | } | |||
835 | ||||
836 | Darwin::~Darwin() {} | |||
837 | ||||
838 | MachO::~MachO() {} | |||
839 | ||||
840 | std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args, | |||
841 | types::ID InputType) const { | |||
842 | llvm::Triple Triple(ComputeLLVMTriple(Args, InputType)); | |||
843 | ||||
844 | // If the target isn't initialized (e.g., an unknown Darwin platform, return | |||
845 | // the default triple). | |||
846 | if (!isTargetInitialized()) | |||
847 | return Triple.getTriple(); | |||
848 | ||||
849 | SmallString<16> Str; | |||
850 | if (isTargetWatchOSBased()) | |||
851 | Str += "watchos"; | |||
852 | else if (isTargetTvOSBased()) | |||
853 | Str += "tvos"; | |||
854 | else if (isTargetIOSBased()) | |||
855 | Str += "ios"; | |||
856 | else | |||
857 | Str += "macosx"; | |||
858 | Str += getTargetVersion().getAsString(); | |||
859 | Triple.setOSName(Str); | |||
860 | ||||
861 | return Triple.getTriple(); | |||
862 | } | |||
863 | ||||
864 | Tool *MachO::getTool(Action::ActionClass AC) const { | |||
865 | switch (AC) { | |||
866 | case Action::LipoJobClass: | |||
867 | if (!Lipo) | |||
868 | Lipo.reset(new tools::darwin::Lipo(*this)); | |||
869 | return Lipo.get(); | |||
870 | case Action::DsymutilJobClass: | |||
871 | if (!Dsymutil) | |||
872 | Dsymutil.reset(new tools::darwin::Dsymutil(*this)); | |||
873 | return Dsymutil.get(); | |||
874 | case Action::VerifyDebugInfoJobClass: | |||
875 | if (!VerifyDebug) | |||
876 | VerifyDebug.reset(new tools::darwin::VerifyDebug(*this)); | |||
877 | return VerifyDebug.get(); | |||
878 | default: | |||
879 | return ToolChain::getTool(AC); | |||
880 | } | |||
881 | } | |||
882 | ||||
883 | Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); } | |||
884 | ||||
885 | Tool *MachO::buildAssembler() const { | |||
886 | return new tools::darwin::Assembler(*this); | |||
887 | } | |||
888 | ||||
889 | DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple, | |||
890 | const ArgList &Args) | |||
891 | : Darwin(D, Triple, Args) {} | |||
892 | ||||
893 | void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const { | |||
894 | // For modern targets, promote certain warnings to errors. | |||
895 | if (isTargetWatchOSBased() || getTriple().isArch64Bit()) { | |||
896 | // Always enable -Wdeprecated-objc-isa-usage and promote it | |||
897 | // to an error. | |||
898 | CC1Args.push_back("-Wdeprecated-objc-isa-usage"); | |||
899 | CC1Args.push_back("-Werror=deprecated-objc-isa-usage"); | |||
900 | ||||
901 | // For iOS and watchOS, also error about implicit function declarations, | |||
902 | // as that can impact calling conventions. | |||
903 | if (!isTargetMacOS()) | |||
904 | CC1Args.push_back("-Werror=implicit-function-declaration"); | |||
905 | } | |||
906 | } | |||
907 | ||||
908 | /// Take a path that speculatively points into Xcode and return the | |||
909 | /// `XCODE/Contents/Developer` path if it is an Xcode path, or an empty path | |||
910 | /// otherwise. | |||
911 | static StringRef getXcodeDeveloperPath(StringRef PathIntoXcode) { | |||
912 | static constexpr llvm::StringLiteral XcodeAppSuffix( | |||
913 | ".app/Contents/Developer"); | |||
914 | size_t Index = PathIntoXcode.find(XcodeAppSuffix); | |||
915 | if (Index == StringRef::npos) | |||
916 | return ""; | |||
917 | return PathIntoXcode.take_front(Index + XcodeAppSuffix.size()); | |||
918 | } | |||
919 | ||||
920 | void DarwinClang::AddLinkARCArgs(const ArgList &Args, | |||
921 | ArgStringList &CmdArgs) const { | |||
922 | // Avoid linking compatibility stubs on i386 mac. | |||
923 | if (isTargetMacOS() && getArch() == llvm::Triple::x86) | |||
924 | return; | |||
925 | ||||
926 | ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true); | |||
927 | ||||
928 | if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) && | |||
929 | runtime.hasSubscripting()) | |||
930 | return; | |||
931 | ||||
932 | SmallString<128> P(getDriver().ClangExecutable); | |||
933 | llvm::sys::path::remove_filename(P); // 'clang' | |||
934 | llvm::sys::path::remove_filename(P); // 'bin' | |||
935 | ||||
936 | // 'libarclite' usually lives in the same toolchain as 'clang'. However, the | |||
937 | // Swift open source toolchains for macOS distribute Clang without libarclite. | |||
938 | // In that case, to allow the linker to find 'libarclite', we point to the | |||
939 | // 'libarclite' in the XcodeDefault toolchain instead. | |||
940 | if (getXcodeDeveloperPath(P).empty()) { | |||
941 | if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) { | |||
942 | // Try to infer the path to 'libarclite' in the toolchain from the | |||
943 | // specified SDK path. | |||
944 | StringRef XcodePathForSDK = getXcodeDeveloperPath(A->getValue()); | |||
945 | if (!XcodePathForSDK.empty()) { | |||
946 | P = XcodePathForSDK; | |||
947 | llvm::sys::path::append(P, "Toolchains/XcodeDefault.xctoolchain/usr"); | |||
948 | } | |||
949 | } | |||
950 | } | |||
951 | ||||
952 | CmdArgs.push_back("-force_load"); | |||
953 | llvm::sys::path::append(P, "lib", "arc", "libarclite_"); | |||
954 | // Mash in the platform. | |||
955 | if (isTargetWatchOSSimulator()) | |||
956 | P += "watchsimulator"; | |||
957 | else if (isTargetWatchOS()) | |||
958 | P += "watchos"; | |||
959 | else if (isTargetTvOSSimulator()) | |||
960 | P += "appletvsimulator"; | |||
961 | else if (isTargetTvOS()) | |||
962 | P += "appletvos"; | |||
963 | else if (isTargetIOSSimulator()) | |||
964 | P += "iphonesimulator"; | |||
965 | else if (isTargetIPhoneOS()) | |||
966 | P += "iphoneos"; | |||
967 | else | |||
968 | P += "macosx"; | |||
969 | P += ".a"; | |||
970 | ||||
971 | CmdArgs.push_back(Args.MakeArgString(P)); | |||
972 | } | |||
973 | ||||
974 | unsigned DarwinClang::GetDefaultDwarfVersion() const { | |||
975 | // Default to use DWARF 2 on OS X 10.10 / iOS 8 and lower. | |||
976 | if ((isTargetMacOS() && isMacosxVersionLT(10, 11)) || | |||
977 | (isTargetIOSBased() && isIPhoneOSVersionLT(9))) | |||
978 | return 2; | |||
979 | return 4; | |||
980 | } | |||
981 | ||||
982 | void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs, | |||
983 | StringRef Component, RuntimeLinkOptions Opts, | |||
984 | bool IsShared) const { | |||
985 | SmallString<64> DarwinLibName = StringRef("libclang_rt."); | |||
986 | // an Darwin the builtins compomnent is not in the library name | |||
987 | if (Component != "builtins") { | |||
988 | DarwinLibName += Component; | |||
989 | if (!(Opts & RLO_IsEmbedded)) | |||
990 | DarwinLibName += "_"; | |||
991 | DarwinLibName += getOSLibraryNameSuffix(); | |||
992 | } else | |||
993 | DarwinLibName += getOSLibraryNameSuffix(true); | |||
994 | ||||
995 | DarwinLibName += IsShared ? "_dynamic.dylib" : ".a"; | |||
996 | SmallString<128> Dir(getDriver().ResourceDir); | |||
997 | llvm::sys::path::append( | |||
998 | Dir, "lib", (Opts & RLO_IsEmbedded) ? "macho_embedded" : "darwin"); | |||
999 | ||||
1000 | SmallString<128> P(Dir); | |||
1001 | llvm::sys::path::append(P, DarwinLibName); | |||
1002 | ||||
1003 | // For now, allow missing resource libraries to support developers who may | |||
1004 | // not have compiler-rt checked out or integrated into their build (unless | |||
1005 | // we explicitly force linking with this library). | |||
1006 | if ((Opts & RLO_AlwaysLink) || getVFS().exists(P)) { | |||
1007 | const char *LibArg = Args.MakeArgString(P); | |||
1008 | if (Opts & RLO_FirstLink) | |||
1009 | CmdArgs.insert(CmdArgs.begin(), LibArg); | |||
1010 | else | |||
1011 | CmdArgs.push_back(LibArg); | |||
1012 | } | |||
1013 | ||||
1014 | // Adding the rpaths might negatively interact when other rpaths are involved, | |||
1015 | // so we should make sure we add the rpaths last, after all user-specified | |||
1016 | // rpaths. This is currently true from this place, but we need to be | |||
1017 | // careful if this function is ever called before user's rpaths are emitted. | |||
1018 | if (Opts & RLO_AddRPath) { | |||
1019 | 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-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 1019, __PRETTY_FUNCTION__)); | |||
1020 | ||||
1021 | // Add @executable_path to rpath to support having the dylib copied with | |||
1022 | // the executable. | |||
1023 | CmdArgs.push_back("-rpath"); | |||
1024 | CmdArgs.push_back("@executable_path"); | |||
1025 | ||||
1026 | // Add the path to the resource dir to rpath to support using the dylib | |||
1027 | // from the default location without copying. | |||
1028 | CmdArgs.push_back("-rpath"); | |||
1029 | CmdArgs.push_back(Args.MakeArgString(Dir)); | |||
1030 | } | |||
1031 | } | |||
1032 | ||||
1033 | StringRef Darwin::getPlatformFamily() const { | |||
1034 | switch (TargetPlatform) { | |||
1035 | case DarwinPlatformKind::MacOS: | |||
1036 | return "MacOSX"; | |||
1037 | case DarwinPlatformKind::IPhoneOS: | |||
1038 | return "iPhone"; | |||
1039 | case DarwinPlatformKind::TvOS: | |||
1040 | return "AppleTV"; | |||
1041 | case DarwinPlatformKind::WatchOS: | |||
1042 | return "Watch"; | |||
1043 | } | |||
1044 | llvm_unreachable("Unsupported platform")::llvm::llvm_unreachable_internal("Unsupported platform", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 1044); | |||
1045 | } | |||
1046 | ||||
1047 | StringRef Darwin::getSDKName(StringRef isysroot) { | |||
1048 | // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk | |||
1049 | llvm::sys::path::const_iterator SDKDir; | |||
1050 | auto BeginSDK = llvm::sys::path::begin(isysroot); | |||
1051 | auto EndSDK = llvm::sys::path::end(isysroot); | |||
1052 | for (auto IT = BeginSDK; IT != EndSDK; ++IT) { | |||
1053 | StringRef SDK = *IT; | |||
1054 | if (SDK.endswith(".sdk")) | |||
1055 | return SDK.slice(0, SDK.size() - 4); | |||
1056 | } | |||
1057 | return ""; | |||
1058 | } | |||
1059 | ||||
1060 | StringRef Darwin::getOSLibraryNameSuffix(bool IgnoreSim) const { | |||
1061 | switch (TargetPlatform) { | |||
1062 | case DarwinPlatformKind::MacOS: | |||
1063 | return "osx"; | |||
1064 | case DarwinPlatformKind::IPhoneOS: | |||
1065 | return TargetEnvironment == NativeEnvironment || IgnoreSim ? "ios" | |||
1066 | : "iossim"; | |||
1067 | case DarwinPlatformKind::TvOS: | |||
1068 | return TargetEnvironment == NativeEnvironment || IgnoreSim ? "tvos" | |||
1069 | : "tvossim"; | |||
1070 | case DarwinPlatformKind::WatchOS: | |||
1071 | return TargetEnvironment == NativeEnvironment || IgnoreSim ? "watchos" | |||
1072 | : "watchossim"; | |||
1073 | } | |||
1074 | llvm_unreachable("Unsupported platform")::llvm::llvm_unreachable_internal("Unsupported platform", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 1074); | |||
1075 | } | |||
1076 | ||||
1077 | /// Check if the link command contains a symbol export directive. | |||
1078 | static bool hasExportSymbolDirective(const ArgList &Args) { | |||
1079 | for (Arg *A : Args) { | |||
1080 | if (A->getOption().matches(options::OPT_exported__symbols__list)) | |||
1081 | return true; | |||
1082 | if (!A->getOption().matches(options::OPT_Wl_COMMA) && | |||
1083 | !A->getOption().matches(options::OPT_Xlinker)) | |||
1084 | continue; | |||
1085 | if (A->containsValue("-exported_symbols_list") || | |||
1086 | A->containsValue("-exported_symbol")) | |||
1087 | return true; | |||
1088 | } | |||
1089 | return false; | |||
1090 | } | |||
1091 | ||||
1092 | /// Add an export directive for \p Symbol to the link command. | |||
1093 | static void addExportedSymbol(ArgStringList &CmdArgs, const char *Symbol) { | |||
1094 | CmdArgs.push_back("-exported_symbol"); | |||
1095 | CmdArgs.push_back(Symbol); | |||
1096 | } | |||
1097 | ||||
1098 | void Darwin::addProfileRTLibs(const ArgList &Args, | |||
1099 | ArgStringList &CmdArgs) const { | |||
1100 | if (!needsProfileRT(Args)) return; | |||
1101 | ||||
1102 | AddLinkRuntimeLib(Args, CmdArgs, "profile", | |||
1103 | RuntimeLinkOptions(RLO_AlwaysLink | RLO_FirstLink)); | |||
1104 | ||||
1105 | // If we have a symbol export directive and we're linking in the profile | |||
1106 | // runtime, automatically export symbols necessary to implement some of the | |||
1107 | // runtime's functionality. | |||
1108 | if (hasExportSymbolDirective(Args)) { | |||
1109 | if (needsGCovInstrumentation(Args)) { | |||
1110 | addExportedSymbol(CmdArgs, "___gcov_flush"); | |||
1111 | addExportedSymbol(CmdArgs, "_flush_fn_list"); | |||
1112 | addExportedSymbol(CmdArgs, "_writeout_fn_list"); | |||
1113 | } else { | |||
1114 | addExportedSymbol(CmdArgs, "___llvm_profile_filename"); | |||
1115 | addExportedSymbol(CmdArgs, "___llvm_profile_raw_version"); | |||
1116 | addExportedSymbol(CmdArgs, "_lprofCurFilename"); | |||
1117 | } | |||
1118 | addExportedSymbol(CmdArgs, "_lprofDirMode"); | |||
1119 | } | |||
1120 | } | |||
1121 | ||||
1122 | void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args, | |||
1123 | ArgStringList &CmdArgs, | |||
1124 | StringRef Sanitizer, | |||
1125 | bool Shared) const { | |||
1126 | auto RLO = RuntimeLinkOptions(RLO_AlwaysLink | (Shared ? RLO_AddRPath : 0U)); | |||
1127 | AddLinkRuntimeLib(Args, CmdArgs, Sanitizer, RLO, Shared); | |||
1128 | } | |||
1129 | ||||
1130 | ToolChain::RuntimeLibType DarwinClang::GetRuntimeLibType( | |||
1131 | const ArgList &Args) const { | |||
1132 | if (Arg* A = Args.getLastArg(options::OPT_rtlib_EQ)) { | |||
1133 | StringRef Value = A->getValue(); | |||
1134 | if (Value != "compiler-rt") | |||
1135 | getDriver().Diag(clang::diag::err_drv_unsupported_rtlib_for_platform) | |||
1136 | << Value << "darwin"; | |||
1137 | } | |||
1138 | ||||
1139 | return ToolChain::RLT_CompilerRT; | |||
1140 | } | |||
1141 | ||||
1142 | void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args, | |||
1143 | ArgStringList &CmdArgs, | |||
1144 | bool ForceLinkBuiltinRT) const { | |||
1145 | // Call once to ensure diagnostic is printed if wrong value was specified | |||
1146 | GetRuntimeLibType(Args); | |||
1147 | ||||
1148 | // Darwin doesn't support real static executables, don't link any runtime | |||
1149 | // libraries with -static. | |||
1150 | if (Args.hasArg(options::OPT_static) || | |||
1151 | Args.hasArg(options::OPT_fapple_kext) || | |||
1152 | Args.hasArg(options::OPT_mkernel)) { | |||
1153 | if (ForceLinkBuiltinRT) | |||
1154 | AddLinkRuntimeLib(Args, CmdArgs, "builtins"); | |||
1155 | return; | |||
1156 | } | |||
1157 | ||||
1158 | // Reject -static-libgcc for now, we can deal with this when and if someone | |||
1159 | // cares. This is useful in situations where someone wants to statically link | |||
1160 | // something like libstdc++, and needs its runtime support routines. | |||
1161 | if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) { | |||
1162 | getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args); | |||
1163 | return; | |||
1164 | } | |||
1165 | ||||
1166 | const SanitizerArgs &Sanitize = getSanitizerArgs(); | |||
1167 | if (Sanitize.needsAsanRt()) | |||
1168 | AddLinkSanitizerLibArgs(Args, CmdArgs, "asan"); | |||
1169 | if (Sanitize.needsLsanRt()) | |||
1170 | AddLinkSanitizerLibArgs(Args, CmdArgs, "lsan"); | |||
1171 | if (Sanitize.needsUbsanRt()) | |||
1172 | AddLinkSanitizerLibArgs(Args, CmdArgs, | |||
1173 | Sanitize.requiresMinimalRuntime() ? "ubsan_minimal" | |||
1174 | : "ubsan", | |||
1175 | Sanitize.needsSharedRt()); | |||
1176 | if (Sanitize.needsTsanRt()) | |||
1177 | AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan"); | |||
1178 | if (Sanitize.needsFuzzer() && !Args.hasArg(options::OPT_dynamiclib)) { | |||
1179 | AddLinkSanitizerLibArgs(Args, CmdArgs, "fuzzer", /*shared=*/false); | |||
1180 | ||||
1181 | // Libfuzzer is written in C++ and requires libcxx. | |||
1182 | AddCXXStdlibLibArgs(Args, CmdArgs); | |||
1183 | } | |||
1184 | if (Sanitize.needsStatsRt()) { | |||
1185 | AddLinkRuntimeLib(Args, CmdArgs, "stats_client", RLO_AlwaysLink); | |||
1186 | AddLinkSanitizerLibArgs(Args, CmdArgs, "stats"); | |||
1187 | } | |||
1188 | ||||
1189 | const XRayArgs &XRay = getXRayArgs(); | |||
1190 | if (XRay.needsXRayRt()) { | |||
1191 | AddLinkRuntimeLib(Args, CmdArgs, "xray"); | |||
1192 | AddLinkRuntimeLib(Args, CmdArgs, "xray-basic"); | |||
1193 | AddLinkRuntimeLib(Args, CmdArgs, "xray-fdr"); | |||
1194 | } | |||
1195 | ||||
1196 | // Otherwise link libSystem, then the dynamic runtime library, and finally any | |||
1197 | // target specific static runtime library. | |||
1198 | CmdArgs.push_back("-lSystem"); | |||
1199 | ||||
1200 | // Select the dynamic runtime library and the target specific static library. | |||
1201 | if (isTargetIOSBased()) { | |||
1202 | // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1, | |||
1203 | // it never went into the SDK. | |||
1204 | // Linking against libgcc_s.1 isn't needed for iOS 5.0+ | |||
1205 | if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() && | |||
1206 | getTriple().getArch() != llvm::Triple::aarch64) | |||
1207 | CmdArgs.push_back("-lgcc_s.1"); | |||
1208 | } | |||
1209 | AddLinkRuntimeLib(Args, CmdArgs, "builtins"); | |||
1210 | } | |||
1211 | ||||
1212 | /// Returns the most appropriate macOS target version for the current process. | |||
1213 | /// | |||
1214 | /// If the macOS SDK version is the same or earlier than the system version, | |||
1215 | /// then the SDK version is returned. Otherwise the system version is returned. | |||
1216 | static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion) { | |||
1217 | unsigned Major, Minor, Micro; | |||
1218 | llvm::Triple SystemTriple(llvm::sys::getProcessTriple()); | |||
1219 | if (!SystemTriple.isMacOSX()) | |||
1220 | return MacOSSDKVersion; | |||
1221 | SystemTriple.getMacOSXVersion(Major, Minor, Micro); | |||
1222 | VersionTuple SystemVersion(Major, Minor, Micro); | |||
1223 | bool HadExtra; | |||
1224 | if (!Driver::GetReleaseVersion(MacOSSDKVersion, Major, Minor, Micro, | |||
1225 | HadExtra)) | |||
1226 | return MacOSSDKVersion; | |||
1227 | VersionTuple SDKVersion(Major, Minor, Micro); | |||
1228 | if (SDKVersion > SystemVersion) | |||
1229 | return SystemVersion.getAsString(); | |||
1230 | return MacOSSDKVersion; | |||
1231 | } | |||
1232 | ||||
1233 | namespace { | |||
1234 | ||||
1235 | /// The Darwin OS that was selected or inferred from arguments / environment. | |||
1236 | struct DarwinPlatform { | |||
1237 | enum SourceKind { | |||
1238 | /// The OS was specified using the -target argument. | |||
1239 | TargetArg, | |||
1240 | /// The OS was specified using the -m<os>-version-min argument. | |||
1241 | OSVersionArg, | |||
1242 | /// The OS was specified using the OS_DEPLOYMENT_TARGET environment. | |||
1243 | DeploymentTargetEnv, | |||
1244 | /// The OS was inferred from the SDK. | |||
1245 | InferredFromSDK, | |||
1246 | /// The OS was inferred from the -arch. | |||
1247 | InferredFromArch | |||
1248 | }; | |||
1249 | ||||
1250 | using DarwinPlatformKind = Darwin::DarwinPlatformKind; | |||
1251 | using DarwinEnvironmentKind = Darwin::DarwinEnvironmentKind; | |||
1252 | ||||
1253 | DarwinPlatformKind getPlatform() const { return Platform; } | |||
1254 | ||||
1255 | DarwinEnvironmentKind getEnvironment() const { return Environment; } | |||
1256 | ||||
1257 | void setEnvironment(DarwinEnvironmentKind Kind) { | |||
1258 | Environment = Kind; | |||
1259 | InferSimulatorFromArch = false; | |||
1260 | } | |||
1261 | ||||
1262 | StringRef getOSVersion() const { | |||
1263 | if (Kind == OSVersionArg) | |||
1264 | return Argument->getValue(); | |||
1265 | return OSVersion; | |||
1266 | } | |||
1267 | ||||
1268 | void setOSVersion(StringRef S) { | |||
1269 | assert(Kind == TargetArg && "Unexpected kind!")((Kind == TargetArg && "Unexpected kind!") ? static_cast <void> (0) : __assert_fail ("Kind == TargetArg && \"Unexpected kind!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 1269, __PRETTY_FUNCTION__)); | |||
1270 | OSVersion = S; | |||
1271 | } | |||
1272 | ||||
1273 | bool hasOSVersion() const { return HasOSVersion; } | |||
1274 | ||||
1275 | /// Returns true if the target OS was explicitly specified. | |||
1276 | bool isExplicitlySpecified() const { return Kind <= DeploymentTargetEnv; } | |||
1277 | ||||
1278 | /// Returns true if the simulator environment can be inferred from the arch. | |||
1279 | bool canInferSimulatorFromArch() const { return InferSimulatorFromArch; } | |||
1280 | ||||
1281 | /// Adds the -m<os>-version-min argument to the compiler invocation. | |||
1282 | void addOSVersionMinArgument(DerivedArgList &Args, const OptTable &Opts) { | |||
1283 | if (Argument) | |||
1284 | return; | |||
1285 | 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-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 1285, __PRETTY_FUNCTION__)); | |||
1286 | options::ID Opt; | |||
1287 | switch (Platform) { | |||
1288 | case DarwinPlatformKind::MacOS: | |||
1289 | Opt = options::OPT_mmacosx_version_min_EQ; | |||
1290 | break; | |||
1291 | case DarwinPlatformKind::IPhoneOS: | |||
1292 | Opt = options::OPT_miphoneos_version_min_EQ; | |||
1293 | break; | |||
1294 | case DarwinPlatformKind::TvOS: | |||
1295 | Opt = options::OPT_mtvos_version_min_EQ; | |||
1296 | break; | |||
1297 | case DarwinPlatformKind::WatchOS: | |||
1298 | Opt = options::OPT_mwatchos_version_min_EQ; | |||
1299 | break; | |||
1300 | } | |||
1301 | Argument = Args.MakeJoinedArg(nullptr, Opts.getOption(Opt), OSVersion); | |||
1302 | Args.append(Argument); | |||
1303 | } | |||
1304 | ||||
1305 | /// Returns the OS version with the argument / environment variable that | |||
1306 | /// specified it. | |||
1307 | std::string getAsString(DerivedArgList &Args, const OptTable &Opts) { | |||
1308 | switch (Kind) { | |||
1309 | case TargetArg: | |||
1310 | case OSVersionArg: | |||
1311 | case InferredFromSDK: | |||
1312 | case InferredFromArch: | |||
1313 | 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-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 1313, __PRETTY_FUNCTION__)); | |||
1314 | return Argument->getAsString(Args); | |||
1315 | case DeploymentTargetEnv: | |||
1316 | return (llvm::Twine(EnvVarName) + "=" + OSVersion).str(); | |||
1317 | } | |||
1318 | llvm_unreachable("Unsupported Darwin Source Kind")::llvm::llvm_unreachable_internal("Unsupported Darwin Source Kind" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 1318); | |||
1319 | } | |||
1320 | ||||
1321 | static DarwinPlatform createFromTarget(const llvm::Triple &TT, | |||
1322 | StringRef OSVersion, Arg *A) { | |||
1323 | DarwinPlatform Result(TargetArg, getPlatformFromOS(TT.getOS()), OSVersion, | |||
1324 | A); | |||
1325 | switch (TT.getEnvironment()) { | |||
1326 | case llvm::Triple::Simulator: | |||
1327 | Result.Environment = DarwinEnvironmentKind::Simulator; | |||
1328 | break; | |||
1329 | default: | |||
1330 | break; | |||
1331 | } | |||
1332 | unsigned Major, Minor, Micro; | |||
1333 | TT.getOSVersion(Major, Minor, Micro); | |||
1334 | if (Major == 0) | |||
1335 | Result.HasOSVersion = false; | |||
1336 | return Result; | |||
1337 | } | |||
1338 | static DarwinPlatform createOSVersionArg(DarwinPlatformKind Platform, | |||
1339 | Arg *A) { | |||
1340 | return DarwinPlatform(OSVersionArg, Platform, A); | |||
1341 | } | |||
1342 | static DarwinPlatform createDeploymentTargetEnv(DarwinPlatformKind Platform, | |||
1343 | StringRef EnvVarName, | |||
1344 | StringRef Value) { | |||
1345 | DarwinPlatform Result(DeploymentTargetEnv, Platform, Value); | |||
1346 | Result.EnvVarName = EnvVarName; | |||
1347 | return Result; | |||
1348 | } | |||
1349 | static DarwinPlatform createFromSDK(DarwinPlatformKind Platform, | |||
1350 | StringRef Value, | |||
1351 | bool IsSimulator = false) { | |||
1352 | DarwinPlatform Result(InferredFromSDK, Platform, Value); | |||
1353 | if (IsSimulator) | |||
1354 | Result.Environment = DarwinEnvironmentKind::Simulator; | |||
1355 | Result.InferSimulatorFromArch = false; | |||
1356 | return Result; | |||
1357 | } | |||
1358 | static DarwinPlatform createFromArch(llvm::Triple::OSType OS, | |||
1359 | StringRef Value) { | |||
1360 | return DarwinPlatform(InferredFromArch, getPlatformFromOS(OS), Value); | |||
1361 | } | |||
1362 | ||||
1363 | /// Constructs an inferred SDKInfo value based on the version inferred from | |||
1364 | /// the SDK path itself. Only works for values that were created by inferring | |||
1365 | /// the platform from the SDKPath. | |||
1366 | DarwinSDKInfo inferSDKInfo() { | |||
1367 | 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-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 1367, __PRETTY_FUNCTION__)); | |||
1368 | llvm::VersionTuple Version; | |||
1369 | bool IsValid = !Version.tryParse(OSVersion); | |||
1370 | (void)IsValid; | |||
1371 | assert(IsValid && "invalid SDK version")((IsValid && "invalid SDK version") ? static_cast< void> (0) : __assert_fail ("IsValid && \"invalid SDK version\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 1371, __PRETTY_FUNCTION__)); | |||
1372 | return DarwinSDKInfo(Version); | |||
1373 | } | |||
1374 | ||||
1375 | private: | |||
1376 | DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, Arg *Argument) | |||
1377 | : Kind(Kind), Platform(Platform), Argument(Argument) {} | |||
1378 | DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, StringRef Value, | |||
1379 | Arg *Argument = nullptr) | |||
1380 | : Kind(Kind), Platform(Platform), OSVersion(Value), Argument(Argument) {} | |||
1381 | ||||
1382 | static DarwinPlatformKind getPlatformFromOS(llvm::Triple::OSType OS) { | |||
1383 | switch (OS) { | |||
1384 | case llvm::Triple::Darwin: | |||
1385 | case llvm::Triple::MacOSX: | |||
1386 | return DarwinPlatformKind::MacOS; | |||
1387 | case llvm::Triple::IOS: | |||
1388 | return DarwinPlatformKind::IPhoneOS; | |||
1389 | case llvm::Triple::TvOS: | |||
1390 | return DarwinPlatformKind::TvOS; | |||
1391 | case llvm::Triple::WatchOS: | |||
1392 | return DarwinPlatformKind::WatchOS; | |||
1393 | default: | |||
1394 | llvm_unreachable("Unable to infer Darwin variant")::llvm::llvm_unreachable_internal("Unable to infer Darwin variant" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 1394); | |||
1395 | } | |||
1396 | } | |||
1397 | ||||
1398 | SourceKind Kind; | |||
1399 | DarwinPlatformKind Platform; | |||
1400 | DarwinEnvironmentKind Environment = DarwinEnvironmentKind::NativeEnvironment; | |||
1401 | std::string OSVersion; | |||
1402 | bool HasOSVersion = true, InferSimulatorFromArch = true; | |||
1403 | Arg *Argument; | |||
1404 | StringRef EnvVarName; | |||
1405 | }; | |||
1406 | ||||
1407 | /// Returns the deployment target that's specified using the -m<os>-version-min | |||
1408 | /// argument. | |||
1409 | Optional<DarwinPlatform> | |||
1410 | getDeploymentTargetFromOSVersionArg(DerivedArgList &Args, | |||
1411 | const Driver &TheDriver) { | |||
1412 | Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ); | |||
1413 | Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ, | |||
1414 | options::OPT_mios_simulator_version_min_EQ); | |||
1415 | Arg *TvOSVersion = | |||
1416 | Args.getLastArg(options::OPT_mtvos_version_min_EQ, | |||
1417 | options::OPT_mtvos_simulator_version_min_EQ); | |||
1418 | Arg *WatchOSVersion = | |||
1419 | Args.getLastArg(options::OPT_mwatchos_version_min_EQ, | |||
1420 | options::OPT_mwatchos_simulator_version_min_EQ); | |||
1421 | if (OSXVersion) { | |||
1422 | if (iOSVersion || TvOSVersion || WatchOSVersion) { | |||
1423 | TheDriver.Diag(diag::err_drv_argument_not_allowed_with) | |||
1424 | << OSXVersion->getAsString(Args) | |||
1425 | << (iOSVersion ? iOSVersion | |||
1426 | : TvOSVersion ? TvOSVersion : WatchOSVersion) | |||
1427 | ->getAsString(Args); | |||
1428 | } | |||
1429 | return DarwinPlatform::createOSVersionArg(Darwin::MacOS, OSXVersion); | |||
1430 | } else if (iOSVersion) { | |||
1431 | if (TvOSVersion || WatchOSVersion) { | |||
1432 | TheDriver.Diag(diag::err_drv_argument_not_allowed_with) | |||
1433 | << iOSVersion->getAsString(Args) | |||
1434 | << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args); | |||
1435 | } | |||
1436 | return DarwinPlatform::createOSVersionArg(Darwin::IPhoneOS, iOSVersion); | |||
1437 | } else if (TvOSVersion) { | |||
1438 | if (WatchOSVersion) { | |||
1439 | TheDriver.Diag(diag::err_drv_argument_not_allowed_with) | |||
1440 | << TvOSVersion->getAsString(Args) | |||
1441 | << WatchOSVersion->getAsString(Args); | |||
1442 | } | |||
1443 | return DarwinPlatform::createOSVersionArg(Darwin::TvOS, TvOSVersion); | |||
1444 | } else if (WatchOSVersion) | |||
1445 | return DarwinPlatform::createOSVersionArg(Darwin::WatchOS, WatchOSVersion); | |||
1446 | return None; | |||
1447 | } | |||
1448 | ||||
1449 | /// Returns the deployment target that's specified using the | |||
1450 | /// OS_DEPLOYMENT_TARGET environment variable. | |||
1451 | Optional<DarwinPlatform> | |||
1452 | getDeploymentTargetFromEnvironmentVariables(const Driver &TheDriver, | |||
1453 | const llvm::Triple &Triple) { | |||
1454 | std::string Targets[Darwin::LastDarwinPlatform + 1]; | |||
1455 | const char *EnvVars[] = { | |||
1456 | "MACOSX_DEPLOYMENT_TARGET", | |||
1457 | "IPHONEOS_DEPLOYMENT_TARGET", | |||
1458 | "TVOS_DEPLOYMENT_TARGET", | |||
1459 | "WATCHOS_DEPLOYMENT_TARGET", | |||
1460 | }; | |||
1461 | static_assert(llvm::array_lengthof(EnvVars) == Darwin::LastDarwinPlatform + 1, | |||
1462 | "Missing platform"); | |||
1463 | for (const auto &I : llvm::enumerate(llvm::makeArrayRef(EnvVars))) { | |||
1464 | if (char *Env = ::getenv(I.value())) | |||
1465 | Targets[I.index()] = Env; | |||
1466 | } | |||
1467 | ||||
1468 | // Do not allow conflicts with the watchOS target. | |||
1469 | if (!Targets[Darwin::WatchOS].empty() && | |||
1470 | (!Targets[Darwin::IPhoneOS].empty() || !Targets[Darwin::TvOS].empty())) { | |||
1471 | TheDriver.Diag(diag::err_drv_conflicting_deployment_targets) | |||
1472 | << "WATCHOS_DEPLOYMENT_TARGET" | |||
1473 | << (!Targets[Darwin::IPhoneOS].empty() ? "IPHONEOS_DEPLOYMENT_TARGET" | |||
1474 | : "TVOS_DEPLOYMENT_TARGET"); | |||
1475 | } | |||
1476 | ||||
1477 | // Do not allow conflicts with the tvOS target. | |||
1478 | if (!Targets[Darwin::TvOS].empty() && !Targets[Darwin::IPhoneOS].empty()) { | |||
1479 | TheDriver.Diag(diag::err_drv_conflicting_deployment_targets) | |||
1480 | << "TVOS_DEPLOYMENT_TARGET" | |||
1481 | << "IPHONEOS_DEPLOYMENT_TARGET"; | |||
1482 | } | |||
1483 | ||||
1484 | // Allow conflicts among OSX and iOS for historical reasons, but choose the | |||
1485 | // default platform. | |||
1486 | if (!Targets[Darwin::MacOS].empty() && | |||
1487 | (!Targets[Darwin::IPhoneOS].empty() || | |||
1488 | !Targets[Darwin::WatchOS].empty() || !Targets[Darwin::TvOS].empty())) { | |||
1489 | if (Triple.getArch() == llvm::Triple::arm || | |||
1490 | Triple.getArch() == llvm::Triple::aarch64 || | |||
1491 | Triple.getArch() == llvm::Triple::thumb) | |||
1492 | Targets[Darwin::MacOS] = ""; | |||
1493 | else | |||
1494 | Targets[Darwin::IPhoneOS] = Targets[Darwin::WatchOS] = | |||
1495 | Targets[Darwin::TvOS] = ""; | |||
1496 | } | |||
1497 | ||||
1498 | for (const auto &Target : llvm::enumerate(llvm::makeArrayRef(Targets))) { | |||
1499 | if (!Target.value().empty()) | |||
1500 | return DarwinPlatform::createDeploymentTargetEnv( | |||
1501 | (Darwin::DarwinPlatformKind)Target.index(), EnvVars[Target.index()], | |||
1502 | Target.value()); | |||
1503 | } | |||
1504 | return None; | |||
1505 | } | |||
1506 | ||||
1507 | /// Tries to infer the deployment target from the SDK specified by -isysroot | |||
1508 | /// (or SDKROOT). Uses the version specified in the SDKSettings.json file if | |||
1509 | /// it's available. | |||
1510 | Optional<DarwinPlatform> | |||
1511 | inferDeploymentTargetFromSDK(DerivedArgList &Args, | |||
1512 | const Optional<DarwinSDKInfo> &SDKInfo) { | |||
1513 | const Arg *A = Args.getLastArg(options::OPT_isysroot); | |||
1514 | if (!A) | |||
1515 | return None; | |||
1516 | StringRef isysroot = A->getValue(); | |||
1517 | StringRef SDK = Darwin::getSDKName(isysroot); | |||
1518 | if (!SDK.size()) | |||
1519 | return None; | |||
1520 | ||||
1521 | std::string Version; | |||
1522 | if (SDKInfo) { | |||
1523 | // Get the version from the SDKSettings.json if it's available. | |||
1524 | Version = SDKInfo->getVersion().getAsString(); | |||
1525 | } else { | |||
1526 | // Slice the version number out. | |||
1527 | // Version number is between the first and the last number. | |||
1528 | size_t StartVer = SDK.find_first_of("0123456789"); | |||
1529 | size_t EndVer = SDK.find_last_of("0123456789"); | |||
1530 | if (StartVer != StringRef::npos && EndVer > StartVer) | |||
1531 | Version = SDK.slice(StartVer, EndVer + 1); | |||
1532 | } | |||
1533 | if (Version.empty()) | |||
1534 | return None; | |||
1535 | ||||
1536 | if (SDK.startswith("iPhoneOS") || SDK.startswith("iPhoneSimulator")) | |||
1537 | return DarwinPlatform::createFromSDK( | |||
1538 | Darwin::IPhoneOS, Version, | |||
1539 | /*IsSimulator=*/SDK.startswith("iPhoneSimulator")); | |||
1540 | else if (SDK.startswith("MacOSX")) | |||
1541 | return DarwinPlatform::createFromSDK(Darwin::MacOS, | |||
1542 | getSystemOrSDKMacOSVersion(Version)); | |||
1543 | else if (SDK.startswith("WatchOS") || SDK.startswith("WatchSimulator")) | |||
1544 | return DarwinPlatform::createFromSDK( | |||
1545 | Darwin::WatchOS, Version, | |||
1546 | /*IsSimulator=*/SDK.startswith("WatchSimulator")); | |||
1547 | else if (SDK.startswith("AppleTVOS") || SDK.startswith("AppleTVSimulator")) | |||
1548 | return DarwinPlatform::createFromSDK( | |||
1549 | Darwin::TvOS, Version, | |||
1550 | /*IsSimulator=*/SDK.startswith("AppleTVSimulator")); | |||
1551 | return None; | |||
1552 | } | |||
1553 | ||||
1554 | std::string getOSVersion(llvm::Triple::OSType OS, const llvm::Triple &Triple, | |||
1555 | const Driver &TheDriver) { | |||
1556 | unsigned Major, Minor, Micro; | |||
1557 | llvm::Triple SystemTriple(llvm::sys::getProcessTriple()); | |||
1558 | switch (OS) { | |||
1559 | case llvm::Triple::Darwin: | |||
1560 | case llvm::Triple::MacOSX: | |||
1561 | // If there is no version specified on triple, and both host and target are | |||
1562 | // macos, use the host triple to infer OS version. | |||
1563 | if (Triple.isMacOSX() && SystemTriple.isMacOSX() && | |||
1564 | !Triple.getOSMajorVersion()) | |||
1565 | SystemTriple.getMacOSXVersion(Major, Minor, Micro); | |||
1566 | else if (!Triple.getMacOSXVersion(Major, Minor, Micro)) | |||
1567 | TheDriver.Diag(diag::err_drv_invalid_darwin_version) | |||
1568 | << Triple.getOSName(); | |||
1569 | break; | |||
1570 | case llvm::Triple::IOS: | |||
1571 | Triple.getiOSVersion(Major, Minor, Micro); | |||
1572 | break; | |||
1573 | case llvm::Triple::TvOS: | |||
1574 | Triple.getOSVersion(Major, Minor, Micro); | |||
1575 | break; | |||
1576 | case llvm::Triple::WatchOS: | |||
1577 | Triple.getWatchOSVersion(Major, Minor, Micro); | |||
1578 | break; | |||
1579 | default: | |||
1580 | llvm_unreachable("Unexpected OS type")::llvm::llvm_unreachable_internal("Unexpected OS type", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 1580); | |||
1581 | break; | |||
1582 | } | |||
1583 | ||||
1584 | std::string OSVersion; | |||
1585 | llvm::raw_string_ostream(OSVersion) << Major << '.' << Minor << '.' << Micro; | |||
1586 | return OSVersion; | |||
1587 | } | |||
1588 | ||||
1589 | /// Tries to infer the target OS from the -arch. | |||
1590 | Optional<DarwinPlatform> | |||
1591 | inferDeploymentTargetFromArch(DerivedArgList &Args, const Darwin &Toolchain, | |||
1592 | const llvm::Triple &Triple, | |||
1593 | const Driver &TheDriver) { | |||
1594 | llvm::Triple::OSType OSTy = llvm::Triple::UnknownOS; | |||
1595 | ||||
1596 | StringRef MachOArchName = Toolchain.getMachOArchName(Args); | |||
1597 | if (MachOArchName == "armv7" || MachOArchName == "armv7s" || | |||
1598 | MachOArchName == "arm64") | |||
1599 | OSTy = llvm::Triple::IOS; | |||
1600 | else if (MachOArchName == "armv7k") | |||
1601 | OSTy = llvm::Triple::WatchOS; | |||
1602 | else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" && | |||
1603 | MachOArchName != "armv7em") | |||
1604 | OSTy = llvm::Triple::MacOSX; | |||
1605 | ||||
1606 | if (OSTy == llvm::Triple::UnknownOS) | |||
1607 | return None; | |||
1608 | return DarwinPlatform::createFromArch(OSTy, | |||
1609 | getOSVersion(OSTy, Triple, TheDriver)); | |||
1610 | } | |||
1611 | ||||
1612 | /// Returns the deployment target that's specified using the -target option. | |||
1613 | Optional<DarwinPlatform> getDeploymentTargetFromTargetArg( | |||
1614 | DerivedArgList &Args, const llvm::Triple &Triple, const Driver &TheDriver) { | |||
1615 | if (!Args.hasArg(options::OPT_target)) | |||
1616 | return None; | |||
1617 | if (Triple.getOS() == llvm::Triple::Darwin || | |||
1618 | Triple.getOS() == llvm::Triple::UnknownOS) | |||
1619 | return None; | |||
1620 | std::string OSVersion = getOSVersion(Triple.getOS(), Triple, TheDriver); | |||
1621 | return DarwinPlatform::createFromTarget(Triple, OSVersion, | |||
1622 | Args.getLastArg(options::OPT_target)); | |||
1623 | } | |||
1624 | ||||
1625 | Optional<DarwinSDKInfo> parseSDKSettings(llvm::vfs::FileSystem &VFS, | |||
1626 | const ArgList &Args, | |||
1627 | const Driver &TheDriver) { | |||
1628 | const Arg *A = Args.getLastArg(options::OPT_isysroot); | |||
1629 | if (!A) | |||
1630 | return None; | |||
1631 | StringRef isysroot = A->getValue(); | |||
1632 | auto SDKInfoOrErr = driver::parseDarwinSDKInfo(VFS, isysroot); | |||
1633 | if (!SDKInfoOrErr) { | |||
1634 | llvm::consumeError(SDKInfoOrErr.takeError()); | |||
1635 | TheDriver.Diag(diag::warn_drv_darwin_sdk_invalid_settings); | |||
1636 | return None; | |||
1637 | } | |||
1638 | return *SDKInfoOrErr; | |||
1639 | } | |||
1640 | ||||
1641 | } // namespace | |||
1642 | ||||
1643 | void Darwin::AddDeploymentTarget(DerivedArgList &Args) const { | |||
1644 | const OptTable &Opts = getDriver().getOpts(); | |||
1645 | ||||
1646 | // Support allowing the SDKROOT environment variable used by xcrun and other | |||
1647 | // Xcode tools to define the default sysroot, by making it the default for | |||
1648 | // isysroot. | |||
1649 | if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) { | |||
1650 | // Warn if the path does not exist. | |||
1651 | if (!getVFS().exists(A->getValue())) | |||
1652 | getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue(); | |||
1653 | } else { | |||
1654 | if (char *env = ::getenv("SDKROOT")) { | |||
1655 | // We only use this value as the default if it is an absolute path, | |||
1656 | // exists, and it is not the root path. | |||
1657 | if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) && | |||
1658 | StringRef(env) != "/") { | |||
1659 | Args.append(Args.MakeSeparateArg( | |||
1660 | nullptr, Opts.getOption(options::OPT_isysroot), env)); | |||
1661 | } | |||
1662 | } | |||
1663 | } | |||
1664 | ||||
1665 | // Read the SDKSettings.json file for more information, like the SDK version | |||
1666 | // that we can pass down to the compiler. | |||
1667 | SDKInfo = parseSDKSettings(getVFS(), Args, getDriver()); | |||
1668 | ||||
1669 | // The OS and the version can be specified using the -target argument. | |||
1670 | Optional<DarwinPlatform> OSTarget = | |||
1671 | getDeploymentTargetFromTargetArg(Args, getTriple(), getDriver()); | |||
1672 | if (OSTarget) { | |||
1673 | Optional<DarwinPlatform> OSVersionArgTarget = | |||
1674 | getDeploymentTargetFromOSVersionArg(Args, getDriver()); | |||
1675 | if (OSVersionArgTarget) { | |||
1676 | unsigned TargetMajor, TargetMinor, TargetMicro; | |||
1677 | bool TargetExtra; | |||
1678 | unsigned ArgMajor, ArgMinor, ArgMicro; | |||
1679 | bool ArgExtra; | |||
1680 | if (OSTarget->getPlatform() != OSVersionArgTarget->getPlatform() || | |||
1681 | (Driver::GetReleaseVersion(OSTarget->getOSVersion(), TargetMajor, | |||
1682 | TargetMinor, TargetMicro, TargetExtra) && | |||
1683 | Driver::GetReleaseVersion(OSVersionArgTarget->getOSVersion(), | |||
1684 | ArgMajor, ArgMinor, ArgMicro, ArgExtra) && | |||
1685 | (VersionTuple(TargetMajor, TargetMinor, TargetMicro) != | |||
1686 | VersionTuple(ArgMajor, ArgMinor, ArgMicro) || | |||
1687 | TargetExtra != ArgExtra))) { | |||
1688 | // Select the OS version from the -m<os>-version-min argument when | |||
1689 | // the -target does not include an OS version. | |||
1690 | if (OSTarget->getPlatform() == OSVersionArgTarget->getPlatform() && | |||
1691 | !OSTarget->hasOSVersion()) { | |||
1692 | OSTarget->setOSVersion(OSVersionArgTarget->getOSVersion()); | |||
1693 | } else { | |||
1694 | // Warn about -m<os>-version-min that doesn't match the OS version | |||
1695 | // that's specified in the target. | |||
1696 | std::string OSVersionArg = | |||
1697 | OSVersionArgTarget->getAsString(Args, Opts); | |||
1698 | std::string TargetArg = OSTarget->getAsString(Args, Opts); | |||
1699 | getDriver().Diag(clang::diag::warn_drv_overriding_flag_option) | |||
1700 | << OSVersionArg << TargetArg; | |||
1701 | } | |||
1702 | } | |||
1703 | } | |||
1704 | } else { | |||
1705 | // The OS target can be specified using the -m<os>version-min argument. | |||
1706 | OSTarget = getDeploymentTargetFromOSVersionArg(Args, getDriver()); | |||
1707 | // If no deployment target was specified on the command line, check for | |||
1708 | // environment defines. | |||
1709 | if (!OSTarget) { | |||
1710 | OSTarget = | |||
1711 | getDeploymentTargetFromEnvironmentVariables(getDriver(), getTriple()); | |||
1712 | if (OSTarget) { | |||
1713 | // Don't infer simulator from the arch when the SDK is also specified. | |||
1714 | Optional<DarwinPlatform> SDKTarget = | |||
1715 | inferDeploymentTargetFromSDK(Args, SDKInfo); | |||
1716 | if (SDKTarget) | |||
1717 | OSTarget->setEnvironment(SDKTarget->getEnvironment()); | |||
1718 | } | |||
1719 | } | |||
1720 | // If there is no command-line argument to specify the Target version and | |||
1721 | // no environment variable defined, see if we can set the default based | |||
1722 | // on -isysroot using SDKSettings.json if it exists. | |||
1723 | if (!OSTarget) { | |||
1724 | OSTarget = inferDeploymentTargetFromSDK(Args, SDKInfo); | |||
1725 | /// If the target was successfully constructed from the SDK path, try to | |||
1726 | /// infer the SDK info if the SDK doesn't have it. | |||
1727 | if (OSTarget && !SDKInfo) | |||
1728 | SDKInfo = OSTarget->inferSDKInfo(); | |||
1729 | } | |||
1730 | // If no OS targets have been specified, try to guess platform from -target | |||
1731 | // or arch name and compute the version from the triple. | |||
1732 | if (!OSTarget) | |||
1733 | OSTarget = | |||
1734 | inferDeploymentTargetFromArch(Args, *this, getTriple(), getDriver()); | |||
1735 | } | |||
1736 | ||||
1737 | 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-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 1737, __PRETTY_FUNCTION__)); | |||
1738 | OSTarget->addOSVersionMinArgument(Args, Opts); | |||
1739 | DarwinPlatformKind Platform = OSTarget->getPlatform(); | |||
1740 | ||||
1741 | unsigned Major, Minor, Micro; | |||
1742 | bool HadExtra; | |||
1743 | // Set the tool chain target information. | |||
1744 | if (Platform == MacOS) { | |||
1745 | if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor, | |||
1746 | Micro, HadExtra) || | |||
1747 | HadExtra || Major != 10 || Minor >= 100 || Micro >= 100) | |||
1748 | getDriver().Diag(diag::err_drv_invalid_version_number) | |||
1749 | << OSTarget->getAsString(Args, Opts); | |||
1750 | } else if (Platform == IPhoneOS) { | |||
1751 | if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor, | |||
1752 | Micro, HadExtra) || | |||
1753 | HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100) | |||
1754 | getDriver().Diag(diag::err_drv_invalid_version_number) | |||
1755 | << OSTarget->getAsString(Args, Opts); | |||
1756 | ; | |||
1757 | // For 32-bit targets, the deployment target for iOS has to be earlier than | |||
1758 | // iOS 11. | |||
1759 | if (getTriple().isArch32Bit() && Major >= 11) { | |||
1760 | // If the deployment target is explicitly specified, print a diagnostic. | |||
1761 | if (OSTarget->isExplicitlySpecified()) { | |||
1762 | getDriver().Diag(diag::warn_invalid_ios_deployment_target) | |||
1763 | << OSTarget->getAsString(Args, Opts); | |||
1764 | // Otherwise, set it to 10.99.99. | |||
1765 | } else { | |||
1766 | Major = 10; | |||
1767 | Minor = 99; | |||
1768 | Micro = 99; | |||
1769 | } | |||
1770 | } | |||
1771 | } else if (Platform == TvOS) { | |||
1772 | if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor, | |||
1773 | Micro, HadExtra) || | |||
1774 | HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100) | |||
1775 | getDriver().Diag(diag::err_drv_invalid_version_number) | |||
1776 | << OSTarget->getAsString(Args, Opts); | |||
1777 | } else if (Platform == WatchOS) { | |||
1778 | if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor, | |||
1779 | Micro, HadExtra) || | |||
1780 | HadExtra || Major >= 10 || Minor >= 100 || Micro >= 100) | |||
1781 | getDriver().Diag(diag::err_drv_invalid_version_number) | |||
1782 | << OSTarget->getAsString(Args, Opts); | |||
1783 | } else | |||
1784 | llvm_unreachable("unknown kind of Darwin platform")::llvm::llvm_unreachable_internal("unknown kind of Darwin platform" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 1784); | |||
1785 | ||||
1786 | DarwinEnvironmentKind Environment = OSTarget->getEnvironment(); | |||
1787 | // Recognize iOS targets with an x86 architecture as the iOS simulator. | |||
1788 | if (Environment == NativeEnvironment && Platform != MacOS && | |||
1789 | OSTarget->canInferSimulatorFromArch() && | |||
1790 | (getTriple().getArch() == llvm::Triple::x86 || | |||
1791 | getTriple().getArch() == llvm::Triple::x86_64)) | |||
1792 | Environment = Simulator; | |||
1793 | ||||
1794 | setTarget(Platform, Environment, Major, Minor, Micro); | |||
1795 | ||||
1796 | if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) { | |||
1797 | StringRef SDK = getSDKName(A->getValue()); | |||
1798 | if (SDK.size() > 0) { | |||
1799 | size_t StartVer = SDK.find_first_of("0123456789"); | |||
1800 | StringRef SDKName = SDK.slice(0, StartVer); | |||
1801 | if (!SDKName.startswith(getPlatformFamily())) | |||
1802 | getDriver().Diag(diag::warn_incompatible_sysroot) | |||
1803 | << SDKName << getPlatformFamily(); | |||
1804 | } | |||
1805 | } | |||
1806 | } | |||
1807 | ||||
1808 | // Returns the effective header sysroot path to use. This comes either from | |||
1809 | // -isysroot or --sysroot. | |||
1810 | llvm::StringRef DarwinClang::GetHeaderSysroot(const llvm::opt::ArgList &DriverArgs) const { | |||
1811 | if(DriverArgs.hasArg(options::OPT_isysroot)) | |||
1812 | return DriverArgs.getLastArgValue(options::OPT_isysroot); | |||
1813 | if (!getDriver().SysRoot.empty()) | |||
1814 | return getDriver().SysRoot; | |||
1815 | return "/"; | |||
1816 | } | |||
1817 | ||||
1818 | void DarwinClang::AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, | |||
1819 | llvm::opt::ArgStringList &CC1Args) const { | |||
1820 | const Driver &D = getDriver(); | |||
1821 | ||||
1822 | llvm::StringRef Sysroot = GetHeaderSysroot(DriverArgs); | |||
1823 | ||||
1824 | bool NoStdInc = DriverArgs.hasArg(options::OPT_nostdinc); | |||
1825 | bool NoStdlibInc = DriverArgs.hasArg(options::OPT_nostdlibinc); | |||
1826 | bool NoBuiltinInc = DriverArgs.hasArg(options::OPT_nobuiltininc); | |||
1827 | ||||
1828 | // Add <sysroot>/usr/local/include | |||
1829 | if (!NoStdInc && !NoStdlibInc) { | |||
1830 | SmallString<128> P(Sysroot); | |||
1831 | llvm::sys::path::append(P, "usr", "local", "include"); | |||
1832 | addSystemInclude(DriverArgs, CC1Args, P); | |||
1833 | } | |||
1834 | ||||
1835 | // Add the Clang builtin headers (<resource>/include) | |||
1836 | if (!NoStdInc && !NoBuiltinInc) { | |||
1837 | SmallString<128> P(D.ResourceDir); | |||
1838 | llvm::sys::path::append(P, "include"); | |||
1839 | addSystemInclude(DriverArgs, CC1Args, P); | |||
1840 | } | |||
1841 | ||||
1842 | if (NoStdInc || NoStdlibInc) | |||
1843 | return; | |||
1844 | ||||
1845 | // Check for configure-time C include directories. | |||
1846 | llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS""); | |||
1847 | if (!CIncludeDirs.empty()) { | |||
1848 | llvm::SmallVector<llvm::StringRef, 5> dirs; | |||
1849 | CIncludeDirs.split(dirs, ":"); | |||
1850 | for (llvm::StringRef dir : dirs) { | |||
1851 | llvm::StringRef Prefix = | |||
1852 | llvm::sys::path::is_absolute(dir) ? llvm::StringRef(Sysroot) : ""; | |||
1853 | addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir); | |||
1854 | } | |||
1855 | } else { | |||
1856 | // Otherwise, add <sysroot>/usr/include. | |||
1857 | SmallString<128> P(Sysroot); | |||
1858 | llvm::sys::path::append(P, "usr", "include"); | |||
1859 | addExternCSystemInclude(DriverArgs, CC1Args, P.str()); | |||
1860 | } | |||
1861 | } | |||
1862 | ||||
1863 | bool DarwinClang::AddGnuCPlusPlusIncludePaths(const llvm::opt::ArgList &DriverArgs, | |||
1864 | llvm::opt::ArgStringList &CC1Args, | |||
1865 | llvm::SmallString<128> Base, | |||
1866 | llvm::StringRef Version, | |||
1867 | llvm::StringRef ArchDir, | |||
1868 | llvm::StringRef BitDir) const { | |||
1869 | llvm::sys::path::append(Base, Version); | |||
1870 | ||||
1871 | // Add the base dir | |||
1872 | addSystemInclude(DriverArgs, CC1Args, Base); | |||
1873 | ||||
1874 | // Add the multilib dirs | |||
1875 | { | |||
1876 | llvm::SmallString<128> P = Base; | |||
1877 | if (!ArchDir.empty()) | |||
1878 | llvm::sys::path::append(P, ArchDir); | |||
1879 | if (!BitDir.empty()) | |||
1880 | llvm::sys::path::append(P, BitDir); | |||
1881 | addSystemInclude(DriverArgs, CC1Args, P); | |||
1882 | } | |||
1883 | ||||
1884 | // Add the backward dir | |||
1885 | { | |||
1886 | llvm::SmallString<128> P = Base; | |||
1887 | llvm::sys::path::append(P, "backward"); | |||
1888 | addSystemInclude(DriverArgs, CC1Args, P); | |||
1889 | } | |||
1890 | ||||
1891 | return getVFS().exists(Base); | |||
1892 | } | |||
1893 | ||||
1894 | void DarwinClang::AddClangCXXStdlibIncludeArgs( | |||
1895 | const llvm::opt::ArgList &DriverArgs, | |||
1896 | llvm::opt::ArgStringList &CC1Args) const { | |||
1897 | // The implementation from a base class will pass through the -stdlib to | |||
1898 | // CC1Args. | |||
1899 | // FIXME: this should not be necessary, remove usages in the frontend | |||
1900 | // (e.g. HeaderSearchOptions::UseLibcxx) and don't pipe -stdlib. | |||
1901 | // Also check whether this is used for setting library search paths. | |||
1902 | ToolChain::AddClangCXXStdlibIncludeArgs(DriverArgs, CC1Args); | |||
1903 | ||||
1904 | if (DriverArgs.hasArg(options::OPT_nostdlibinc) || | |||
1905 | DriverArgs.hasArg(options::OPT_nostdincxx)) | |||
1906 | return; | |||
1907 | ||||
1908 | llvm::StringRef Sysroot = GetHeaderSysroot(DriverArgs); | |||
1909 | ||||
1910 | switch (GetCXXStdlibType(DriverArgs)) { | |||
1911 | case ToolChain::CST_Libcxx: { | |||
1912 | // On Darwin, libc++ is installed alongside the compiler in | |||
1913 | // include/c++/v1, so get from '<install>/bin' to '<install>/include/c++/v1'. | |||
1914 | { | |||
1915 | llvm::SmallString<128> P = llvm::StringRef(getDriver().getInstalledDir()); | |||
1916 | // Note that P can be relative, so we have to '..' and not parent_path. | |||
1917 | llvm::sys::path::append(P, "..", "include", "c++", "v1"); | |||
1918 | addSystemInclude(DriverArgs, CC1Args, P); | |||
1919 | } | |||
1920 | // Also add <sysroot>/usr/include/c++/v1 unless -nostdinc is used, | |||
1921 | // to match the legacy behavior in CC1. | |||
1922 | if (!DriverArgs.hasArg(options::OPT_nostdinc)) { | |||
1923 | llvm::SmallString<128> P = Sysroot; | |||
1924 | llvm::sys::path::append(P, "usr", "include", "c++", "v1"); | |||
1925 | addSystemInclude(DriverArgs, CC1Args, P); | |||
1926 | } | |||
1927 | break; | |||
1928 | } | |||
1929 | ||||
1930 | case ToolChain::CST_Libstdcxx: | |||
1931 | llvm::SmallString<128> UsrIncludeCxx = Sysroot; | |||
1932 | llvm::sys::path::append(UsrIncludeCxx, "usr", "include", "c++"); | |||
1933 | ||||
1934 | llvm::Triple::ArchType arch = getTriple().getArch(); | |||
1935 | bool IsBaseFound = true; | |||
1936 | switch (arch) { | |||
1937 | default: break; | |||
1938 | ||||
1939 | case llvm::Triple::ppc: | |||
1940 | case llvm::Triple::ppc64: | |||
1941 | IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx, | |||
1942 | "4.2.1", | |||
1943 | "powerpc-apple-darwin10", | |||
1944 | arch == llvm::Triple::ppc64 ? "ppc64" : ""); | |||
1945 | IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx, | |||
1946 | "4.0.0", "powerpc-apple-darwin10", | |||
1947 | arch == llvm::Triple::ppc64 ? "ppc64" : ""); | |||
1948 | break; | |||
1949 | ||||
1950 | case llvm::Triple::x86: | |||
1951 | case llvm::Triple::x86_64: | |||
1952 | IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx, | |||
1953 | "4.2.1", | |||
1954 | "i686-apple-darwin10", | |||
1955 | arch == llvm::Triple::x86_64 ? "x86_64" : ""); | |||
1956 | IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx, | |||
1957 | "4.0.0", "i686-apple-darwin8", | |||
1958 | ""); | |||
1959 | break; | |||
1960 | ||||
1961 | case llvm::Triple::arm: | |||
1962 | case llvm::Triple::thumb: | |||
1963 | IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx, | |||
1964 | "4.2.1", | |||
1965 | "arm-apple-darwin10", | |||
1966 | "v7"); | |||
1967 | IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx, | |||
1968 | "4.2.1", | |||
1969 | "arm-apple-darwin10", | |||
1970 | "v6"); | |||
1971 | break; | |||
1972 | ||||
1973 | case llvm::Triple::aarch64: | |||
1974 | IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx, | |||
1975 | "4.2.1", | |||
1976 | "arm64-apple-darwin10", | |||
1977 | ""); | |||
1978 | break; | |||
1979 | } | |||
1980 | ||||
1981 | if (!IsBaseFound) { | |||
1982 | getDriver().Diag(diag::warn_drv_libstdcxx_not_found); | |||
1983 | } | |||
1984 | ||||
1985 | break; | |||
1986 | } | |||
1987 | } | |||
1988 | void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args, | |||
1989 | ArgStringList &CmdArgs) const { | |||
1990 | CXXStdlibType Type = GetCXXStdlibType(Args); | |||
1991 | ||||
1992 | switch (Type) { | |||
1993 | case ToolChain::CST_Libcxx: | |||
1994 | CmdArgs.push_back("-lc++"); | |||
1995 | break; | |||
1996 | ||||
1997 | case ToolChain::CST_Libstdcxx: | |||
1998 | // Unfortunately, -lstdc++ doesn't always exist in the standard search path; | |||
1999 | // it was previously found in the gcc lib dir. However, for all the Darwin | |||
2000 | // platforms we care about it was -lstdc++.6, so we search for that | |||
2001 | // explicitly if we can't see an obvious -lstdc++ candidate. | |||
2002 | ||||
2003 | // Check in the sysroot first. | |||
2004 | if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) { | |||
2005 | SmallString<128> P(A->getValue()); | |||
2006 | llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib"); | |||
2007 | ||||
2008 | if (!getVFS().exists(P)) { | |||
2009 | llvm::sys::path::remove_filename(P); | |||
2010 | llvm::sys::path::append(P, "libstdc++.6.dylib"); | |||
2011 | if (getVFS().exists(P)) { | |||
2012 | CmdArgs.push_back(Args.MakeArgString(P)); | |||
2013 | return; | |||
2014 | } | |||
2015 | } | |||
2016 | } | |||
2017 | ||||
2018 | // Otherwise, look in the root. | |||
2019 | // FIXME: This should be removed someday when we don't have to care about | |||
2020 | // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist. | |||
2021 | if (!getVFS().exists("/usr/lib/libstdc++.dylib") && | |||
2022 | getVFS().exists("/usr/lib/libstdc++.6.dylib")) { | |||
2023 | CmdArgs.push_back("/usr/lib/libstdc++.6.dylib"); | |||
2024 | return; | |||
2025 | } | |||
2026 | ||||
2027 | // Otherwise, let the linker search. | |||
2028 | CmdArgs.push_back("-lstdc++"); | |||
2029 | break; | |||
2030 | } | |||
2031 | } | |||
2032 | ||||
2033 | void DarwinClang::AddCCKextLibArgs(const ArgList &Args, | |||
2034 | ArgStringList &CmdArgs) const { | |||
2035 | // For Darwin platforms, use the compiler-rt-based support library | |||
2036 | // instead of the gcc-provided one (which is also incidentally | |||
2037 | // only present in the gcc lib dir, which makes it hard to find). | |||
2038 | ||||
2039 | SmallString<128> P(getDriver().ResourceDir); | |||
2040 | llvm::sys::path::append(P, "lib", "darwin"); | |||
2041 | ||||
2042 | // Use the newer cc_kext for iOS ARM after 6.0. | |||
2043 | if (isTargetWatchOS()) { | |||
2044 | llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a"); | |||
2045 | } else if (isTargetTvOS()) { | |||
2046 | llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a"); | |||
2047 | } else if (isTargetIPhoneOS()) { | |||
2048 | llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a"); | |||
2049 | } else { | |||
2050 | llvm::sys::path::append(P, "libclang_rt.cc_kext.a"); | |||
2051 | } | |||
2052 | ||||
2053 | // For now, allow missing resource libraries to support developers who may | |||
2054 | // not have compiler-rt checked out or integrated into their build. | |||
2055 | if (getVFS().exists(P)) | |||
2056 | CmdArgs.push_back(Args.MakeArgString(P)); | |||
2057 | } | |||
2058 | ||||
2059 | DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args, | |||
2060 | StringRef BoundArch, | |||
2061 | Action::OffloadKind) const { | |||
2062 | DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); | |||
2063 | const OptTable &Opts = getDriver().getOpts(); | |||
2064 | ||||
2065 | // FIXME: We really want to get out of the tool chain level argument | |||
2066 | // translation business, as it makes the driver functionality much | |||
2067 | // more opaque. For now, we follow gcc closely solely for the | |||
2068 | // purpose of easily achieving feature parity & testability. Once we | |||
2069 | // have something that works, we should reevaluate each translation | |||
2070 | // and try to push it down into tool specific logic. | |||
2071 | ||||
2072 | for (Arg *A : Args) { | |||
2073 | if (A->getOption().matches(options::OPT_Xarch__)) { | |||
2074 | // Skip this argument unless the architecture matches either the toolchain | |||
2075 | // triple arch, or the arch being bound. | |||
2076 | llvm::Triple::ArchType XarchArch = | |||
2077 | tools::darwin::getArchTypeForMachOArchName(A->getValue(0)); | |||
2078 | if (!(XarchArch == getArch() || | |||
2079 | (!BoundArch.empty() && | |||
2080 | XarchArch == | |||
2081 | tools::darwin::getArchTypeForMachOArchName(BoundArch)))) | |||
2082 | continue; | |||
2083 | ||||
2084 | Arg *OriginalArg = A; | |||
2085 | unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1)); | |||
2086 | unsigned Prev = Index; | |||
2087 | std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index)); | |||
2088 | ||||
2089 | // If the argument parsing failed or more than one argument was | |||
2090 | // consumed, the -Xarch_ argument's parameter tried to consume | |||
2091 | // extra arguments. Emit an error and ignore. | |||
2092 | // | |||
2093 | // We also want to disallow any options which would alter the | |||
2094 | // driver behavior; that isn't going to work in our model. We | |||
2095 | // use isDriverOption() as an approximation, although things | |||
2096 | // like -O4 are going to slip through. | |||
2097 | if (!XarchArg || Index > Prev + 1) { | |||
2098 | getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args) | |||
2099 | << A->getAsString(Args); | |||
2100 | continue; | |||
2101 | } else if (XarchArg->getOption().hasFlag(options::DriverOption)) { | |||
2102 | getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver) | |||
2103 | << A->getAsString(Args); | |||
2104 | continue; | |||
2105 | } | |||
2106 | ||||
2107 | XarchArg->setBaseArg(A); | |||
2108 | ||||
2109 | A = XarchArg.release(); | |||
2110 | DAL->AddSynthesizedArg(A); | |||
2111 | ||||
2112 | // Linker input arguments require custom handling. The problem is that we | |||
2113 | // have already constructed the phase actions, so we can not treat them as | |||
2114 | // "input arguments". | |||
2115 | if (A->getOption().hasFlag(options::LinkerInput)) { | |||
2116 | // Convert the argument into individual Zlinker_input_args. | |||
2117 | for (const char *Value : A->getValues()) { | |||
2118 | DAL->AddSeparateArg( | |||
2119 | OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value); | |||
2120 | } | |||
2121 | continue; | |||
2122 | } | |||
2123 | } | |||
2124 | ||||
2125 | // Sob. These is strictly gcc compatible for the time being. Apple | |||
2126 | // gcc translates options twice, which means that self-expanding | |||
2127 | // options add duplicates. | |||
2128 | switch ((options::ID)A->getOption().getID()) { | |||
2129 | default: | |||
2130 | DAL->append(A); | |||
2131 | break; | |||
2132 | ||||
2133 | case options::OPT_mkernel: | |||
2134 | case options::OPT_fapple_kext: | |||
2135 | DAL->append(A); | |||
2136 | DAL->AddFlagArg(A, Opts.getOption(options::OPT_static)); | |||
2137 | break; | |||
2138 | ||||
2139 | case options::OPT_dependency_file: | |||
2140 | DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue()); | |||
2141 | break; | |||
2142 | ||||
2143 | case options::OPT_gfull: | |||
2144 | DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag)); | |||
2145 | DAL->AddFlagArg( | |||
2146 | A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols)); | |||
2147 | break; | |||
2148 | ||||
2149 | case options::OPT_gused: | |||
2150 | DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag)); | |||
2151 | DAL->AddFlagArg( | |||
2152 | A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols)); | |||
2153 | break; | |||
2154 | ||||
2155 | case options::OPT_shared: | |||
2156 | DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib)); | |||
2157 | break; | |||
2158 | ||||
2159 | case options::OPT_fconstant_cfstrings: | |||
2160 | DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings)); | |||
2161 | break; | |||
2162 | ||||
2163 | case options::OPT_fno_constant_cfstrings: | |||
2164 | DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings)); | |||
2165 | break; | |||
2166 | ||||
2167 | case options::OPT_Wnonportable_cfstrings: | |||
2168 | DAL->AddFlagArg(A, | |||
2169 | Opts.getOption(options::OPT_mwarn_nonportable_cfstrings)); | |||
2170 | break; | |||
2171 | ||||
2172 | case options::OPT_Wno_nonportable_cfstrings: | |||
2173 | DAL->AddFlagArg( | |||
2174 | A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings)); | |||
2175 | break; | |||
2176 | ||||
2177 | case options::OPT_fpascal_strings: | |||
2178 | DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings)); | |||
2179 | break; | |||
2180 | ||||
2181 | case options::OPT_fno_pascal_strings: | |||
2182 | DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings)); | |||
2183 | break; | |||
2184 | } | |||
2185 | } | |||
2186 | ||||
2187 | if (getTriple().getArch() == llvm::Triple::x86 || | |||
2188 | getTriple().getArch() == llvm::Triple::x86_64) | |||
2189 | if (!Args.hasArgNoClaim(options::OPT_mtune_EQ)) | |||
2190 | DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ), | |||
2191 | "core2"); | |||
2192 | ||||
2193 | // Add the arch options based on the particular spelling of -arch, to match | |||
2194 | // how the driver driver works. | |||
2195 | if (!BoundArch.empty()) { | |||
2196 | StringRef Name = BoundArch; | |||
2197 | const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ); | |||
2198 | const Option MArch = Opts.getOption(clang::driver::options::OPT_march_EQ); | |||
2199 | ||||
2200 | // This code must be kept in sync with LLVM's getArchTypeForDarwinArch, | |||
2201 | // which defines the list of which architectures we accept. | |||
2202 | if (Name == "ppc") | |||
2203 | ; | |||
2204 | else if (Name == "ppc601") | |||
2205 | DAL->AddJoinedArg(nullptr, MCpu, "601"); | |||
2206 | else if (Name == "ppc603") | |||
2207 | DAL->AddJoinedArg(nullptr, MCpu, "603"); | |||
2208 | else if (Name == "ppc604") | |||
2209 | DAL->AddJoinedArg(nullptr, MCpu, "604"); | |||
2210 | else if (Name == "ppc604e") | |||
2211 | DAL->AddJoinedArg(nullptr, MCpu, "604e"); | |||
2212 | else if (Name == "ppc750") | |||
2213 | DAL->AddJoinedArg(nullptr, MCpu, "750"); | |||
2214 | else if (Name == "ppc7400") | |||
2215 | DAL->AddJoinedArg(nullptr, MCpu, "7400"); | |||
2216 | else if (Name == "ppc7450") | |||
2217 | DAL->AddJoinedArg(nullptr, MCpu, "7450"); | |||
2218 | else if (Name == "ppc970") | |||
2219 | DAL->AddJoinedArg(nullptr, MCpu, "970"); | |||
2220 | ||||
2221 | else if (Name == "ppc64" || Name == "ppc64le") | |||
2222 | DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64)); | |||
2223 | ||||
2224 | else if (Name == "i386") | |||
2225 | ; | |||
2226 | else if (Name == "i486") | |||
2227 | DAL->AddJoinedArg(nullptr, MArch, "i486"); | |||
2228 | else if (Name == "i586") | |||
2229 | DAL->AddJoinedArg(nullptr, MArch, "i586"); | |||
2230 | else if (Name == "i686") | |||
2231 | DAL->AddJoinedArg(nullptr, MArch, "i686"); | |||
2232 | else if (Name == "pentium") | |||
2233 | DAL->AddJoinedArg(nullptr, MArch, "pentium"); | |||
2234 | else if (Name == "pentium2") | |||
2235 | DAL->AddJoinedArg(nullptr, MArch, "pentium2"); | |||
2236 | else if (Name == "pentpro") | |||
2237 | DAL->AddJoinedArg(nullptr, MArch, "pentiumpro"); | |||
2238 | else if (Name == "pentIIm3") | |||
2239 | DAL->AddJoinedArg(nullptr, MArch, "pentium2"); | |||
2240 | ||||
2241 | else if (Name == "x86_64" || Name == "x86_64h") | |||
2242 | DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64)); | |||
2243 | ||||
2244 | else if (Name == "arm") | |||
2245 | DAL->AddJoinedArg(nullptr, MArch, "armv4t"); | |||
2246 | else if (Name == "armv4t") | |||
2247 | DAL->AddJoinedArg(nullptr, MArch, "armv4t"); | |||
2248 | else if (Name == "armv5") | |||
2249 | DAL->AddJoinedArg(nullptr, MArch, "armv5tej"); | |||
2250 | else if (Name == "xscale") | |||
2251 | DAL->AddJoinedArg(nullptr, MArch, "xscale"); | |||
2252 | else if (Name == "armv6") | |||
2253 | DAL->AddJoinedArg(nullptr, MArch, "armv6k"); | |||
2254 | else if (Name == "armv6m") | |||
2255 | DAL->AddJoinedArg(nullptr, MArch, "armv6m"); | |||
2256 | else if (Name == "armv7") | |||
2257 | DAL->AddJoinedArg(nullptr, MArch, "armv7a"); | |||
2258 | else if (Name == "armv7em") | |||
2259 | DAL->AddJoinedArg(nullptr, MArch, "armv7em"); | |||
2260 | else if (Name == "armv7k") | |||
2261 | DAL->AddJoinedArg(nullptr, MArch, "armv7k"); | |||
2262 | else if (Name == "armv7m") | |||
2263 | DAL->AddJoinedArg(nullptr, MArch, "armv7m"); | |||
2264 | else if (Name == "armv7s") | |||
2265 | DAL->AddJoinedArg(nullptr, MArch, "armv7s"); | |||
2266 | } | |||
2267 | ||||
2268 | return DAL; | |||
2269 | } | |||
2270 | ||||
2271 | void MachO::AddLinkRuntimeLibArgs(const ArgList &Args, | |||
2272 | ArgStringList &CmdArgs, | |||
2273 | bool ForceLinkBuiltinRT) const { | |||
2274 | // Embedded targets are simple at the moment, not supporting sanitizers and | |||
2275 | // with different libraries for each member of the product { static, PIC } x | |||
2276 | // { hard-float, soft-float } | |||
2277 | llvm::SmallString<32> CompilerRT = StringRef(""); | |||
2278 | CompilerRT += | |||
2279 | (tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard) | |||
2280 | ? "hard" | |||
2281 | : "soft"; | |||
2282 | CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic" : "_static"; | |||
2283 | ||||
2284 | AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, RLO_IsEmbedded); | |||
2285 | } | |||
2286 | ||||
2287 | bool Darwin::isAlignedAllocationUnavailable() const { | |||
2288 | llvm::Triple::OSType OS; | |||
2289 | ||||
2290 | switch (TargetPlatform) { | |||
2291 | case MacOS: // Earlier than 10.13. | |||
2292 | OS = llvm::Triple::MacOSX; | |||
2293 | break; | |||
2294 | case IPhoneOS: | |||
2295 | OS = llvm::Triple::IOS; | |||
2296 | break; | |||
2297 | case TvOS: // Earlier than 11.0. | |||
2298 | OS = llvm::Triple::TvOS; | |||
2299 | break; | |||
2300 | case WatchOS: // Earlier than 4.0. | |||
2301 | OS = llvm::Triple::WatchOS; | |||
2302 | break; | |||
2303 | } | |||
2304 | ||||
2305 | return TargetVersion < alignedAllocMinVersion(OS); | |||
2306 | } | |||
2307 | ||||
2308 | void Darwin::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, | |||
2309 | llvm::opt::ArgStringList &CC1Args, | |||
2310 | Action::OffloadKind DeviceOffloadKind) const { | |||
2311 | // Pass "-faligned-alloc-unavailable" only when the user hasn't manually | |||
2312 | // enabled or disabled aligned allocations. | |||
2313 | if (!DriverArgs.hasArgNoClaim(options::OPT_faligned_allocation, | |||
2314 | options::OPT_fno_aligned_allocation) && | |||
2315 | isAlignedAllocationUnavailable()) | |||
2316 | CC1Args.push_back("-faligned-alloc-unavailable"); | |||
2317 | ||||
2318 | if (SDKInfo) { | |||
2319 | /// Pass the SDK version to the compiler when the SDK information is | |||
2320 | /// available. | |||
2321 | std::string Arg; | |||
2322 | llvm::raw_string_ostream OS(Arg); | |||
2323 | OS << "-target-sdk-version=" << SDKInfo->getVersion(); | |||
2324 | CC1Args.push_back(DriverArgs.MakeArgString(OS.str())); | |||
2325 | } | |||
2326 | } | |||
2327 | ||||
2328 | DerivedArgList * | |||
2329 | Darwin::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch, | |||
2330 | Action::OffloadKind DeviceOffloadKind) const { | |||
2331 | // First get the generic Apple args, before moving onto Darwin-specific ones. | |||
2332 | DerivedArgList *DAL = | |||
2333 | MachO::TranslateArgs(Args, BoundArch, DeviceOffloadKind); | |||
2334 | const OptTable &Opts = getDriver().getOpts(); | |||
2335 | ||||
2336 | // If no architecture is bound, none of the translations here are relevant. | |||
2337 | if (BoundArch.empty()) | |||
| ||||
2338 | return DAL; | |||
2339 | ||||
2340 | // Add an explicit version min argument for the deployment target. We do this | |||
2341 | // after argument translation because -Xarch_ arguments may add a version min | |||
2342 | // argument. | |||
2343 | AddDeploymentTarget(*DAL); | |||
2344 | ||||
2345 | // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext. | |||
2346 | // FIXME: It would be far better to avoid inserting those -static arguments, | |||
2347 | // but we can't check the deployment target in the translation code until | |||
2348 | // it is set here. | |||
2349 | if (isTargetWatchOSBased() || | |||
2350 | (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) { | |||
2351 | for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) { | |||
2352 | Arg *A = *it; | |||
2353 | ++it; | |||
2354 | if (A->getOption().getID() != options::OPT_mkernel && | |||
2355 | A->getOption().getID() != options::OPT_fapple_kext) | |||
2356 | continue; | |||
2357 | 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-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 2357, __PRETTY_FUNCTION__)); | |||
2358 | A = *it; | |||
2359 | 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-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 2360, __PRETTY_FUNCTION__)) | |||
2360 | "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-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 2360, __PRETTY_FUNCTION__)); | |||
2361 | *it = nullptr; | |||
2362 | ++it; | |||
2363 | } | |||
2364 | } | |||
2365 | ||||
2366 | if (!Args.getLastArg(options::OPT_stdlib_EQ) && | |||
2367 | GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) | |||
2368 | DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ), | |||
2369 | "libc++"); | |||
2370 | ||||
2371 | // Validate the C++ standard library choice. | |||
2372 | CXXStdlibType Type = GetCXXStdlibType(*DAL); | |||
2373 | if (Type == ToolChain::CST_Libcxx) { | |||
2374 | // Check whether the target provides libc++. | |||
2375 | StringRef where; | |||
2376 | ||||
2377 | // Complain about targeting iOS < 5.0 in any way. | |||
2378 | if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0)) | |||
2379 | where = "iOS 5.0"; | |||
2380 | ||||
2381 | if (where != StringRef()) { | |||
2382 | getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where; | |||
2383 | } | |||
2384 | } | |||
2385 | ||||
2386 | auto Arch = tools::darwin::getArchTypeForMachOArchName(BoundArch); | |||
2387 | if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) { | |||
2388 | if (Args.hasFlag(options::OPT_fomit_frame_pointer, | |||
2389 | options::OPT_fno_omit_frame_pointer, false)) | |||
2390 | getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target) | |||
2391 | << "-fomit-frame-pointer" << BoundArch; | |||
2392 | } | |||
2393 | ||||
2394 | return DAL; | |||
2395 | } | |||
2396 | ||||
2397 | bool MachO::IsUnwindTablesDefault(const ArgList &Args) const { | |||
2398 | // Unwind tables are not emitted if -fno-exceptions is supplied (except when | |||
2399 | // targeting x86_64). | |||
2400 | return getArch() == llvm::Triple::x86_64 || | |||
2401 | (GetExceptionModel(Args) != llvm::ExceptionHandling::SjLj && | |||
2402 | Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions, | |||
2403 | true)); | |||
2404 | } | |||
2405 | ||||
2406 | bool MachO::UseDwarfDebugFlags() const { | |||
2407 | if (const char *S = ::getenv("RC_DEBUG_OPTIONS")) | |||
2408 | return S[0] != '\0'; | |||
2409 | return false; | |||
2410 | } | |||
2411 | ||||
2412 | llvm::ExceptionHandling Darwin::GetExceptionModel(const ArgList &Args) const { | |||
2413 | // Darwin uses SjLj exceptions on ARM. | |||
2414 | if (getTriple().getArch() != llvm::Triple::arm && | |||
2415 | getTriple().getArch() != llvm::Triple::thumb) | |||
2416 | return llvm::ExceptionHandling::None; | |||
2417 | ||||
2418 | // Only watchOS uses the new DWARF/Compact unwinding method. | |||
2419 | llvm::Triple Triple(ComputeLLVMTriple(Args)); | |||
2420 | if (Triple.isWatchABI()) | |||
2421 | return llvm::ExceptionHandling::DwarfCFI; | |||
2422 | ||||
2423 | return llvm::ExceptionHandling::SjLj; | |||
2424 | } | |||
2425 | ||||
2426 | bool Darwin::SupportsEmbeddedBitcode() const { | |||
2427 | assert(TargetInitialized && "Target not initialized!")((TargetInitialized && "Target not initialized!") ? static_cast <void> (0) : __assert_fail ("TargetInitialized && \"Target not initialized!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 2427, __PRETTY_FUNCTION__)); | |||
2428 | if (isTargetIPhoneOS() && isIPhoneOSVersionLT(6, 0)) | |||
2429 | return false; | |||
2430 | return true; | |||
2431 | } | |||
2432 | ||||
2433 | bool MachO::isPICDefault() const { return true; } | |||
2434 | ||||
2435 | bool MachO::isPIEDefault() const { return false; } | |||
2436 | ||||
2437 | bool MachO::isPICDefaultForced() const { | |||
2438 | return (getArch() == llvm::Triple::x86_64 || | |||
2439 | getArch() == llvm::Triple::aarch64); | |||
2440 | } | |||
2441 | ||||
2442 | bool MachO::SupportsProfiling() const { | |||
2443 | // Profiling instrumentation is only supported on x86. | |||
2444 | return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64; | |||
2445 | } | |||
2446 | ||||
2447 | void Darwin::addMinVersionArgs(const ArgList &Args, | |||
2448 | ArgStringList &CmdArgs) const { | |||
2449 | VersionTuple TargetVersion = getTargetVersion(); | |||
2450 | ||||
2451 | if (isTargetWatchOS()) | |||
2452 | CmdArgs.push_back("-watchos_version_min"); | |||
2453 | else if (isTargetWatchOSSimulator()) | |||
2454 | CmdArgs.push_back("-watchos_simulator_version_min"); | |||
2455 | else if (isTargetTvOS()) | |||
2456 | CmdArgs.push_back("-tvos_version_min"); | |||
2457 | else if (isTargetTvOSSimulator()) | |||
2458 | CmdArgs.push_back("-tvos_simulator_version_min"); | |||
2459 | else if (isTargetIOSSimulator()) | |||
2460 | CmdArgs.push_back("-ios_simulator_version_min"); | |||
2461 | else if (isTargetIOSBased()) | |||
2462 | CmdArgs.push_back("-iphoneos_version_min"); | |||
2463 | else { | |||
2464 | assert(isTargetMacOS() && "unexpected target")((isTargetMacOS() && "unexpected target") ? static_cast <void> (0) : __assert_fail ("isTargetMacOS() && \"unexpected target\"" , "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Driver/ToolChains/Darwin.cpp" , 2464, __PRETTY_FUNCTION__)); | |||
2465 | CmdArgs.push_back("-macosx_version_min"); | |||
2466 | } | |||
2467 | ||||
2468 | CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString())); | |||
2469 | } | |||
2470 | ||||
2471 | void Darwin::addStartObjectFileArgs(const ArgList &Args, | |||
2472 | ArgStringList &CmdArgs) const { | |||
2473 | // Derived from startfile spec. | |||
2474 | if (Args.hasArg(options::OPT_dynamiclib)) { | |||
2475 | // Derived from darwin_dylib1 spec. | |||
2476 | if (isTargetWatchOSBased()) { | |||
2477 | ; // watchOS does not need dylib1.o. | |||
2478 | } else if (isTargetIOSSimulator()) { | |||
2479 | ; // iOS simulator does not need dylib1.o. | |||
2480 | } else if (isTargetIPhoneOS()) { | |||
2481 | if (isIPhoneOSVersionLT(3, 1)) | |||
2482 | CmdArgs.push_back("-ldylib1.o"); | |||
2483 | } else { | |||
2484 | if (isMacosxVersionLT(10, 5)) | |||
2485 | CmdArgs.push_back("-ldylib1.o"); | |||
2486 | else if (isMacosxVersionLT(10, 6)) | |||
2487 | CmdArgs.push_back("-ldylib1.10.5.o"); | |||
2488 | } | |||
2489 | } else { | |||
2490 | if (Args.hasArg(options::OPT_bundle)) { | |||
2491 | if (!Args.hasArg(options::OPT_static)) { | |||
2492 | // Derived from darwin_bundle1 spec. | |||
2493 | if (isTargetWatchOSBased()) { | |||
2494 | ; // watchOS does not need bundle1.o. | |||
2495 | } else if (isTargetIOSSimulator()) { | |||
2496 | ; // iOS simulator does not need bundle1.o. | |||
2497 | } else if (isTargetIPhoneOS()) { | |||
2498 | if (isIPhoneOSVersionLT(3, 1)) | |||
2499 | CmdArgs.push_back("-lbundle1.o"); | |||
2500 | } else { | |||
2501 | if (isMacosxVersionLT(10, 6)) | |||
2502 | CmdArgs.push_back("-lbundle1.o"); | |||
2503 | } | |||
2504 | } | |||
2505 | } else { | |||
2506 | if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) { | |||
2507 | if (isTargetMacOS() && isMacosxVersionLT(10, 9)) { | |||
2508 | if (Args.hasArg(options::OPT_static) || | |||
2509 | Args.hasArg(options::OPT_object) || | |||
2510 | Args.hasArg(options::OPT_preload)) { | |||
2511 | CmdArgs.push_back("-lgcrt0.o"); | |||
2512 | } else { | |||
2513 | CmdArgs.push_back("-lgcrt1.o"); | |||
2514 | ||||
2515 | // darwin_crt2 spec is empty. | |||
2516 | } | |||
2517 | // By default on OS X 10.8 and later, we don't link with a crt1.o | |||
2518 | // file and the linker knows to use _main as the entry point. But, | |||
2519 | // when compiling with -pg, we need to link with the gcrt1.o file, | |||
2520 | // so pass the -no_new_main option to tell the linker to use the | |||
2521 | // "start" symbol as the entry point. | |||
2522 | if (isTargetMacOS() && !isMacosxVersionLT(10, 8)) | |||
2523 | CmdArgs.push_back("-no_new_main"); | |||
2524 | } else { | |||
2525 | getDriver().Diag(diag::err_drv_clang_unsupported_opt_pg_darwin) | |||
2526 | << isTargetMacOS(); | |||
2527 | } | |||
2528 | } else { | |||
2529 | if (Args.hasArg(options::OPT_static) || | |||
2530 | Args.hasArg(options::OPT_object) || | |||
2531 | Args.hasArg(options::OPT_preload)) { | |||
2532 | CmdArgs.push_back("-lcrt0.o"); | |||
2533 | } else { | |||
2534 | // Derived from darwin_crt1 spec. | |||
2535 | if (isTargetWatchOSBased()) { | |||
2536 | ; // watchOS does not need crt1.o. | |||
2537 | } else if (isTargetIOSSimulator()) { | |||
2538 | ; // iOS simulator does not need crt1.o. | |||
2539 | } else if (isTargetIPhoneOS()) { | |||
2540 | if (getArch() == llvm::Triple::aarch64) | |||
2541 | ; // iOS does not need any crt1 files for arm64 | |||
2542 | else if (isIPhoneOSVersionLT(3, 1)) | |||
2543 | CmdArgs.push_back("-lcrt1.o"); | |||
2544 | else if (isIPhoneOSVersionLT(6, 0)) | |||
2545 | CmdArgs.push_back("-lcrt1.3.1.o"); | |||
2546 | } else { | |||
2547 | if (isMacosxVersionLT(10, 5)) | |||
2548 | CmdArgs.push_back("-lcrt1.o"); | |||
2549 | else if (isMacosxVersionLT(10, 6)) | |||
2550 | CmdArgs.push_back("-lcrt1.10.5.o"); | |||
2551 | else if (isMacosxVersionLT(10, 8)) | |||
2552 | CmdArgs.push_back("-lcrt1.10.6.o"); | |||
2553 | ||||
2554 | // darwin_crt2 spec is empty. | |||
2555 | } | |||
2556 | } | |||
2557 | } | |||
2558 | } | |||
2559 | } | |||
2560 | ||||
2561 | if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) && | |||
2562 | !isTargetWatchOS() && isMacosxVersionLT(10, 5)) { | |||
2563 | const char *Str = Args.MakeArgString(GetFilePath("crt3.o")); | |||
2564 | CmdArgs.push_back(Str); | |||
2565 | } | |||
2566 | } | |||
2567 | ||||
2568 | void Darwin::CheckObjCARC() const { | |||
2569 | if (isTargetIOSBased() || isTargetWatchOSBased() || | |||
2570 | (isTargetMacOS() && !isMacosxVersionLT(10, 6))) | |||
2571 | return; | |||
2572 | getDriver().Diag(diag::err_arc_unsupported_on_toolchain); | |||
2573 | } | |||
2574 | ||||
2575 | SanitizerMask Darwin::getSupportedSanitizers() const { | |||
2576 | const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64; | |||
2577 | SanitizerMask Res = ToolChain::getSupportedSanitizers(); | |||
2578 | Res |= SanitizerKind::Address; | |||
2579 | Res |= SanitizerKind::PointerCompare; | |||
2580 | Res |= SanitizerKind::PointerSubtract; | |||
2581 | Res |= SanitizerKind::Leak; | |||
2582 | Res |= SanitizerKind::Fuzzer; | |||
2583 | Res |= SanitizerKind::FuzzerNoLink; | |||
2584 | Res |= SanitizerKind::Function; | |||
2585 | ||||
2586 | // Prior to 10.9, macOS shipped a version of the C++ standard library without | |||
2587 | // C++11 support. The same is true of iOS prior to version 5. These OS'es are | |||
2588 | // incompatible with -fsanitize=vptr. | |||
2589 | if (!(isTargetMacOS() && isMacosxVersionLT(10, 9)) | |||
2590 | && !(isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0))) | |||
2591 | Res |= SanitizerKind::Vptr; | |||
2592 | ||||
2593 | if (isTargetMacOS()) { | |||
2594 | if (IsX86_64) | |||
2595 | Res |= SanitizerKind::Thread; | |||
2596 | } else if (isTargetIOSSimulator() || isTargetTvOSSimulator()) { | |||
2597 | if (IsX86_64) | |||
2598 | Res |= SanitizerKind::Thread; | |||
2599 | } | |||
2600 | return Res; | |||
2601 | } | |||
2602 | ||||
2603 | void Darwin::printVerboseInfo(raw_ostream &OS) const { | |||
2604 | CudaInstallation.print(OS); | |||
2605 | } |
1 | //===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This file defines an API used to report recoverable errors. | |||
10 | // | |||
11 | //===----------------------------------------------------------------------===// | |||
12 | ||||
13 | #ifndef LLVM_SUPPORT_ERROR_H | |||
14 | #define LLVM_SUPPORT_ERROR_H | |||
15 | ||||
16 | #include "llvm-c/Error.h" | |||
17 | #include "llvm/ADT/STLExtras.h" | |||
18 | #include "llvm/ADT/SmallVector.h" | |||
19 | #include "llvm/ADT/StringExtras.h" | |||
20 | #include "llvm/ADT/Twine.h" | |||
21 | #include "llvm/Config/abi-breaking.h" | |||
22 | #include "llvm/Support/AlignOf.h" | |||
23 | #include "llvm/Support/Compiler.h" | |||
24 | #include "llvm/Support/Debug.h" | |||
25 | #include "llvm/Support/ErrorHandling.h" | |||
26 | #include "llvm/Support/ErrorOr.h" | |||
27 | #include "llvm/Support/Format.h" | |||
28 | #include "llvm/Support/raw_ostream.h" | |||
29 | #include <algorithm> | |||
30 | #include <cassert> | |||
31 | #include <cstdint> | |||
32 | #include <cstdlib> | |||
33 | #include <functional> | |||
34 | #include <memory> | |||
35 | #include <new> | |||
36 | #include <string> | |||
37 | #include <system_error> | |||
38 | #include <type_traits> | |||
39 | #include <utility> | |||
40 | #include <vector> | |||
41 | ||||
42 | namespace llvm { | |||
43 | ||||
44 | class ErrorSuccess; | |||
45 | ||||
46 | /// Base class for error info classes. Do not extend this directly: Extend | |||
47 | /// the ErrorInfo template subclass instead. | |||
48 | class ErrorInfoBase { | |||
49 | public: | |||
50 | virtual ~ErrorInfoBase() = default; | |||
51 | ||||
52 | /// Print an error message to an output stream. | |||
53 | virtual void log(raw_ostream &OS) const = 0; | |||
54 | ||||
55 | /// Return the error message as a string. | |||
56 | virtual std::string message() const { | |||
57 | std::string Msg; | |||
58 | raw_string_ostream OS(Msg); | |||
59 | log(OS); | |||
60 | return OS.str(); | |||
61 | } | |||
62 | ||||
63 | /// Convert this error to a std::error_code. | |||
64 | /// | |||
65 | /// This is a temporary crutch to enable interaction with code still | |||
66 | /// using std::error_code. It will be removed in the future. | |||
67 | virtual std::error_code convertToErrorCode() const = 0; | |||
68 | ||||
69 | // Returns the class ID for this type. | |||
70 | static const void *classID() { return &ID; } | |||
71 | ||||
72 | // Returns the class ID for the dynamic type of this ErrorInfoBase instance. | |||
73 | virtual const void *dynamicClassID() const = 0; | |||
74 | ||||
75 | // Check whether this instance is a subclass of the class identified by | |||
76 | // ClassID. | |||
77 | virtual bool isA(const void *const ClassID) const { | |||
78 | return ClassID == classID(); | |||
79 | } | |||
80 | ||||
81 | // Check whether this instance is a subclass of ErrorInfoT. | |||
82 | template <typename ErrorInfoT> bool isA() const { | |||
83 | return isA(ErrorInfoT::classID()); | |||
84 | } | |||
85 | ||||
86 | private: | |||
87 | virtual void anchor(); | |||
88 | ||||
89 | static char ID; | |||
90 | }; | |||
91 | ||||
92 | /// Lightweight error class with error context and mandatory checking. | |||
93 | /// | |||
94 | /// Instances of this class wrap a ErrorInfoBase pointer. Failure states | |||
95 | /// are represented by setting the pointer to a ErrorInfoBase subclass | |||
96 | /// instance containing information describing the failure. Success is | |||
97 | /// represented by a null pointer value. | |||
98 | /// | |||
99 | /// Instances of Error also contains a 'Checked' flag, which must be set | |||
100 | /// before the destructor is called, otherwise the destructor will trigger a | |||
101 | /// runtime error. This enforces at runtime the requirement that all Error | |||
102 | /// instances be checked or returned to the caller. | |||
103 | /// | |||
104 | /// There are two ways to set the checked flag, depending on what state the | |||
105 | /// Error instance is in. For Error instances indicating success, it | |||
106 | /// is sufficient to invoke the boolean conversion operator. E.g.: | |||
107 | /// | |||
108 | /// @code{.cpp} | |||
109 | /// Error foo(<...>); | |||
110 | /// | |||
111 | /// if (auto E = foo(<...>)) | |||
112 | /// return E; // <- Return E if it is in the error state. | |||
113 | /// // We have verified that E was in the success state. It can now be safely | |||
114 | /// // destroyed. | |||
115 | /// @endcode | |||
116 | /// | |||
117 | /// A success value *can not* be dropped. For example, just calling 'foo(<...>)' | |||
118 | /// without testing the return value will raise a runtime error, even if foo | |||
119 | /// returns success. | |||
120 | /// | |||
121 | /// For Error instances representing failure, you must use either the | |||
122 | /// handleErrors or handleAllErrors function with a typed handler. E.g.: | |||
123 | /// | |||
124 | /// @code{.cpp} | |||
125 | /// class MyErrorInfo : public ErrorInfo<MyErrorInfo> { | |||
126 | /// // Custom error info. | |||
127 | /// }; | |||
128 | /// | |||
129 | /// Error foo(<...>) { return make_error<MyErrorInfo>(...); } | |||
130 | /// | |||
131 | /// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo. | |||
132 | /// auto NewE = | |||
133 | /// handleErrors(E, | |||
134 | /// [](const MyErrorInfo &M) { | |||
135 | /// // Deal with the error. | |||
136 | /// }, | |||
137 | /// [](std::unique_ptr<OtherError> M) -> Error { | |||
138 | /// if (canHandle(*M)) { | |||
139 | /// // handle error. | |||
140 | /// return Error::success(); | |||
141 | /// } | |||
142 | /// // Couldn't handle this error instance. Pass it up the stack. | |||
143 | /// return Error(std::move(M)); | |||
144 | /// ); | |||
145 | /// // Note - we must check or return NewE in case any of the handlers | |||
146 | /// // returned a new error. | |||
147 | /// @endcode | |||
148 | /// | |||
149 | /// The handleAllErrors function is identical to handleErrors, except | |||
150 | /// that it has a void return type, and requires all errors to be handled and | |||
151 | /// no new errors be returned. It prevents errors (assuming they can all be | |||
152 | /// handled) from having to be bubbled all the way to the top-level. | |||
153 | /// | |||
154 | /// *All* Error instances must be checked before destruction, even if | |||
155 | /// they're moved-assigned or constructed from Success values that have already | |||
156 | /// been checked. This enforces checking through all levels of the call stack. | |||
157 | class LLVM_NODISCARD[[clang::warn_unused_result]] Error { | |||
158 | // Both ErrorList and FileError need to be able to yank ErrorInfoBase | |||
159 | // pointers out of this class to add to the error list. | |||
160 | friend class ErrorList; | |||
161 | friend class FileError; | |||
162 | ||||
163 | // handleErrors needs to be able to set the Checked flag. | |||
164 | template <typename... HandlerTs> | |||
165 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); | |||
166 | ||||
167 | // Expected<T> needs to be able to steal the payload when constructed from an | |||
168 | // error. | |||
169 | template <typename T> friend class Expected; | |||
170 | ||||
171 | // wrap needs to be able to steal the payload. | |||
172 | friend LLVMErrorRef wrap(Error); | |||
173 | ||||
174 | protected: | |||
175 | /// Create a success value. Prefer using 'Error::success()' for readability | |||
176 | Error() { | |||
177 | setPtr(nullptr); | |||
178 | setChecked(false); | |||
179 | } | |||
180 | ||||
181 | public: | |||
182 | /// Create a success value. | |||
183 | static ErrorSuccess success(); | |||
184 | ||||
185 | // Errors are not copy-constructable. | |||
186 | Error(const Error &Other) = delete; | |||
187 | ||||
188 | /// Move-construct an error value. The newly constructed error is considered | |||
189 | /// unchecked, even if the source error had been checked. The original error | |||
190 | /// becomes a checked Success value, regardless of its original state. | |||
191 | Error(Error &&Other) { | |||
192 | setChecked(true); | |||
193 | *this = std::move(Other); | |||
194 | } | |||
195 | ||||
196 | /// Create an error value. Prefer using the 'make_error' function, but | |||
197 | /// this constructor can be useful when "re-throwing" errors from handlers. | |||
198 | Error(std::unique_ptr<ErrorInfoBase> Payload) { | |||
199 | setPtr(Payload.release()); | |||
200 | setChecked(false); | |||
| ||||
201 | } | |||
202 | ||||
203 | // Errors are not copy-assignable. | |||
204 | Error &operator=(const Error &Other) = delete; | |||
205 | ||||
206 | /// Move-assign an error value. The current error must represent success, you | |||
207 | /// you cannot overwrite an unhandled error. The current error is then | |||
208 | /// considered unchecked. The source error becomes a checked success value, | |||
209 | /// regardless of its original state. | |||
210 | Error &operator=(Error &&Other) { | |||
211 | // Don't allow overwriting of unchecked values. | |||
212 | assertIsChecked(); | |||
213 | setPtr(Other.getPtr()); | |||
214 | ||||
215 | // This Error is unchecked, even if the source error was checked. | |||
216 | setChecked(false); | |||
217 | ||||
218 | // Null out Other's payload and set its checked bit. | |||
219 | Other.setPtr(nullptr); | |||
220 | Other.setChecked(true); | |||
221 | ||||
222 | return *this; | |||
223 | } | |||
224 | ||||
225 | /// Destroy a Error. Fails with a call to abort() if the error is | |||
226 | /// unchecked. | |||
227 | ~Error() { | |||
228 | assertIsChecked(); | |||
229 | delete getPtr(); | |||
230 | } | |||
231 | ||||
232 | /// Bool conversion. Returns true if this Error is in a failure state, | |||
233 | /// and false if it is in an accept state. If the error is in a Success state | |||
234 | /// it will be considered checked. | |||
235 | explicit operator bool() { | |||
236 | setChecked(getPtr() == nullptr); | |||
237 | return getPtr() != nullptr; | |||
238 | } | |||
239 | ||||
240 | /// Check whether one error is a subclass of another. | |||
241 | template <typename ErrT> bool isA() const { | |||
242 | return getPtr() && getPtr()->isA(ErrT::classID()); | |||
243 | } | |||
244 | ||||
245 | /// Returns the dynamic class id of this error, or null if this is a success | |||
246 | /// value. | |||
247 | const void* dynamicClassID() const { | |||
248 | if (!getPtr()) | |||
249 | return nullptr; | |||
250 | return getPtr()->dynamicClassID(); | |||
251 | } | |||
252 | ||||
253 | private: | |||
254 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
255 | // assertIsChecked() happens very frequently, but under normal circumstances | |||
256 | // is supposed to be a no-op. So we want it to be inlined, but having a bunch | |||
257 | // of debug prints can cause the function to be too large for inlining. So | |||
258 | // it's important that we define this function out of line so that it can't be | |||
259 | // inlined. | |||
260 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) | |||
261 | void fatalUncheckedError() const; | |||
262 | #endif | |||
263 | ||||
264 | void assertIsChecked() { | |||
265 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
266 | if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false)) | |||
267 | fatalUncheckedError(); | |||
268 | #endif | |||
269 | } | |||
270 | ||||
271 | ErrorInfoBase *getPtr() const { | |||
272 | return reinterpret_cast<ErrorInfoBase*>( | |||
273 | reinterpret_cast<uintptr_t>(Payload) & | |||
274 | ~static_cast<uintptr_t>(0x1)); | |||
275 | } | |||
276 | ||||
277 | void setPtr(ErrorInfoBase *EI) { | |||
278 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
279 | Payload = reinterpret_cast<ErrorInfoBase*>( | |||
280 | (reinterpret_cast<uintptr_t>(EI) & | |||
281 | ~static_cast<uintptr_t>(0x1)) | | |||
282 | (reinterpret_cast<uintptr_t>(Payload) & 0x1)); | |||
283 | #else | |||
284 | Payload = EI; | |||
285 | #endif | |||
286 | } | |||
287 | ||||
288 | bool getChecked() const { | |||
289 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
290 | return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0; | |||
291 | #else | |||
292 | return true; | |||
293 | #endif | |||
294 | } | |||
295 | ||||
296 | void setChecked(bool V) { | |||
297 | Payload = reinterpret_cast<ErrorInfoBase*>( | |||
298 | (reinterpret_cast<uintptr_t>(Payload) & | |||
299 | ~static_cast<uintptr_t>(0x1)) | | |||
300 | (V ? 0 : 1)); | |||
301 | } | |||
302 | ||||
303 | std::unique_ptr<ErrorInfoBase> takePayload() { | |||
304 | std::unique_ptr<ErrorInfoBase> Tmp(getPtr()); | |||
305 | setPtr(nullptr); | |||
306 | setChecked(true); | |||
307 | return Tmp; | |||
308 | } | |||
309 | ||||
310 | friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) { | |||
311 | if (auto P = E.getPtr()) | |||
312 | P->log(OS); | |||
313 | else | |||
314 | OS << "success"; | |||
315 | return OS; | |||
316 | } | |||
317 | ||||
318 | ErrorInfoBase *Payload = nullptr; | |||
319 | }; | |||
320 | ||||
321 | /// Subclass of Error for the sole purpose of identifying the success path in | |||
322 | /// the type system. This allows to catch invalid conversion to Expected<T> at | |||
323 | /// compile time. | |||
324 | class ErrorSuccess final : public Error {}; | |||
325 | ||||
326 | inline ErrorSuccess Error::success() { return ErrorSuccess(); } | |||
327 | ||||
328 | /// Make a Error instance representing failure using the given error info | |||
329 | /// type. | |||
330 | template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) { | |||
331 | return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...)); | |||
332 | } | |||
333 | ||||
334 | /// Base class for user error types. Users should declare their error types | |||
335 | /// like: | |||
336 | /// | |||
337 | /// class MyError : public ErrorInfo<MyError> { | |||
338 | /// .... | |||
339 | /// }; | |||
340 | /// | |||
341 | /// This class provides an implementation of the ErrorInfoBase::kind | |||
342 | /// method, which is used by the Error RTTI system. | |||
343 | template <typename ThisErrT, typename ParentErrT = ErrorInfoBase> | |||
344 | class ErrorInfo : public ParentErrT { | |||
345 | public: | |||
346 | using ParentErrT::ParentErrT; // inherit constructors | |||
347 | ||||
348 | static const void *classID() { return &ThisErrT::ID; } | |||
349 | ||||
350 | const void *dynamicClassID() const override { return &ThisErrT::ID; } | |||
351 | ||||
352 | bool isA(const void *const ClassID) const override { | |||
353 | return ClassID == classID() || ParentErrT::isA(ClassID); | |||
354 | } | |||
355 | }; | |||
356 | ||||
357 | /// Special ErrorInfo subclass representing a list of ErrorInfos. | |||
358 | /// Instances of this class are constructed by joinError. | |||
359 | class ErrorList final : public ErrorInfo<ErrorList> { | |||
360 | // handleErrors needs to be able to iterate the payload list of an | |||
361 | // ErrorList. | |||
362 | template <typename... HandlerTs> | |||
363 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); | |||
364 | ||||
365 | // joinErrors is implemented in terms of join. | |||
366 | friend Error joinErrors(Error, Error); | |||
367 | ||||
368 | public: | |||
369 | void log(raw_ostream &OS) const override { | |||
370 | OS << "Multiple errors:\n"; | |||
371 | for (auto &ErrPayload : Payloads) { | |||
372 | ErrPayload->log(OS); | |||
373 | OS << "\n"; | |||
374 | } | |||
375 | } | |||
376 | ||||
377 | std::error_code convertToErrorCode() const override; | |||
378 | ||||
379 | // Used by ErrorInfo::classID. | |||
380 | static char ID; | |||
381 | ||||
382 | private: | |||
383 | ErrorList(std::unique_ptr<ErrorInfoBase> Payload1, | |||
384 | std::unique_ptr<ErrorInfoBase> Payload2) { | |||
385 | 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-9~svn362543/include/llvm/Support/Error.h" , 386, __PRETTY_FUNCTION__)) | |||
386 | "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-9~svn362543/include/llvm/Support/Error.h" , 386, __PRETTY_FUNCTION__)); | |||
387 | Payloads.push_back(std::move(Payload1)); | |||
388 | Payloads.push_back(std::move(Payload2)); | |||
389 | } | |||
390 | ||||
391 | static Error join(Error E1, Error E2) { | |||
392 | if (!E1) | |||
393 | return E2; | |||
394 | if (!E2) | |||
395 | return E1; | |||
396 | if (E1.isA<ErrorList>()) { | |||
397 | auto &E1List = static_cast<ErrorList &>(*E1.getPtr()); | |||
398 | if (E2.isA<ErrorList>()) { | |||
399 | auto E2Payload = E2.takePayload(); | |||
400 | auto &E2List = static_cast<ErrorList &>(*E2Payload); | |||
401 | for (auto &Payload : E2List.Payloads) | |||
402 | E1List.Payloads.push_back(std::move(Payload)); | |||
403 | } else | |||
404 | E1List.Payloads.push_back(E2.takePayload()); | |||
405 | ||||
406 | return E1; | |||
407 | } | |||
408 | if (E2.isA<ErrorList>()) { | |||
409 | auto &E2List = static_cast<ErrorList &>(*E2.getPtr()); | |||
410 | E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload()); | |||
411 | return E2; | |||
412 | } | |||
413 | return Error(std::unique_ptr<ErrorList>( | |||
414 | new ErrorList(E1.takePayload(), E2.takePayload()))); | |||
415 | } | |||
416 | ||||
417 | std::vector<std::unique_ptr<ErrorInfoBase>> Payloads; | |||
418 | }; | |||
419 | ||||
420 | /// Concatenate errors. The resulting Error is unchecked, and contains the | |||
421 | /// ErrorInfo(s), if any, contained in E1, followed by the | |||
422 | /// ErrorInfo(s), if any, contained in E2. | |||
423 | inline Error joinErrors(Error E1, Error E2) { | |||
424 | return ErrorList::join(std::move(E1), std::move(E2)); | |||
425 | } | |||
426 | ||||
427 | /// Tagged union holding either a T or a Error. | |||
428 | /// | |||
429 | /// This class parallels ErrorOr, but replaces error_code with Error. Since | |||
430 | /// Error cannot be copied, this class replaces getError() with | |||
431 | /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the | |||
432 | /// error class type. | |||
433 | template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected { | |||
434 | template <class T1> friend class ExpectedAsOutParameter; | |||
435 | template <class OtherT> friend class Expected; | |||
436 | ||||
437 | static const bool isRef = std::is_reference<T>::value; | |||
438 | ||||
439 | using wrap = std::reference_wrapper<typename std::remove_reference<T>::type>; | |||
440 | ||||
441 | using error_type = std::unique_ptr<ErrorInfoBase>; | |||
442 | ||||
443 | public: | |||
444 | using storage_type = typename std::conditional<isRef, wrap, T>::type; | |||
445 | using value_type = T; | |||
446 | ||||
447 | private: | |||
448 | using reference = typename std::remove_reference<T>::type &; | |||
449 | using const_reference = const typename std::remove_reference<T>::type &; | |||
450 | using pointer = typename std::remove_reference<T>::type *; | |||
451 | using const_pointer = const typename std::remove_reference<T>::type *; | |||
452 | ||||
453 | public: | |||
454 | /// Create an Expected<T> error value from the given Error. | |||
455 | Expected(Error Err) | |||
456 | : HasError(true) | |||
457 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
458 | // Expected is unchecked upon construction in Debug builds. | |||
459 | , Unchecked(true) | |||
460 | #endif | |||
461 | { | |||
462 | 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-9~svn362543/include/llvm/Support/Error.h" , 462, __PRETTY_FUNCTION__)); | |||
463 | new (getErrorStorage()) error_type(Err.takePayload()); | |||
464 | } | |||
465 | ||||
466 | /// Forbid to convert from Error::success() implicitly, this avoids having | |||
467 | /// Expected<T> foo() { return Error::success(); } which compiles otherwise | |||
468 | /// but triggers the assertion above. | |||
469 | Expected(ErrorSuccess) = delete; | |||
470 | ||||
471 | /// Create an Expected<T> success value from the given OtherT value, which | |||
472 | /// must be convertible to T. | |||
473 | template <typename OtherT> | |||
474 | Expected(OtherT &&Val, | |||
475 | typename std::enable_if<std::is_convertible<OtherT, T>::value>::type | |||
476 | * = nullptr) | |||
477 | : HasError(false) | |||
478 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
479 | // Expected is unchecked upon construction in Debug builds. | |||
480 | , Unchecked(true) | |||
481 | #endif | |||
482 | { | |||
483 | new (getStorage()) storage_type(std::forward<OtherT>(Val)); | |||
484 | } | |||
485 | ||||
486 | /// Move construct an Expected<T> value. | |||
487 | Expected(Expected &&Other) { moveConstruct(std::move(Other)); } | |||
488 | ||||
489 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT | |||
490 | /// must be convertible to T. | |||
491 | template <class OtherT> | |||
492 | Expected(Expected<OtherT> &&Other, | |||
493 | typename std::enable_if<std::is_convertible<OtherT, T>::value>::type | |||
494 | * = nullptr) { | |||
495 | moveConstruct(std::move(Other)); | |||
496 | } | |||
497 | ||||
498 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT | |||
499 | /// isn't convertible to T. | |||
500 | template <class OtherT> | |||
501 | explicit Expected( | |||
502 | Expected<OtherT> &&Other, | |||
503 | typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * = | |||
504 | nullptr) { | |||
505 | moveConstruct(std::move(Other)); | |||
506 | } | |||
507 | ||||
508 | /// Move-assign from another Expected<T>. | |||
509 | Expected &operator=(Expected &&Other) { | |||
510 | moveAssign(std::move(Other)); | |||
511 | return *this; | |||
512 | } | |||
513 | ||||
514 | /// Destroy an Expected<T>. | |||
515 | ~Expected() { | |||
516 | assertIsChecked(); | |||
517 | if (!HasError) | |||
518 | getStorage()->~storage_type(); | |||
519 | else | |||
520 | getErrorStorage()->~error_type(); | |||
521 | } | |||
522 | ||||
523 | /// Return false if there is an error. | |||
524 | explicit operator bool() { | |||
525 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
526 | Unchecked = HasError; | |||
527 | #endif | |||
528 | return !HasError; | |||
529 | } | |||
530 | ||||
531 | /// Returns a reference to the stored T value. | |||
532 | reference get() { | |||
533 | assertIsChecked(); | |||
534 | return *getStorage(); | |||
535 | } | |||
536 | ||||
537 | /// Returns a const reference to the stored T value. | |||
538 | const_reference get() const { | |||
539 | assertIsChecked(); | |||
540 | return const_cast<Expected<T> *>(this)->get(); | |||
541 | } | |||
542 | ||||
543 | /// Check that this Expected<T> is an error of type ErrT. | |||
544 | template <typename ErrT> bool errorIsA() const { | |||
545 | return HasError && (*getErrorStorage())->template isA<ErrT>(); | |||
546 | } | |||
547 | ||||
548 | /// Take ownership of the stored error. | |||
549 | /// After calling this the Expected<T> is in an indeterminate state that can | |||
550 | /// only be safely destructed. No further calls (beside the destructor) should | |||
551 | /// be made on the Expected<T> vaule. | |||
552 | Error takeError() { | |||
553 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
554 | Unchecked = false; | |||
555 | #endif | |||
556 | return HasError ? Error(std::move(*getErrorStorage())) : Error::success(); | |||
557 | } | |||
558 | ||||
559 | /// Returns a pointer to the stored T value. | |||
560 | pointer operator->() { | |||
561 | assertIsChecked(); | |||
562 | return toPointer(getStorage()); | |||
563 | } | |||
564 | ||||
565 | /// Returns a const pointer to the stored T value. | |||
566 | const_pointer operator->() const { | |||
567 | assertIsChecked(); | |||
568 | return toPointer(getStorage()); | |||
569 | } | |||
570 | ||||
571 | /// Returns a reference to the stored T value. | |||
572 | reference operator*() { | |||
573 | assertIsChecked(); | |||
574 | return *getStorage(); | |||
575 | } | |||
576 | ||||
577 | /// Returns a const reference to the stored T value. | |||
578 | const_reference operator*() const { | |||
579 | assertIsChecked(); | |||
580 | return *getStorage(); | |||
581 | } | |||
582 | ||||
583 | private: | |||
584 | template <class T1> | |||
585 | static bool compareThisIfSameType(const T1 &a, const T1 &b) { | |||
586 | return &a == &b; | |||
587 | } | |||
588 | ||||
589 | template <class T1, class T2> | |||
590 | static bool compareThisIfSameType(const T1 &a, const T2 &b) { | |||
591 | return false; | |||
592 | } | |||
593 | ||||
594 | template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) { | |||
595 | HasError = Other.HasError; | |||
596 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
597 | Unchecked = true; | |||
598 | Other.Unchecked = false; | |||
599 | #endif | |||
600 | ||||
601 | if (!HasError) | |||
602 | new (getStorage()) storage_type(std::move(*Other.getStorage())); | |||
603 | else | |||
604 | new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage())); | |||
605 | } | |||
606 | ||||
607 | template <class OtherT> void moveAssign(Expected<OtherT> &&Other) { | |||
608 | assertIsChecked(); | |||
609 | ||||
610 | if (compareThisIfSameType(*this, Other)) | |||
611 | return; | |||
612 | ||||
613 | this->~Expected(); | |||
614 | new (this) Expected(std::move(Other)); | |||
615 | } | |||
616 | ||||
617 | pointer toPointer(pointer Val) { return Val; } | |||
618 | ||||
619 | const_pointer toPointer(const_pointer Val) const { return Val; } | |||
620 | ||||
621 | pointer toPointer(wrap *Val) { return &Val->get(); } | |||
622 | ||||
623 | const_pointer toPointer(const wrap *Val) const { return &Val->get(); } | |||
624 | ||||
625 | storage_type *getStorage() { | |||
626 | 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-9~svn362543/include/llvm/Support/Error.h" , 626, __PRETTY_FUNCTION__)); | |||
627 | return reinterpret_cast<storage_type *>(TStorage.buffer); | |||
628 | } | |||
629 | ||||
630 | const storage_type *getStorage() const { | |||
631 | 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-9~svn362543/include/llvm/Support/Error.h" , 631, __PRETTY_FUNCTION__)); | |||
632 | return reinterpret_cast<const storage_type *>(TStorage.buffer); | |||
633 | } | |||
634 | ||||
635 | error_type *getErrorStorage() { | |||
636 | 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-9~svn362543/include/llvm/Support/Error.h" , 636, __PRETTY_FUNCTION__)); | |||
637 | return reinterpret_cast<error_type *>(ErrorStorage.buffer); | |||
638 | } | |||
639 | ||||
640 | const error_type *getErrorStorage() const { | |||
641 | 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-9~svn362543/include/llvm/Support/Error.h" , 641, __PRETTY_FUNCTION__)); | |||
642 | return reinterpret_cast<const error_type *>(ErrorStorage.buffer); | |||
643 | } | |||
644 | ||||
645 | // Used by ExpectedAsOutParameter to reset the checked flag. | |||
646 | void setUnchecked() { | |||
647 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
648 | Unchecked = true; | |||
649 | #endif | |||
650 | } | |||
651 | ||||
652 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
653 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) | |||
654 | LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) | |||
655 | void fatalUncheckedExpected() const { | |||
656 | dbgs() << "Expected<T> must be checked before access or destruction.\n"; | |||
657 | if (HasError) { | |||
658 | dbgs() << "Unchecked Expected<T> contained error:\n"; | |||
659 | (*getErrorStorage())->log(dbgs()); | |||
660 | } else | |||
661 | dbgs() << "Expected<T> value was in success state. (Note: Expected<T> " | |||
662 | "values in success mode must still be checked prior to being " | |||
663 | "destroyed).\n"; | |||
664 | abort(); | |||
665 | } | |||
666 | #endif | |||
667 | ||||
668 | void assertIsChecked() { | |||
669 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
670 | if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false)) | |||
671 | fatalUncheckedExpected(); | |||
672 | #endif | |||
673 | } | |||
674 | ||||
675 | union { | |||
676 | AlignedCharArrayUnion<storage_type> TStorage; | |||
677 | AlignedCharArrayUnion<error_type> ErrorStorage; | |||
678 | }; | |||
679 | bool HasError : 1; | |||
680 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 | |||
681 | bool Unchecked : 1; | |||
682 | #endif | |||
683 | }; | |||
684 | ||||
685 | /// Report a serious error, calling any installed error handler. See | |||
686 | /// ErrorHandling.h. | |||
687 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void report_fatal_error(Error Err, | |||
688 | bool gen_crash_diag = true); | |||
689 | ||||
690 | /// Report a fatal error if Err is a failure value. | |||
691 | /// | |||
692 | /// This function can be used to wrap calls to fallible functions ONLY when it | |||
693 | /// is known that the Error will always be a success value. E.g. | |||
694 | /// | |||
695 | /// @code{.cpp} | |||
696 | /// // foo only attempts the fallible operation if DoFallibleOperation is | |||
697 | /// // true. If DoFallibleOperation is false then foo always returns | |||
698 | /// // Error::success(). | |||
699 | /// Error foo(bool DoFallibleOperation); | |||
700 | /// | |||
701 | /// cantFail(foo(false)); | |||
702 | /// @endcode | |||
703 | inline void cantFail(Error Err, const char *Msg = nullptr) { | |||
704 | if (Err) { | |||
705 | if (!Msg) | |||
706 | Msg = "Failure value returned from cantFail wrapped call"; | |||
707 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 707); | |||
708 | } | |||
709 | } | |||
710 | ||||
711 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and | |||
712 | /// returns the contained value. | |||
713 | /// | |||
714 | /// This function can be used to wrap calls to fallible functions ONLY when it | |||
715 | /// is known that the Error will always be a success value. E.g. | |||
716 | /// | |||
717 | /// @code{.cpp} | |||
718 | /// // foo only attempts the fallible operation if DoFallibleOperation is | |||
719 | /// // true. If DoFallibleOperation is false then foo always returns an int. | |||
720 | /// Expected<int> foo(bool DoFallibleOperation); | |||
721 | /// | |||
722 | /// int X = cantFail(foo(false)); | |||
723 | /// @endcode | |||
724 | template <typename T> | |||
725 | T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) { | |||
726 | if (ValOrErr) | |||
727 | return std::move(*ValOrErr); | |||
728 | else { | |||
729 | if (!Msg) | |||
730 | Msg = "Failure value returned from cantFail wrapped call"; | |||
731 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 731); | |||
732 | } | |||
733 | } | |||
734 | ||||
735 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and | |||
736 | /// returns the contained reference. | |||
737 | /// | |||
738 | /// This function can be used to wrap calls to fallible functions ONLY when it | |||
739 | /// is known that the Error will always be a success value. E.g. | |||
740 | /// | |||
741 | /// @code{.cpp} | |||
742 | /// // foo only attempts the fallible operation if DoFallibleOperation is | |||
743 | /// // true. If DoFallibleOperation is false then foo always returns a Bar&. | |||
744 | /// Expected<Bar&> foo(bool DoFallibleOperation); | |||
745 | /// | |||
746 | /// Bar &X = cantFail(foo(false)); | |||
747 | /// @endcode | |||
748 | template <typename T> | |||
749 | T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) { | |||
750 | if (ValOrErr) | |||
751 | return *ValOrErr; | |||
752 | else { | |||
753 | if (!Msg) | |||
754 | Msg = "Failure value returned from cantFail wrapped call"; | |||
755 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 755); | |||
756 | } | |||
757 | } | |||
758 | ||||
759 | /// Helper for testing applicability of, and applying, handlers for | |||
760 | /// ErrorInfo types. | |||
761 | template <typename HandlerT> | |||
762 | class ErrorHandlerTraits | |||
763 | : public ErrorHandlerTraits<decltype( | |||
764 | &std::remove_reference<HandlerT>::type::operator())> {}; | |||
765 | ||||
766 | // Specialization functions of the form 'Error (const ErrT&)'. | |||
767 | template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> { | |||
768 | public: | |||
769 | static bool appliesTo(const ErrorInfoBase &E) { | |||
770 | return E.template isA<ErrT>(); | |||
771 | } | |||
772 | ||||
773 | template <typename HandlerT> | |||
774 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { | |||
775 | 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-9~svn362543/include/llvm/Support/Error.h" , 775, __PRETTY_FUNCTION__)); | |||
776 | return H(static_cast<ErrT &>(*E)); | |||
777 | } | |||
778 | }; | |||
779 | ||||
780 | // Specialization functions of the form 'void (const ErrT&)'. | |||
781 | template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> { | |||
782 | public: | |||
783 | static bool appliesTo(const ErrorInfoBase &E) { | |||
784 | return E.template isA<ErrT>(); | |||
785 | } | |||
786 | ||||
787 | template <typename HandlerT> | |||
788 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { | |||
789 | 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-9~svn362543/include/llvm/Support/Error.h" , 789, __PRETTY_FUNCTION__)); | |||
790 | H(static_cast<ErrT &>(*E)); | |||
791 | return Error::success(); | |||
792 | } | |||
793 | }; | |||
794 | ||||
795 | /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'. | |||
796 | template <typename ErrT> | |||
797 | class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> { | |||
798 | public: | |||
799 | static bool appliesTo(const ErrorInfoBase &E) { | |||
800 | return E.template isA<ErrT>(); | |||
801 | } | |||
802 | ||||
803 | template <typename HandlerT> | |||
804 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { | |||
805 | 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-9~svn362543/include/llvm/Support/Error.h" , 805, __PRETTY_FUNCTION__)); | |||
806 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); | |||
807 | return H(std::move(SubE)); | |||
808 | } | |||
809 | }; | |||
810 | ||||
811 | /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'. | |||
812 | template <typename ErrT> | |||
813 | class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> { | |||
814 | public: | |||
815 | static bool appliesTo(const ErrorInfoBase &E) { | |||
816 | return E.template isA<ErrT>(); | |||
817 | } | |||
818 | ||||
819 | template <typename HandlerT> | |||
820 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { | |||
821 | 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-9~svn362543/include/llvm/Support/Error.h" , 821, __PRETTY_FUNCTION__)); | |||
822 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); | |||
823 | H(std::move(SubE)); | |||
824 | return Error::success(); | |||
825 | } | |||
826 | }; | |||
827 | ||||
828 | // Specialization for member functions of the form 'RetT (const ErrT&)'. | |||
829 | template <typename C, typename RetT, typename ErrT> | |||
830 | class ErrorHandlerTraits<RetT (C::*)(ErrT &)> | |||
831 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; | |||
832 | ||||
833 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. | |||
834 | template <typename C, typename RetT, typename ErrT> | |||
835 | class ErrorHandlerTraits<RetT (C::*)(ErrT &) const> | |||
836 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; | |||
837 | ||||
838 | // Specialization for member functions of the form 'RetT (const ErrT&)'. | |||
839 | template <typename C, typename RetT, typename ErrT> | |||
840 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &)> | |||
841 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; | |||
842 | ||||
843 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. | |||
844 | template <typename C, typename RetT, typename ErrT> | |||
845 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const> | |||
846 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; | |||
847 | ||||
848 | /// Specialization for member functions of the form | |||
849 | /// 'RetT (std::unique_ptr<ErrT>)'. | |||
850 | template <typename C, typename RetT, typename ErrT> | |||
851 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)> | |||
852 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; | |||
853 | ||||
854 | /// Specialization for member functions of the form | |||
855 | /// 'RetT (std::unique_ptr<ErrT>) const'. | |||
856 | template <typename C, typename RetT, typename ErrT> | |||
857 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const> | |||
858 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; | |||
859 | ||||
860 | inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) { | |||
861 | return Error(std::move(Payload)); | |||
862 | } | |||
863 | ||||
864 | template <typename HandlerT, typename... HandlerTs> | |||
865 | Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload, | |||
866 | HandlerT &&Handler, HandlerTs &&... Handlers) { | |||
867 | if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload)) | |||
868 | return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler), | |||
869 | std::move(Payload)); | |||
870 | return handleErrorImpl(std::move(Payload), | |||
871 | std::forward<HandlerTs>(Handlers)...); | |||
872 | } | |||
873 | ||||
874 | /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any | |||
875 | /// unhandled errors (or Errors returned by handlers) are re-concatenated and | |||
876 | /// returned. | |||
877 | /// Because this function returns an error, its result must also be checked | |||
878 | /// or returned. If you intend to handle all errors use handleAllErrors | |||
879 | /// (which returns void, and will abort() on unhandled errors) instead. | |||
880 | template <typename... HandlerTs> | |||
881 | Error handleErrors(Error E, HandlerTs &&... Hs) { | |||
882 | if (!E) | |||
883 | return Error::success(); | |||
884 | ||||
885 | std::unique_ptr<ErrorInfoBase> Payload = E.takePayload(); | |||
886 | ||||
887 | if (Payload->isA<ErrorList>()) { | |||
888 | ErrorList &List = static_cast<ErrorList &>(*Payload); | |||
889 | Error R; | |||
890 | for (auto &P : List.Payloads) | |||
891 | R = ErrorList::join( | |||
892 | std::move(R), | |||
893 | handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...)); | |||
894 | return R; | |||
895 | } | |||
896 | ||||
897 | return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...); | |||
898 | } | |||
899 | ||||
900 | /// Behaves the same as handleErrors, except that by contract all errors | |||
901 | /// *must* be handled by the given handlers (i.e. there must be no remaining | |||
902 | /// errors after running the handlers, or llvm_unreachable is called). | |||
903 | template <typename... HandlerTs> | |||
904 | void handleAllErrors(Error E, HandlerTs &&... Handlers) { | |||
905 | cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...)); | |||
906 | } | |||
907 | ||||
908 | /// Check that E is a non-error, then drop it. | |||
909 | /// If E is an error, llvm_unreachable will be called. | |||
910 | inline void handleAllErrors(Error E) { | |||
911 | cantFail(std::move(E)); | |||
912 | } | |||
913 | ||||
914 | /// Handle any errors (if present) in an Expected<T>, then try a recovery path. | |||
915 | /// | |||
916 | /// If the incoming value is a success value it is returned unmodified. If it | |||
917 | /// is a failure value then it the contained error is passed to handleErrors. | |||
918 | /// If handleErrors is able to handle the error then the RecoveryPath functor | |||
919 | /// is called to supply the final result. If handleErrors is not able to | |||
920 | /// handle all errors then the unhandled errors are returned. | |||
921 | /// | |||
922 | /// This utility enables the follow pattern: | |||
923 | /// | |||
924 | /// @code{.cpp} | |||
925 | /// enum FooStrategy { Aggressive, Conservative }; | |||
926 | /// Expected<Foo> foo(FooStrategy S); | |||
927 | /// | |||
928 | /// auto ResultOrErr = | |||
929 | /// handleExpected( | |||
930 | /// foo(Aggressive), | |||
931 | /// []() { return foo(Conservative); }, | |||
932 | /// [](AggressiveStrategyError&) { | |||
933 | /// // Implicitly conusme this - we'll recover by using a conservative | |||
934 | /// // strategy. | |||
935 | /// }); | |||
936 | /// | |||
937 | /// @endcode | |||
938 | template <typename T, typename RecoveryFtor, typename... HandlerTs> | |||
939 | Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath, | |||
940 | HandlerTs &&... Handlers) { | |||
941 | if (ValOrErr) | |||
942 | return ValOrErr; | |||
943 | ||||
944 | if (auto Err = handleErrors(ValOrErr.takeError(), | |||
945 | std::forward<HandlerTs>(Handlers)...)) | |||
946 | return std::move(Err); | |||
947 | ||||
948 | return RecoveryPath(); | |||
949 | } | |||
950 | ||||
951 | /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner | |||
952 | /// will be printed before the first one is logged. A newline will be printed | |||
953 | /// after each error. | |||
954 | /// | |||
955 | /// This function is compatible with the helpers from Support/WithColor.h. You | |||
956 | /// can pass any of them as the OS. Please consider using them instead of | |||
957 | /// including 'error: ' in the ErrorBanner. | |||
958 | /// | |||
959 | /// This is useful in the base level of your program to allow clean termination | |||
960 | /// (allowing clean deallocation of resources, etc.), while reporting error | |||
961 | /// information to the user. | |||
962 | void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {}); | |||
963 | ||||
964 | /// Write all error messages (if any) in E to a string. The newline character | |||
965 | /// is used to separate error messages. | |||
966 | inline std::string toString(Error E) { | |||
967 | SmallVector<std::string, 2> Errors; | |||
968 | handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) { | |||
969 | Errors.push_back(EI.message()); | |||
970 | }); | |||
971 | return join(Errors.begin(), Errors.end(), "\n"); | |||
972 | } | |||
973 | ||||
974 | /// Consume a Error without doing anything. This method should be used | |||
975 | /// only where an error can be considered a reasonable and expected return | |||
976 | /// value. | |||
977 | /// | |||
978 | /// Uses of this method are potentially indicative of design problems: If it's | |||
979 | /// legitimate to do nothing while processing an "error", the error-producer | |||
980 | /// might be more clearly refactored to return an Optional<T>. | |||
981 | inline void consumeError(Error Err) { | |||
982 | handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {}); | |||
983 | } | |||
984 | ||||
985 | /// Helper for converting an Error to a bool. | |||
986 | /// | |||
987 | /// This method returns true if Err is in an error state, or false if it is | |||
988 | /// in a success state. Puts Err in a checked state in both cases (unlike | |||
989 | /// Error::operator bool(), which only does this for success states). | |||
990 | inline bool errorToBool(Error Err) { | |||
991 | bool IsError = static_cast<bool>(Err); | |||
992 | if (IsError) | |||
993 | consumeError(std::move(Err)); | |||
994 | return IsError; | |||
995 | } | |||
996 | ||||
997 | /// Helper for Errors used as out-parameters. | |||
998 | /// | |||
999 | /// This helper is for use with the Error-as-out-parameter idiom, where an error | |||
1000 | /// is passed to a function or method by reference, rather than being returned. | |||
1001 | /// In such cases it is helpful to set the checked bit on entry to the function | |||
1002 | /// so that the error can be written to (unchecked Errors abort on assignment) | |||
1003 | /// and clear the checked bit on exit so that clients cannot accidentally forget | |||
1004 | /// to check the result. This helper performs these actions automatically using | |||
1005 | /// RAII: | |||
1006 | /// | |||
1007 | /// @code{.cpp} | |||
1008 | /// Result foo(Error &Err) { | |||
1009 | /// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set | |||
1010 | /// // <body of foo> | |||
1011 | /// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed. | |||
1012 | /// } | |||
1013 | /// @endcode | |||
1014 | /// | |||
1015 | /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be | |||
1016 | /// used with optional Errors (Error pointers that are allowed to be null). If | |||
1017 | /// ErrorAsOutParameter took an Error reference, an instance would have to be | |||
1018 | /// created inside every condition that verified that Error was non-null. By | |||
1019 | /// taking an Error pointer we can just create one instance at the top of the | |||
1020 | /// function. | |||
1021 | class ErrorAsOutParameter { | |||
1022 | public: | |||
1023 | ErrorAsOutParameter(Error *Err) : Err(Err) { | |||
1024 | // Raise the checked bit if Err is success. | |||
1025 | if (Err) | |||
1026 | (void)!!*Err; | |||
1027 | } | |||
1028 | ||||
1029 | ~ErrorAsOutParameter() { | |||
1030 | // Clear the checked bit. | |||
1031 | if (Err && !*Err) | |||
1032 | *Err = Error::success(); | |||
1033 | } | |||
1034 | ||||
1035 | private: | |||
1036 | Error *Err; | |||
1037 | }; | |||
1038 | ||||
1039 | /// Helper for Expected<T>s used as out-parameters. | |||
1040 | /// | |||
1041 | /// See ErrorAsOutParameter. | |||
1042 | template <typename T> | |||
1043 | class ExpectedAsOutParameter { | |||
1044 | public: | |||
1045 | ExpectedAsOutParameter(Expected<T> *ValOrErr) | |||
1046 | : ValOrErr(ValOrErr) { | |||
1047 | if (ValOrErr) | |||
1048 | (void)!!*ValOrErr; | |||
1049 | } | |||
1050 | ||||
1051 | ~ExpectedAsOutParameter() { | |||
1052 | if (ValOrErr) | |||
1053 | ValOrErr->setUnchecked(); | |||
1054 | } | |||
1055 | ||||
1056 | private: | |||
1057 | Expected<T> *ValOrErr; | |||
1058 | }; | |||
1059 | ||||
1060 | /// This class wraps a std::error_code in a Error. | |||
1061 | /// | |||
1062 | /// This is useful if you're writing an interface that returns a Error | |||
1063 | /// (or Expected) and you want to call code that still returns | |||
1064 | /// std::error_codes. | |||
1065 | class ECError : public ErrorInfo<ECError> { | |||
1066 | friend Error errorCodeToError(std::error_code); | |||
1067 | ||||
1068 | virtual void anchor() override; | |||
1069 | ||||
1070 | public: | |||
1071 | void setErrorCode(std::error_code EC) { this->EC = EC; } | |||
1072 | std::error_code convertToErrorCode() const override { return EC; } | |||
1073 | void log(raw_ostream &OS) const override { OS << EC.message(); } | |||
1074 | ||||
1075 | // Used by ErrorInfo::classID. | |||
1076 | static char ID; | |||
1077 | ||||
1078 | protected: | |||
1079 | ECError() = default; | |||
1080 | ECError(std::error_code EC) : EC(EC) {} | |||
1081 | ||||
1082 | std::error_code EC; | |||
1083 | }; | |||
1084 | ||||
1085 | /// The value returned by this function can be returned from convertToErrorCode | |||
1086 | /// for Error values where no sensible translation to std::error_code exists. | |||
1087 | /// It should only be used in this situation, and should never be used where a | |||
1088 | /// sensible conversion to std::error_code is available, as attempts to convert | |||
1089 | /// to/from this error will result in a fatal error. (i.e. it is a programmatic | |||
1090 | ///error to try to convert such a value). | |||
1091 | std::error_code inconvertibleErrorCode(); | |||
1092 | ||||
1093 | /// Helper for converting an std::error_code to a Error. | |||
1094 | Error errorCodeToError(std::error_code EC); | |||
1095 | ||||
1096 | /// Helper for converting an ECError to a std::error_code. | |||
1097 | /// | |||
1098 | /// This method requires that Err be Error() or an ECError, otherwise it | |||
1099 | /// will trigger a call to abort(). | |||
1100 | std::error_code errorToErrorCode(Error Err); | |||
1101 | ||||
1102 | /// Convert an ErrorOr<T> to an Expected<T>. | |||
1103 | template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) { | |||
1104 | if (auto EC = EO.getError()) | |||
1105 | return errorCodeToError(EC); | |||
1106 | return std::move(*EO); | |||
1107 | } | |||
1108 | ||||
1109 | /// Convert an Expected<T> to an ErrorOr<T>. | |||
1110 | template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) { | |||
1111 | if (auto Err = E.takeError()) | |||
1112 | return errorToErrorCode(std::move(Err)); | |||
1113 | return std::move(*E); | |||
1114 | } | |||
1115 | ||||
1116 | /// This class wraps a string in an Error. | |||
1117 | /// | |||
1118 | /// StringError is useful in cases where the client is not expected to be able | |||
1119 | /// to consume the specific error message programmatically (for example, if the | |||
1120 | /// error message is to be presented to the user). | |||
1121 | /// | |||
1122 | /// StringError can also be used when additional information is to be printed | |||
1123 | /// along with a error_code message. Depending on the constructor called, this | |||
1124 | /// class can either display: | |||
1125 | /// 1. the error_code message (ECError behavior) | |||
1126 | /// 2. a string | |||
1127 | /// 3. the error_code message and a string | |||
1128 | /// | |||
1129 | /// These behaviors are useful when subtyping is required; for example, when a | |||
1130 | /// specific library needs an explicit error type. In the example below, | |||
1131 | /// PDBError is derived from StringError: | |||
1132 | /// | |||
1133 | /// @code{.cpp} | |||
1134 | /// Expected<int> foo() { | |||
1135 | /// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading, | |||
1136 | /// "Additional information"); | |||
1137 | /// } | |||
1138 | /// @endcode | |||
1139 | /// | |||
1140 | class StringError : public ErrorInfo<StringError> { | |||
1141 | public: | |||
1142 | static char ID; | |||
1143 | ||||
1144 | // Prints EC + S and converts to EC | |||
1145 | StringError(std::error_code EC, const Twine &S = Twine()); | |||
1146 | ||||
1147 | // Prints S and converts to EC | |||
1148 | StringError(const Twine &S, std::error_code EC); | |||
1149 | ||||
1150 | void log(raw_ostream &OS) const override; | |||
1151 | std::error_code convertToErrorCode() const override; | |||
1152 | ||||
1153 | const std::string &getMessage() const { return Msg; } | |||
1154 | ||||
1155 | private: | |||
1156 | std::string Msg; | |||
1157 | std::error_code EC; | |||
1158 | const bool PrintMsgOnly = false; | |||
1159 | }; | |||
1160 | ||||
1161 | /// Create formatted StringError object. | |||
1162 | template <typename... Ts> | |||
1163 | Error createStringError(std::error_code EC, char const *Fmt, | |||
1164 | const Ts &... Vals) { | |||
1165 | std::string Buffer; | |||
1166 | raw_string_ostream Stream(Buffer); | |||
1167 | Stream << format(Fmt, Vals...); | |||
1168 | return make_error<StringError>(Stream.str(), EC); | |||
1169 | } | |||
1170 | ||||
1171 | Error createStringError(std::error_code EC, char const *Msg); | |||
1172 | ||||
1173 | /// This class wraps a filename and another Error. | |||
1174 | /// | |||
1175 | /// In some cases, an error needs to live along a 'source' name, in order to | |||
1176 | /// show more detailed information to the user. | |||
1177 | class FileError final : public ErrorInfo<FileError> { | |||
1178 | ||||
1179 | friend Error createFileError(const Twine &, Error); | |||
1180 | friend Error createFileError(const Twine &, size_t, Error); | |||
1181 | ||||
1182 | public: | |||
1183 | void log(raw_ostream &OS) const override { | |||
1184 | 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-9~svn362543/include/llvm/Support/Error.h" , 1184, __PRETTY_FUNCTION__)); | |||
1185 | OS << "'" << FileName << "': "; | |||
1186 | if (Line.hasValue()) | |||
1187 | OS << "line " << Line.getValue() << ": "; | |||
1188 | Err->log(OS); | |||
1189 | } | |||
1190 | ||||
1191 | Error takeError() { return Error(std::move(Err)); } | |||
1192 | ||||
1193 | std::error_code convertToErrorCode() const override; | |||
1194 | ||||
1195 | // Used by ErrorInfo::classID. | |||
1196 | static char ID; | |||
1197 | ||||
1198 | private: | |||
1199 | FileError(const Twine &F, Optional<size_t> LineNum, | |||
1200 | std::unique_ptr<ErrorInfoBase> E) { | |||
1201 | 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-9~svn362543/include/llvm/Support/Error.h" , 1201, __PRETTY_FUNCTION__)); | |||
1202 | assert(!F.isTriviallyEmpty() &&((!F.isTriviallyEmpty() && "The file name provided to FileError must not be empty." ) ? static_cast<void> (0) : __assert_fail ("!F.isTriviallyEmpty() && \"The file name provided to FileError must not be empty.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 1203, __PRETTY_FUNCTION__)) | |||
1203 | "The file name provided to FileError must not be empty.")((!F.isTriviallyEmpty() && "The file name provided to FileError must not be empty." ) ? static_cast<void> (0) : __assert_fail ("!F.isTriviallyEmpty() && \"The file name provided to FileError must not be empty.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h" , 1203, __PRETTY_FUNCTION__)); | |||
1204 | FileName = F.str(); | |||
1205 | Err = std::move(E); | |||
1206 | Line = std::move(LineNum); | |||
1207 | } | |||
1208 | ||||
1209 | static Error build(const Twine &F, Optional<size_t> Line, Error E) { | |||
1210 | return Error( | |||
1211 | std::unique_ptr<FileError>(new FileError(F, Line, E.takePayload()))); | |||
1212 | } | |||
1213 | ||||
1214 | std::string FileName; | |||
1215 | Optional<size_t> Line; | |||
1216 | std::unique_ptr<ErrorInfoBase> Err; | |||
1217 | }; | |||
1218 | ||||
1219 | /// Concatenate a source file path and/or name with an Error. The resulting | |||
1220 | /// Error is unchecked. | |||
1221 | inline Error createFileError(const Twine &F, Error E) { | |||
1222 | return FileError::build(F, Optional<size_t>(), std::move(E)); | |||
1223 | } | |||
1224 | ||||
1225 | /// Concatenate a source file path and/or name with line number and an Error. | |||
1226 | /// The resulting Error is unchecked. | |||
1227 | inline Error createFileError(const Twine &F, size_t Line, Error E) { | |||
1228 | return FileError::build(F, Optional<size_t>(Line), std::move(E)); | |||
1229 | } | |||
1230 | ||||
1231 | /// Concatenate a source file path and/or name with a std::error_code | |||
1232 | /// to form an Error object. | |||
1233 | inline Error createFileError(const Twine &F, std::error_code EC) { | |||
1234 | return createFileError(F, errorCodeToError(EC)); | |||
1235 | } | |||
1236 | ||||
1237 | /// Concatenate a source file path and/or name with line number and | |||
1238 | /// std::error_code to form an Error object. | |||
1239 | inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) { | |||
1240 | return createFileError(F, Line, errorCodeToError(EC)); | |||
1241 | } | |||
1242 | ||||
1243 | Error createFileError(const Twine &F, ErrorSuccess) = delete; | |||
1244 | ||||
1245 | /// Helper for check-and-exit error handling. | |||
1246 | /// | |||
1247 | /// For tool use only. NOT FOR USE IN LIBRARY CODE. | |||
1248 | /// | |||
1249 | class ExitOnError { | |||
1250 | public: | |||
1251 | /// Create an error on exit helper. | |||
1252 | ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1) | |||
1253 | : Banner(std::move(Banner)), | |||
1254 | GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {} | |||
1255 | ||||
1256 | /// Set the banner string for any errors caught by operator(). | |||
1257 | void setBanner(std::string Banner) { this->Banner = std::move(Banner); } | |||
1258 | ||||
1259 | /// Set the exit-code mapper function. | |||
1260 | void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) { | |||
1261 | this->GetExitCode = std::move(GetExitCode); | |||
1262 | } | |||
1263 | ||||
1264 | /// Check Err. If it's in a failure state log the error(s) and exit. | |||
1265 | void operator()(Error Err) const { checkError(std::move(Err)); } | |||
1266 | ||||
1267 | /// Check E. If it's in a success state then return the contained value. If | |||
1268 | /// it's in a failure state log the error(s) and exit. | |||
1269 | template <typename T> T operator()(Expected<T> &&E) const { | |||
1270 | checkError(E.takeError()); | |||
1271 | return std::move(*E); | |||
1272 | } | |||
1273 | ||||
1274 | /// Check E. If it's in a success state then return the contained reference. If | |||
1275 | /// it's in a failure state log the error(s) and exit. | |||
1276 | template <typename T> T& operator()(Expected<T&> &&E) const { | |||
1277 | checkError(E.takeError()); | |||
1278 | return *E; | |||
1279 | } | |||
1280 | ||||
1281 | private: | |||
1282 | void checkError(Error Err) const { | |||
1283 | if (Err) { | |||
1284 | int ExitCode = GetExitCode(Err); | |||
1285 | logAllUnhandledErrors(std::move(Err), errs(), Banner); | |||
1286 | exit(ExitCode); | |||
1287 | } | |||
1288 | } | |||
1289 | ||||
1290 | std::string Banner; | |||
1291 | std::function<int(const Error &)> GetExitCode; | |||
1292 | }; | |||
1293 | ||||
1294 | /// Conversion from Error to LLVMErrorRef for C error bindings. | |||
1295 | inline LLVMErrorRef wrap(Error Err) { | |||
1296 | return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release()); | |||
1297 | } | |||
1298 | ||||
1299 | /// Conversion from LLVMErrorRef to Error for C error bindings. | |||
1300 | inline Error unwrap(LLVMErrorRef ErrRef) { | |||
1301 | return Error(std::unique_ptr<ErrorInfoBase>( | |||
1302 | reinterpret_cast<ErrorInfoBase *>(ErrRef))); | |||
1303 | } | |||
1304 | ||||
1305 | } // end namespace llvm | |||
1306 | ||||
1307 | #endif // LLVM_SUPPORT_ERROR_H |