1 | //===--- Driver.h - Clang GCC Compatible Driver -----------------*- 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 | #ifndef LLVM_CLANG_DRIVER_DRIVER_H |
10 | #define LLVM_CLANG_DRIVER_DRIVER_H |
11 | |
12 | #include "clang/Basic/Diagnostic.h" |
13 | #include "clang/Basic/HeaderInclude.h" |
14 | #include "clang/Basic/LLVM.h" |
15 | #include "clang/Driver/Action.h" |
16 | #include "clang/Driver/DriverDiagnostic.h" |
17 | #include "clang/Driver/InputInfo.h" |
18 | #include "clang/Driver/Options.h" |
19 | #include "clang/Driver/Phases.h" |
20 | #include "clang/Driver/ToolChain.h" |
21 | #include "clang/Driver/Types.h" |
22 | #include "clang/Driver/Util.h" |
23 | #include "llvm/ADT/ArrayRef.h" |
24 | #include "llvm/ADT/STLFunctionalExtras.h" |
25 | #include "llvm/ADT/StringMap.h" |
26 | #include "llvm/ADT/StringRef.h" |
27 | #include "llvm/Option/Arg.h" |
28 | #include "llvm/Option/ArgList.h" |
29 | #include "llvm/Support/StringSaver.h" |
30 | |
31 | #include <map> |
32 | #include <set> |
33 | #include <string> |
34 | #include <vector> |
35 | |
36 | namespace llvm { |
37 | class Triple; |
38 | namespace vfs { |
39 | class FileSystem; |
40 | } |
41 | namespace cl { |
42 | class ExpansionContext; |
43 | } |
44 | } // namespace llvm |
45 | |
46 | namespace clang { |
47 | |
48 | namespace driver { |
49 | |
50 | typedef SmallVector<InputInfo, 4> InputInfoList; |
51 | |
52 | class Command; |
53 | class Compilation; |
54 | class JobAction; |
55 | class ToolChain; |
56 | |
57 | /// Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options. |
58 | enum LTOKind { |
59 | LTOK_None, |
60 | LTOK_Full, |
61 | LTOK_Thin, |
62 | LTOK_Unknown |
63 | }; |
64 | |
65 | /// Whether headers used to construct C++20 module units should be looked |
66 | /// up by the path supplied on the command line, or in the user or system |
67 | /// search paths. |
68 | enum { |
69 | , |
70 | , |
71 | , |
72 | |
73 | }; |
74 | |
75 | /// Driver - Encapsulate logic for constructing compilation processes |
76 | /// from a set of gcc-driver-like command line arguments. |
77 | class Driver { |
78 | DiagnosticsEngine &Diags; |
79 | |
80 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS; |
81 | |
82 | enum DriverMode { |
83 | GCCMode, |
84 | GXXMode, |
85 | CPPMode, |
86 | CLMode, |
87 | FlangMode, |
88 | DXCMode |
89 | } Mode; |
90 | |
91 | enum SaveTempsMode { |
92 | SaveTempsNone, |
93 | SaveTempsCwd, |
94 | SaveTempsObj |
95 | } SaveTemps; |
96 | |
97 | enum BitcodeEmbedMode { |
98 | EmbedNone, |
99 | EmbedMarker, |
100 | EmbedBitcode |
101 | } BitcodeEmbed; |
102 | |
103 | enum OffloadMode { |
104 | OffloadHostDevice, |
105 | OffloadHost, |
106 | OffloadDevice, |
107 | } Offload; |
108 | |
109 | /// Header unit mode set by -fmodule-header={user,system}. |
110 | ModuleHeaderMode ; |
111 | |
112 | /// Set if we should process inputs and jobs with C++20 module |
113 | /// interpretation. |
114 | bool ModulesModeCXX20; |
115 | |
116 | /// LTO mode selected via -f(no-)?lto(=.*)? options. |
117 | LTOKind LTOMode; |
118 | |
119 | /// LTO mode selected via -f(no-offload-)?lto(=.*)? options. |
120 | LTOKind OffloadLTOMode; |
121 | |
122 | public: |
123 | enum OpenMPRuntimeKind { |
124 | /// An unknown OpenMP runtime. We can't generate effective OpenMP code |
125 | /// without knowing what runtime to target. |
126 | OMPRT_Unknown, |
127 | |
128 | /// The LLVM OpenMP runtime. When completed and integrated, this will become |
129 | /// the default for Clang. |
130 | OMPRT_OMP, |
131 | |
132 | /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for |
133 | /// this runtime but can swallow the pragmas, and find and link against the |
134 | /// runtime library itself. |
135 | OMPRT_GOMP, |
136 | |
137 | /// The legacy name for the LLVM OpenMP runtime from when it was the Intel |
138 | /// OpenMP runtime. We support this mode for users with existing |
139 | /// dependencies on this runtime library name. |
140 | OMPRT_IOMP5 |
141 | }; |
142 | |
143 | // Diag - Forwarding function for diagnostics. |
144 | DiagnosticBuilder Diag(unsigned DiagID) const { |
145 | return Diags.Report(DiagID); |
146 | } |
147 | |
148 | // FIXME: Privatize once interface is stable. |
149 | public: |
150 | /// The name the driver was invoked as. |
151 | std::string Name; |
152 | |
153 | /// The path the driver executable was in, as invoked from the |
154 | /// command line. |
155 | std::string Dir; |
156 | |
157 | /// The original path to the clang executable. |
158 | std::string ClangExecutable; |
159 | |
160 | /// Target and driver mode components extracted from clang executable name. |
161 | ParsedClangName ClangNameParts; |
162 | |
163 | /// The path to the compiler resource directory. |
164 | std::string ResourceDir; |
165 | |
166 | /// System directory for config files. |
167 | std::string SystemConfigDir; |
168 | |
169 | /// User directory for config files. |
170 | std::string UserConfigDir; |
171 | |
172 | /// A prefix directory used to emulate a limited subset of GCC's '-Bprefix' |
173 | /// functionality. |
174 | /// FIXME: This type of customization should be removed in favor of the |
175 | /// universal driver when it is ready. |
176 | typedef SmallVector<std::string, 4> prefix_list; |
177 | prefix_list PrefixDirs; |
178 | |
179 | /// sysroot, if present |
180 | std::string SysRoot; |
181 | |
182 | /// Dynamic loader prefix, if present |
183 | std::string DyldPrefix; |
184 | |
185 | /// Driver title to use with help. |
186 | std::string DriverTitle; |
187 | |
188 | /// Information about the host which can be overridden by the user. |
189 | std::string HostBits, HostMachine, HostSystem, HostRelease; |
190 | |
191 | /// The file to log CC_PRINT_PROC_STAT_FILE output to, if enabled. |
192 | std::string CCPrintStatReportFilename; |
193 | |
194 | /// The file to log CC_PRINT_INTERNAL_STAT_FILE output to, if enabled. |
195 | std::string CCPrintInternalStatReportFilename; |
196 | |
197 | /// The file to log CC_PRINT_OPTIONS output to, if enabled. |
198 | std::string CCPrintOptionsFilename; |
199 | |
200 | /// The file to log CC_PRINT_HEADERS output to, if enabled. |
201 | std::string ; |
202 | |
203 | /// The file to log CC_LOG_DIAGNOSTICS output to, if enabled. |
204 | std::string CCLogDiagnosticsFilename; |
205 | |
206 | /// An input type and its arguments. |
207 | using InputTy = std::pair<types::ID, const llvm::opt::Arg *>; |
208 | |
209 | /// A list of inputs and their types for the given arguments. |
210 | using InputList = SmallVector<InputTy, 16>; |
211 | |
212 | /// Whether the driver should follow g++ like behavior. |
213 | bool CCCIsCXX() const { return Mode == GXXMode; } |
214 | |
215 | /// Whether the driver is just the preprocessor. |
216 | bool CCCIsCPP() const { return Mode == CPPMode; } |
217 | |
218 | /// Whether the driver should follow gcc like behavior. |
219 | bool CCCIsCC() const { return Mode == GCCMode; } |
220 | |
221 | /// Whether the driver should follow cl.exe like behavior. |
222 | bool IsCLMode() const { return Mode == CLMode; } |
223 | |
224 | /// Whether the driver should invoke flang for fortran inputs. |
225 | /// Other modes fall back to calling gcc which in turn calls gfortran. |
226 | bool IsFlangMode() const { return Mode == FlangMode; } |
227 | |
228 | /// Whether the driver should follow dxc.exe like behavior. |
229 | bool IsDXCMode() const { return Mode == DXCMode; } |
230 | |
231 | /// Only print tool bindings, don't build any jobs. |
232 | LLVM_PREFERRED_TYPE(bool) |
233 | unsigned CCCPrintBindings : 1; |
234 | |
235 | /// Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to |
236 | /// CCPrintOptionsFilename or to stderr. |
237 | LLVM_PREFERRED_TYPE(bool) |
238 | unsigned CCPrintOptions : 1; |
239 | |
240 | /// The format of the header information that is emitted. If CC_PRINT_HEADERS |
241 | /// is set, the format is textual. Otherwise, the format is determined by the |
242 | /// enviroment variable CC_PRINT_HEADERS_FORMAT. |
243 | HeaderIncludeFormatKind = HIFMT_None; |
244 | |
245 | /// This flag determines whether clang should filter the header information |
246 | /// that is emitted. If enviroment variable CC_PRINT_HEADERS_FILTERING is set |
247 | /// to "only-direct-system", only system headers that are directly included |
248 | /// from non-system headers are emitted. |
249 | HeaderIncludeFilteringKind = HIFIL_None; |
250 | |
251 | /// Name of the library that provides implementations of |
252 | /// IEEE-754 128-bit float math functions used by Fortran F128 |
253 | /// runtime library. It should be linked as needed by the linker job. |
254 | std::string FlangF128MathLibrary; |
255 | |
256 | /// Set CC_LOG_DIAGNOSTICS mode, which causes the frontend to log diagnostics |
257 | /// to CCLogDiagnosticsFilename or to stderr, in a stable machine readable |
258 | /// format. |
259 | LLVM_PREFERRED_TYPE(bool) |
260 | unsigned CCLogDiagnostics : 1; |
261 | |
262 | /// Whether the driver is generating diagnostics for debugging purposes. |
263 | LLVM_PREFERRED_TYPE(bool) |
264 | unsigned CCGenDiagnostics : 1; |
265 | |
266 | /// Set CC_PRINT_PROC_STAT mode, which causes the driver to dump |
267 | /// performance report to CC_PRINT_PROC_STAT_FILE or to stdout. |
268 | LLVM_PREFERRED_TYPE(bool) |
269 | unsigned CCPrintProcessStats : 1; |
270 | |
271 | /// Set CC_PRINT_INTERNAL_STAT mode, which causes the driver to dump internal |
272 | /// performance report to CC_PRINT_INTERNAL_STAT_FILE or to stdout. |
273 | LLVM_PREFERRED_TYPE(bool) |
274 | unsigned CCPrintInternalStats : 1; |
275 | |
276 | /// Pointer to the ExecuteCC1Tool function, if available. |
277 | /// When the clangDriver lib is used through clang.exe, this provides a |
278 | /// shortcut for executing the -cc1 command-line directly, in the same |
279 | /// process. |
280 | using CC1ToolFunc = |
281 | llvm::function_ref<int(SmallVectorImpl<const char *> &ArgV)>; |
282 | CC1ToolFunc CC1Main = nullptr; |
283 | |
284 | private: |
285 | /// Raw target triple. |
286 | std::string TargetTriple; |
287 | |
288 | /// Name to use when invoking gcc/g++. |
289 | std::string CCCGenericGCCName; |
290 | |
291 | /// Paths to configuration files used. |
292 | std::vector<std::string> ConfigFiles; |
293 | |
294 | /// Allocator for string saver. |
295 | llvm::BumpPtrAllocator Alloc; |
296 | |
297 | /// Object that stores strings read from configuration file. |
298 | llvm::StringSaver Saver; |
299 | |
300 | /// Arguments originated from configuration file. |
301 | std::unique_ptr<llvm::opt::InputArgList> CfgOptions; |
302 | |
303 | /// Arguments originated from command line. |
304 | std::unique_ptr<llvm::opt::InputArgList> CLOptions; |
305 | |
306 | /// If this is non-null, the driver will prepend this argument before |
307 | /// reinvoking clang. This is useful for the llvm-driver where clang's |
308 | /// realpath will be to the llvm binary and not clang, so it must pass |
309 | /// "clang" as it's first argument. |
310 | const char *PrependArg; |
311 | |
312 | /// Whether to check that input files exist when constructing compilation |
313 | /// jobs. |
314 | LLVM_PREFERRED_TYPE(bool) |
315 | unsigned CheckInputsExist : 1; |
316 | /// Whether to probe for PCH files on disk, in order to upgrade |
317 | /// -include foo.h to -include-pch foo.h.pch. |
318 | LLVM_PREFERRED_TYPE(bool) |
319 | unsigned ProbePrecompiled : 1; |
320 | |
321 | public: |
322 | // getFinalPhase - Determine which compilation mode we are in and record |
323 | // which option we used to determine the final phase. |
324 | // TODO: Much of what getFinalPhase returns are not actually true compiler |
325 | // modes. Fold this functionality into Types::getCompilationPhases and |
326 | // handleArguments. |
327 | phases::ID getFinalPhase(const llvm::opt::DerivedArgList &DAL, |
328 | llvm::opt::Arg **FinalPhaseArg = nullptr) const; |
329 | |
330 | private: |
331 | /// Certain options suppress the 'no input files' warning. |
332 | LLVM_PREFERRED_TYPE(bool) |
333 | unsigned SuppressMissingInputWarning : 1; |
334 | |
335 | /// Cache of all the ToolChains in use by the driver. |
336 | /// |
337 | /// This maps from the string representation of a triple to a ToolChain |
338 | /// created targeting that triple. The driver owns all the ToolChain objects |
339 | /// stored in it, and will clean them up when torn down. |
340 | mutable llvm::StringMap<std::unique_ptr<ToolChain>> ToolChains; |
341 | |
342 | /// Cache of known offloading architectures for the ToolChain already derived. |
343 | /// This should only be modified when we first initialize the offloading |
344 | /// toolchains. |
345 | llvm::DenseMap<const ToolChain *, llvm::DenseSet<llvm::StringRef>> KnownArchs; |
346 | |
347 | private: |
348 | /// TranslateInputArgs - Create a new derived argument list from the input |
349 | /// arguments, after applying the standard argument translations. |
350 | llvm::opt::DerivedArgList * |
351 | TranslateInputArgs(const llvm::opt::InputArgList &Args) const; |
352 | |
353 | // handleArguments - All code related to claiming and printing diagnostics |
354 | // related to arguments to the driver are done here. |
355 | void handleArguments(Compilation &C, llvm::opt::DerivedArgList &Args, |
356 | const InputList &Inputs, ActionList &Actions) const; |
357 | |
358 | // Before executing jobs, sets up response files for commands that need them. |
359 | void setUpResponseFiles(Compilation &C, Command &Cmd); |
360 | |
361 | void generatePrefixedToolNames(StringRef Tool, const ToolChain &TC, |
362 | SmallVectorImpl<std::string> &Names) const; |
363 | |
364 | /// Find the appropriate .crash diagonostic file for the child crash |
365 | /// under this driver and copy it out to a temporary destination with the |
366 | /// other reproducer related files (.sh, .cache, etc). If not found, suggest a |
367 | /// directory for the user to look at. |
368 | /// |
369 | /// \param ReproCrashFilename The file path to copy the .crash to. |
370 | /// \param CrashDiagDir The suggested directory for the user to look at |
371 | /// in case the search or copy fails. |
372 | /// |
373 | /// \returns If the .crash is found and successfully copied return true, |
374 | /// otherwise false and return the suggested directory in \p CrashDiagDir. |
375 | bool getCrashDiagnosticFile(StringRef ReproCrashFilename, |
376 | SmallString<128> &CrashDiagDir); |
377 | |
378 | public: |
379 | |
380 | /// Takes the path to a binary that's either in bin/ or lib/ and returns |
381 | /// the path to clang's resource directory. |
382 | static std::string GetResourcesPath(StringRef BinaryPath, |
383 | StringRef CustomResourceDir = "" ); |
384 | |
385 | Driver(StringRef ClangExecutable, StringRef TargetTriple, |
386 | DiagnosticsEngine &Diags, std::string Title = "clang LLVM compiler" , |
387 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr); |
388 | |
389 | /// @name Accessors |
390 | /// @{ |
391 | |
392 | /// Name to use when invoking gcc/g++. |
393 | const std::string &getCCCGenericGCCName() const { return CCCGenericGCCName; } |
394 | |
395 | llvm::ArrayRef<std::string> getConfigFiles() const { |
396 | return ConfigFiles; |
397 | } |
398 | |
399 | const llvm::opt::OptTable &getOpts() const { return getDriverOptTable(); } |
400 | |
401 | DiagnosticsEngine &getDiags() const { return Diags; } |
402 | |
403 | llvm::vfs::FileSystem &getVFS() const { return *VFS; } |
404 | |
405 | bool getCheckInputsExist() const { return CheckInputsExist; } |
406 | |
407 | void setCheckInputsExist(bool Value) { CheckInputsExist = Value; } |
408 | |
409 | bool getProbePrecompiled() const { return ProbePrecompiled; } |
410 | void setProbePrecompiled(bool Value) { ProbePrecompiled = Value; } |
411 | |
412 | const char *getPrependArg() const { return PrependArg; } |
413 | void setPrependArg(const char *Value) { PrependArg = Value; } |
414 | |
415 | void setTargetAndMode(const ParsedClangName &TM) { ClangNameParts = TM; } |
416 | |
417 | const std::string &getTitle() { return DriverTitle; } |
418 | void setTitle(std::string Value) { DriverTitle = std::move(Value); } |
419 | |
420 | std::string getTargetTriple() const { return TargetTriple; } |
421 | |
422 | /// Get the path to the main clang executable. |
423 | const char *getClangProgramPath() const { |
424 | return ClangExecutable.c_str(); |
425 | } |
426 | |
427 | /// Get the path to where the clang executable was installed. |
428 | const char *getInstalledDir() const { |
429 | return Dir.c_str(); |
430 | } |
431 | |
432 | bool isSaveTempsEnabled() const { return SaveTemps != SaveTempsNone; } |
433 | bool isSaveTempsObj() const { return SaveTemps == SaveTempsObj; } |
434 | |
435 | bool embedBitcodeEnabled() const { return BitcodeEmbed != EmbedNone; } |
436 | bool embedBitcodeInObject() const { return (BitcodeEmbed == EmbedBitcode); } |
437 | bool embedBitcodeMarkerOnly() const { return (BitcodeEmbed == EmbedMarker); } |
438 | |
439 | bool offloadHostOnly() const { return Offload == OffloadHost; } |
440 | bool offloadDeviceOnly() const { return Offload == OffloadDevice; } |
441 | |
442 | void setFlangF128MathLibrary(std::string name) { |
443 | FlangF128MathLibrary = std::move(name); |
444 | } |
445 | StringRef getFlangF128MathLibrary() const { return FlangF128MathLibrary; } |
446 | |
447 | /// Compute the desired OpenMP runtime from the flags provided. |
448 | OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const; |
449 | |
450 | /// @} |
451 | /// @name Primary Functionality |
452 | /// @{ |
453 | |
454 | /// CreateOffloadingDeviceToolChains - create all the toolchains required to |
455 | /// support offloading devices given the programming models specified in the |
456 | /// current compilation. Also, update the host tool chain kind accordingly. |
457 | void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs); |
458 | |
459 | /// BuildCompilation - Construct a compilation object for a command |
460 | /// line argument vector. |
461 | /// |
462 | /// \return A compilation, or 0 if none was built for the given |
463 | /// argument vector. A null return value does not necessarily |
464 | /// indicate an error condition, the diagnostics should be queried |
465 | /// to determine if an error occurred. |
466 | Compilation *BuildCompilation(ArrayRef<const char *> Args); |
467 | |
468 | /// ParseArgStrings - Parse the given list of strings into an |
469 | /// ArgList. |
470 | llvm::opt::InputArgList ParseArgStrings(ArrayRef<const char *> Args, |
471 | bool UseDriverMode, |
472 | bool &ContainsError); |
473 | |
474 | /// BuildInputs - Construct the list of inputs and their types from |
475 | /// the given arguments. |
476 | /// |
477 | /// \param TC - The default host tool chain. |
478 | /// \param Args - The input arguments. |
479 | /// \param Inputs - The list to store the resulting compilation |
480 | /// inputs onto. |
481 | void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args, |
482 | InputList &Inputs) const; |
483 | |
484 | /// BuildActions - Construct the list of actions to perform for the |
485 | /// given arguments, which are only done for a single architecture. |
486 | /// |
487 | /// \param C - The compilation that is being built. |
488 | /// \param Args - The input arguments. |
489 | /// \param Actions - The list to store the resulting actions onto. |
490 | void BuildActions(Compilation &C, llvm::opt::DerivedArgList &Args, |
491 | const InputList &Inputs, ActionList &Actions) const; |
492 | |
493 | /// BuildUniversalActions - Construct the list of actions to perform |
494 | /// for the given arguments, which may require a universal build. |
495 | /// |
496 | /// \param C - The compilation that is being built. |
497 | /// \param TC - The default host tool chain. |
498 | void BuildUniversalActions(Compilation &C, const ToolChain &TC, |
499 | const InputList &BAInputs) const; |
500 | |
501 | /// BuildOffloadingActions - Construct the list of actions to perform for the |
502 | /// offloading toolchain that will be embedded in the host. |
503 | /// |
504 | /// \param C - The compilation that is being built. |
505 | /// \param Args - The input arguments. |
506 | /// \param Input - The input type and arguments |
507 | /// \param HostAction - The host action used in the offloading toolchain. |
508 | Action *BuildOffloadingActions(Compilation &C, |
509 | llvm::opt::DerivedArgList &Args, |
510 | const InputTy &Input, |
511 | Action *HostAction) const; |
512 | |
513 | /// Returns the set of bound architectures active for this offload kind. |
514 | /// If there are no bound architctures we return a set containing only the |
515 | /// empty string. The \p SuppressError option is used to suppress errors. |
516 | llvm::DenseSet<StringRef> |
517 | getOffloadArchs(Compilation &C, const llvm::opt::DerivedArgList &Args, |
518 | Action::OffloadKind Kind, const ToolChain *TC, |
519 | bool SuppressError = false) const; |
520 | |
521 | /// Check that the file referenced by Value exists. If it doesn't, |
522 | /// issue a diagnostic and return false. |
523 | /// If TypoCorrect is true and the file does not exist, see if it looks |
524 | /// like a likely typo for a flag and if so print a "did you mean" blurb. |
525 | bool DiagnoseInputExistence(const llvm::opt::DerivedArgList &Args, |
526 | StringRef Value, types::ID Ty, |
527 | bool TypoCorrect) const; |
528 | |
529 | /// BuildJobs - Bind actions to concrete tools and translate |
530 | /// arguments to form the list of jobs to run. |
531 | /// |
532 | /// \param C - The compilation that is being built. |
533 | void BuildJobs(Compilation &C) const; |
534 | |
535 | /// ExecuteCompilation - Execute the compilation according to the command line |
536 | /// arguments and return an appropriate exit code. |
537 | /// |
538 | /// This routine handles additional processing that must be done in addition |
539 | /// to just running the subprocesses, for example reporting errors, setting |
540 | /// up response files, removing temporary files, etc. |
541 | int ExecuteCompilation(Compilation &C, |
542 | SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands); |
543 | |
544 | /// Contains the files in the compilation diagnostic report generated by |
545 | /// generateCompilationDiagnostics. |
546 | struct CompilationDiagnosticReport { |
547 | llvm::SmallVector<std::string, 4> TemporaryFiles; |
548 | }; |
549 | |
550 | /// generateCompilationDiagnostics - Generate diagnostics information |
551 | /// including preprocessed source file(s). |
552 | /// |
553 | void generateCompilationDiagnostics( |
554 | Compilation &C, const Command &FailingCommand, |
555 | StringRef AdditionalInformation = "" , |
556 | CompilationDiagnosticReport *GeneratedReport = nullptr); |
557 | |
558 | enum class CommandStatus { |
559 | Crash = 1, |
560 | Error, |
561 | Ok, |
562 | }; |
563 | |
564 | enum class ReproLevel { |
565 | Off = 0, |
566 | OnCrash = static_cast<int>(CommandStatus::Crash), |
567 | OnError = static_cast<int>(CommandStatus::Error), |
568 | Always = static_cast<int>(CommandStatus::Ok), |
569 | }; |
570 | |
571 | bool maybeGenerateCompilationDiagnostics( |
572 | CommandStatus CS, ReproLevel Level, Compilation &C, |
573 | const Command &FailingCommand, StringRef AdditionalInformation = "" , |
574 | CompilationDiagnosticReport *GeneratedReport = nullptr) { |
575 | if (static_cast<int>(CS) > static_cast<int>(Level)) |
576 | return false; |
577 | if (CS != CommandStatus::Crash) |
578 | Diags.Report(diag::err_drv_force_crash) |
579 | << !::getenv(name: "FORCE_CLANG_DIAGNOSTICS_CRASH" ); |
580 | // Hack to ensure that diagnostic notes get emitted. |
581 | Diags.setLastDiagnosticIgnored(false); |
582 | generateCompilationDiagnostics(C, FailingCommand, AdditionalInformation, |
583 | GeneratedReport); |
584 | return true; |
585 | } |
586 | |
587 | /// @} |
588 | /// @name Helper Methods |
589 | /// @{ |
590 | |
591 | /// PrintActions - Print the list of actions. |
592 | void PrintActions(const Compilation &C) const; |
593 | |
594 | /// PrintHelp - Print the help text. |
595 | /// |
596 | /// \param ShowHidden - Show hidden options. |
597 | void PrintHelp(bool ShowHidden) const; |
598 | |
599 | /// PrintVersion - Print the driver version. |
600 | void PrintVersion(const Compilation &C, raw_ostream &OS) const; |
601 | |
602 | /// GetFilePath - Lookup \p Name in the list of file search paths. |
603 | /// |
604 | /// \param TC - The tool chain for additional information on |
605 | /// directories to search. |
606 | // |
607 | // FIXME: This should be in CompilationInfo. |
608 | std::string GetFilePath(StringRef Name, const ToolChain &TC) const; |
609 | |
610 | /// GetProgramPath - Lookup \p Name in the list of program search paths. |
611 | /// |
612 | /// \param TC - The provided tool chain for additional information on |
613 | /// directories to search. |
614 | // |
615 | // FIXME: This should be in CompilationInfo. |
616 | std::string GetProgramPath(StringRef Name, const ToolChain &TC) const; |
617 | |
618 | /// Lookup the path to the Standard library module manifest. |
619 | /// |
620 | /// \param C - The compilation. |
621 | /// \param TC - The tool chain for additional information on |
622 | /// directories to search. |
623 | // |
624 | // FIXME: This should be in CompilationInfo. |
625 | std::string GetStdModuleManifestPath(const Compilation &C, |
626 | const ToolChain &TC) const; |
627 | |
628 | /// HandleAutocompletions - Handle --autocomplete by searching and printing |
629 | /// possible flags, descriptions, and its arguments. |
630 | void HandleAutocompletions(StringRef PassedFlags) const; |
631 | |
632 | /// HandleImmediateArgs - Handle any arguments which should be |
633 | /// treated before building actions or binding tools. |
634 | /// |
635 | /// \return Whether any compilation should be built for this |
636 | /// invocation. |
637 | bool HandleImmediateArgs(const Compilation &C); |
638 | |
639 | /// ConstructAction - Construct the appropriate action to do for |
640 | /// \p Phase on the \p Input, taking in to account arguments |
641 | /// like -fsyntax-only or --analyze. |
642 | Action *ConstructPhaseAction( |
643 | Compilation &C, const llvm::opt::ArgList &Args, phases::ID Phase, |
644 | Action *Input, |
645 | Action::OffloadKind TargetDeviceOffloadKind = Action::OFK_None) const; |
646 | |
647 | /// BuildJobsForAction - Construct the jobs to perform for the action \p A and |
648 | /// return an InputInfo for the result of running \p A. Will only construct |
649 | /// jobs for a given (Action, ToolChain, BoundArch, DeviceKind) tuple once. |
650 | InputInfoList BuildJobsForAction( |
651 | Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, |
652 | bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, |
653 | std::map<std::pair<const Action *, std::string>, InputInfoList> |
654 | &CachedResults, |
655 | Action::OffloadKind TargetDeviceOffloadKind) const; |
656 | |
657 | /// Returns the default name for linked images (e.g., "a.out"). |
658 | const char *getDefaultImageName() const; |
659 | |
660 | /// Creates a temp file. |
661 | /// 1. If \p MultipleArch is false or \p BoundArch is empty, the temp file is |
662 | /// in the temporary directory with name $Prefix-%%%%%%.$Suffix. |
663 | /// 2. If \p MultipleArch is true and \p BoundArch is not empty, |
664 | /// 2a. If \p NeedUniqueDirectory is false, the temp file is in the |
665 | /// temporary directory with name $Prefix-$BoundArch-%%%%%.$Suffix. |
666 | /// 2b. If \p NeedUniqueDirectory is true, the temp file is in a unique |
667 | /// subdiretory with random name under the temporary directory, and |
668 | /// the temp file itself has name $Prefix-$BoundArch.$Suffix. |
669 | const char *CreateTempFile(Compilation &C, StringRef Prefix, StringRef Suffix, |
670 | bool MultipleArchs = false, |
671 | StringRef BoundArch = {}, |
672 | bool NeedUniqueDirectory = false) const; |
673 | |
674 | /// GetNamedOutputPath - Return the name to use for the output of |
675 | /// the action \p JA. The result is appended to the compilation's |
676 | /// list of temporary or result files, as appropriate. |
677 | /// |
678 | /// \param C - The compilation. |
679 | /// \param JA - The action of interest. |
680 | /// \param BaseInput - The original input file that this action was |
681 | /// triggered by. |
682 | /// \param BoundArch - The bound architecture. |
683 | /// \param AtTopLevel - Whether this is a "top-level" action. |
684 | /// \param MultipleArchs - Whether multiple -arch options were supplied. |
685 | /// \param NormalizedTriple - The normalized triple of the relevant target. |
686 | const char *GetNamedOutputPath(Compilation &C, const JobAction &JA, |
687 | const char *BaseInput, StringRef BoundArch, |
688 | bool AtTopLevel, bool MultipleArchs, |
689 | StringRef NormalizedTriple) const; |
690 | |
691 | /// GetTemporaryPath - Return the pathname of a temporary file to use |
692 | /// as part of compilation; the file will have the given prefix and suffix. |
693 | /// |
694 | /// GCC goes to extra lengths here to be a bit more robust. |
695 | std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const; |
696 | |
697 | /// GetTemporaryDirectory - Return the pathname of a temporary directory to |
698 | /// use as part of compilation; the directory will have the given prefix. |
699 | std::string GetTemporaryDirectory(StringRef Prefix) const; |
700 | |
701 | /// Return the pathname of the pch file in clang-cl mode. |
702 | std::string GetClPchPath(Compilation &C, StringRef BaseName) const; |
703 | |
704 | /// ShouldUseClangCompiler - Should the clang compiler be used to |
705 | /// handle this action. |
706 | bool ShouldUseClangCompiler(const JobAction &JA) const; |
707 | |
708 | /// ShouldUseFlangCompiler - Should the flang compiler be used to |
709 | /// handle this action. |
710 | bool ShouldUseFlangCompiler(const JobAction &JA) const; |
711 | |
712 | /// ShouldEmitStaticLibrary - Should the linker emit a static library. |
713 | bool ShouldEmitStaticLibrary(const llvm::opt::ArgList &Args) const; |
714 | |
715 | /// Returns true if the user has indicated a C++20 header unit mode. |
716 | bool () const { return CXX20HeaderType != HeaderMode_None; } |
717 | |
718 | /// Get the mode for handling headers as set by fmodule-header{=}. |
719 | ModuleHeaderMode () const { return CXX20HeaderType; } |
720 | |
721 | /// Returns true if we are performing any kind of LTO. |
722 | bool isUsingLTO(bool IsOffload = false) const { |
723 | return getLTOMode(IsOffload) != LTOK_None; |
724 | } |
725 | |
726 | /// Get the specific kind of LTO being performed. |
727 | LTOKind getLTOMode(bool IsOffload = false) const { |
728 | return IsOffload ? OffloadLTOMode : LTOMode; |
729 | } |
730 | |
731 | private: |
732 | |
733 | /// Tries to load options from configuration files. |
734 | /// |
735 | /// \returns true if error occurred. |
736 | bool loadConfigFiles(); |
737 | |
738 | /// Tries to load options from default configuration files (deduced from |
739 | /// executable filename). |
740 | /// |
741 | /// \returns true if error occurred. |
742 | bool loadDefaultConfigFiles(llvm::cl::ExpansionContext &ExpCtx); |
743 | |
744 | /// Read options from the specified file. |
745 | /// |
746 | /// \param [in] FileName File to read. |
747 | /// \param [in] Search and expansion options. |
748 | /// \returns true, if error occurred while reading. |
749 | bool readConfigFile(StringRef FileName, llvm::cl::ExpansionContext &ExpCtx); |
750 | |
751 | /// Set the driver mode (cl, gcc, etc) from the value of the `--driver-mode` |
752 | /// option. |
753 | void setDriverMode(StringRef DriverModeValue); |
754 | |
755 | /// Parse the \p Args list for LTO options and record the type of LTO |
756 | /// compilation based on which -f(no-)?lto(=.*)? option occurs last. |
757 | void setLTOMode(const llvm::opt::ArgList &Args); |
758 | |
759 | /// Retrieves a ToolChain for a particular \p Target triple. |
760 | /// |
761 | /// Will cache ToolChains for the life of the driver object, and create them |
762 | /// on-demand. |
763 | const ToolChain &getToolChain(const llvm::opt::ArgList &Args, |
764 | const llvm::Triple &Target) const; |
765 | |
766 | /// @} |
767 | |
768 | /// Retrieves a ToolChain for a particular device \p Target triple |
769 | /// |
770 | /// \param[in] HostTC is the host ToolChain paired with the device |
771 | /// |
772 | /// \param[in] TargetDeviceOffloadKind (e.g. OFK_Cuda/OFK_OpenMP/OFK_SYCL) is |
773 | /// an Offloading action that is optionally passed to a ToolChain (used by |
774 | /// CUDA, to specify if it's used in conjunction with OpenMP) |
775 | /// |
776 | /// Will cache ToolChains for the life of the driver object, and create them |
777 | /// on-demand. |
778 | const ToolChain &getOffloadingDeviceToolChain( |
779 | const llvm::opt::ArgList &Args, const llvm::Triple &Target, |
780 | const ToolChain &HostTC, |
781 | const Action::OffloadKind &TargetDeviceOffloadKind) const; |
782 | |
783 | /// Get bitmasks for which option flags to include and exclude based on |
784 | /// the driver mode. |
785 | llvm::opt::Visibility |
786 | getOptionVisibilityMask(bool UseDriverMode = true) const; |
787 | |
788 | /// Helper used in BuildJobsForAction. Doesn't use the cache when building |
789 | /// jobs specifically for the given action, but will use the cache when |
790 | /// building jobs for the Action's inputs. |
791 | InputInfoList BuildJobsForActionNoCache( |
792 | Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch, |
793 | bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, |
794 | std::map<std::pair<const Action *, std::string>, InputInfoList> |
795 | &CachedResults, |
796 | Action::OffloadKind TargetDeviceOffloadKind) const; |
797 | |
798 | /// Return the typical executable name for the specified driver \p Mode. |
799 | static const char *getExecutableForDriverMode(DriverMode Mode); |
800 | |
801 | public: |
802 | /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and |
803 | /// return the grouped values as integers. Numbers which are not |
804 | /// provided are set to 0. |
805 | /// |
806 | /// \return True if the entire string was parsed (9.2), or all |
807 | /// groups were parsed (10.3.5extrastuff). HadExtra is true if all |
808 | /// groups were parsed but extra characters remain at the end. |
809 | static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor, |
810 | unsigned &Micro, bool &); |
811 | |
812 | /// Parse digits from a string \p Str and fulfill \p Digits with |
813 | /// the parsed numbers. This method assumes that the max number of |
814 | /// digits to look for is equal to Digits.size(). |
815 | /// |
816 | /// \return True if the entire string was parsed and there are |
817 | /// no extra characters remaining at the end. |
818 | static bool GetReleaseVersion(StringRef Str, |
819 | MutableArrayRef<unsigned> Digits); |
820 | /// Compute the default -fmodule-cache-path. |
821 | /// \return True if the system provides a default cache directory. |
822 | static bool getDefaultModuleCachePath(SmallVectorImpl<char> &Result); |
823 | }; |
824 | |
825 | /// \return True if the last defined optimization level is -Ofast. |
826 | /// And False otherwise. |
827 | bool isOptimizationLevelFast(const llvm::opt::ArgList &Args); |
828 | |
829 | /// \return True if the argument combination will end up generating remarks. |
830 | bool (const llvm::opt::ArgList &Args); |
831 | |
832 | /// Returns the driver mode option's value, i.e. `X` in `--driver-mode=X`. If \p |
833 | /// Args doesn't mention one explicitly, tries to deduce from `ProgName`. |
834 | /// Returns empty on failure. |
835 | /// Common values are "gcc", "g++", "cpp", "cl" and "flang". Returned value need |
836 | /// not be one of these. |
837 | llvm::StringRef getDriverMode(StringRef ProgName, ArrayRef<const char *> Args); |
838 | |
839 | /// Checks whether the value produced by getDriverMode is for CL mode. |
840 | bool IsClangCL(StringRef DriverMode); |
841 | |
842 | /// Expand response files from a clang driver or cc1 invocation. |
843 | /// |
844 | /// \param Args The arguments that will be expanded. |
845 | /// \param ClangCLMode Whether clang is in CL mode. |
846 | /// \param Alloc Allocator for new arguments. |
847 | /// \param FS Filesystem to use when expanding files. |
848 | llvm::Error expandResponseFiles(SmallVectorImpl<const char *> &Args, |
849 | bool ClangCLMode, llvm::BumpPtrAllocator &Alloc, |
850 | llvm::vfs::FileSystem *FS = nullptr); |
851 | |
852 | /// Apply a space separated list of edits to the input argument lists. |
853 | /// See applyOneOverrideOption. |
854 | void applyOverrideOptions(SmallVectorImpl<const char *> &Args, |
855 | const char *OverrideOpts, |
856 | llvm::StringSet<> &SavedStrings, |
857 | raw_ostream *OS = nullptr); |
858 | |
859 | } // end namespace driver |
860 | } // end namespace clang |
861 | |
862 | #endif |
863 | |