clang 24.0.0git
Compilation.cpp
Go to the documentation of this file.
1//===- Compilation.cpp - Compilation Task Implementation ------------------===//
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
10#include "ClangCLArgs.h"
11#include "clang/Basic/LLVM.h"
12#include "clang/Driver/Action.h"
14#include "clang/Driver/Driver.h"
15#include "clang/Driver/Job.h"
17#include "clang/Driver/Util.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/Option/ArgList.h"
22#include "llvm/Option/OptSpecifier.h"
23#include "llvm/Option/Option.h"
24#include "llvm/Support/FileSystem.h"
25#include "llvm/Support/ThreadPool.h"
26#include "llvm/Support/Threading.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/TargetParser/Triple.h"
29#include <algorithm>
30#include <cassert>
31#include <optional>
32#include <string>
33#include <system_error>
34#include <utility>
35
36using namespace clang;
37using namespace driver;
38using namespace llvm::opt;
39
40Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
41 InputArgList *_Args, DerivedArgList *_TranslatedArgs,
42 bool ContainsError)
43 : TheDriver(D), DefaultToolChain(_DefaultToolChain), Args(_Args),
44 TranslatedArgs(_TranslatedArgs), ContainsError(ContainsError) {
45 // The offloading host toolchain is the default toolchain.
46 OrderedOffloadingToolchains.insert(
47 std::make_pair(Action::OFK_Host, &DefaultToolChain));
48}
49
51 // Remove temporary files. This must be done before arguments are freed, as
52 // the file names might be derived from the input arguments.
53 if (!TheDriver.isSaveTempsEnabled() && !ForceKeepTempFiles)
54 CleanupFileList(TempFiles);
55
56 delete TranslatedArgs;
57 delete Args;
58
59 // Free any derived arg lists.
60 for (auto Arg : TCArgs)
61 if (Arg.second != TranslatedArgs)
62 delete Arg.second;
63}
64
65const DerivedArgList &
67 Action::OffloadKind DeviceOffloadKind) {
68 if (!TC)
69 TC = &DefaultToolChain;
70
71 DerivedArgList *&Entry = TCArgs[{TC, BA, DeviceOffloadKind}];
72 if (!Entry) {
73 SmallVector<Arg *, 4> AllocatedArgs;
74 DerivedArgList *OpenMPArgs = nullptr;
75 // Translate OpenMP toolchain arguments provided via the -Xopenmp-target flags.
76 if (DeviceOffloadKind == Action::OFK_OpenMP) {
78 OpenMPArgs = TC->TranslateOpenMPTargetArgs(
79 *TranslatedArgs, HostTC->getTriple(), AllocatedArgs);
80 }
81
82 DerivedArgList *NewDAL = nullptr;
83 if (!OpenMPArgs) {
84 NewDAL = TC->TranslateXarchArgs(*TranslatedArgs, BA, DeviceOffloadKind,
85 &AllocatedArgs);
86 } else {
87 NewDAL = TC->TranslateXarchArgs(*OpenMPArgs, BA, DeviceOffloadKind,
88 &AllocatedArgs);
89 if (!NewDAL)
90 NewDAL = OpenMPArgs;
91 else
92 delete OpenMPArgs;
93 }
94
95 if (NewDAL && TheDriver.IsCLMode()) {
96 // Forwarding can introduce clang-cl options after the shared
97 // translation. Keep synthesized arguments in the compilation-owned list.
99 *NewDAL, DefaultToolChain.getTriple(), *TranslatedArgs);
100 delete NewDAL;
101 NewDAL = DAL;
102 }
103
104 if (!NewDAL) {
105 Entry = TC->TranslateArgs(*TranslatedArgs, BA, DeviceOffloadKind);
106 if (!Entry)
107 Entry = TranslatedArgs;
108 } else {
109 Entry = TC->TranslateArgs(*NewDAL, BA, DeviceOffloadKind);
110 if (!Entry)
111 Entry = NewDAL;
112 else
113 delete NewDAL;
114 }
115
116 // Add allocated arguments to the final DAL.
117 for (auto *ArgPtr : AllocatedArgs)
118 Entry->AddSynthesizedArg(ArgPtr);
119 }
120
121 return *Entry;
122}
123
125 StringRef Device) {
126 SmallVector<StringRef, 2> &Devices = IGCADevices[{TC, Target}];
127 auto It = llvm::lower_bound(Devices, Device);
128 if (It == Devices.end() || *It != Device)
129 Devices.insert(It, Device);
130}
131
133 StringRef Target) const {
134 auto It = IGCADevices.find({TC, Target});
135 if (It == IGCADevices.end())
136 return {};
137 return It->second;
138}
139
140bool Compilation::CleanupFile(const char *File, bool IssueErrors) const {
141 // FIXME: Why are we trying to remove files that we have not created? For
142 // example we should only try to remove a temporary assembly file if
143 // "clang -cc1" succeed in writing it. Was this a workaround for when
144 // clang was writing directly to a .s file and sometimes leaving it behind
145 // during a failure?
146
147 // FIXME: If this is necessary, we can still try to split
148 // llvm::sys::fs::remove into a removeFile and a removeDir and avoid the
149 // duplicated stat from is_regular_file.
150
151 // Don't try to remove files which we don't have write access to (but may be
152 // able to remove), or non-regular files. Underlying tools may have
153 // intentionally not overwritten them.
154 if (!llvm::sys::fs::can_write(File) || !llvm::sys::fs::is_regular_file(File))
155 return true;
156
157 if (std::error_code EC = llvm::sys::fs::remove(File)) {
158 // Failure is only failure if the file exists and is "regular". We checked
159 // for it being regular before, and llvm::sys::fs::remove ignores ENOENT,
160 // so we don't need to check again.
161
162 if (IssueErrors)
163 getDriver().Diag(diag::err_drv_unable_to_remove_file)
164 << EC.message();
165 return false;
166 }
167 return true;
168}
169
170bool Compilation::CleanupFileList(const llvm::opt::ArgStringList &Files,
171 bool IssueErrors) const {
172 bool Success = true;
173 for (const auto &File: Files)
174 Success &= CleanupFile(File, IssueErrors);
175 return Success;
176}
177
179 const JobAction *JA,
180 bool IssueErrors) const {
181 bool Success = true;
182 for (const auto &File : Files) {
183 // If specified, only delete the files associated with the JobAction.
184 // Otherwise, delete all files in the map.
185 if (JA && File.first != JA)
186 continue;
187 Success &= CleanupFile(File.second, IssueErrors);
188 }
189 return Success;
190}
191
193 const Command *&FailingCommand,
194 bool LogOnly) const {
195 if ((getDriver().CCPrintOptions ||
196 getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {
197 raw_ostream *OS = &llvm::errs();
198 std::unique_ptr<llvm::raw_fd_ostream> OwnedStream;
199
200 // Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
201 // output stream.
202 if (getDriver().CCPrintOptions &&
203 !getDriver().CCPrintOptionsFilename.empty()) {
204 std::error_code EC;
205 OwnedStream.reset(new llvm::raw_fd_ostream(
206 getDriver().CCPrintOptionsFilename, EC,
207 llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF));
208 if (EC) {
209 getDriver().Diag(diag::err_drv_cc_print_options_failure)
210 << EC.message();
211 FailingCommand = &C;
212 return 1;
213 }
214 OS = OwnedStream.get();
215 }
216
217 if (getDriver().CCPrintOptions)
218 *OS << "[Logging clang options]\n";
219
220 C.Print(*OS, "\n", /*Quote=*/getDriver().CCPrintOptions);
221 }
222
223 if (LogOnly)
224 return 0;
225
226 std::string Error;
227 bool ExecutionFailed;
228 int Res = C.Execute(Redirects, &Error, &ExecutionFailed);
229 if (PostCallback)
230 PostCallback(C, Res);
231 if (!Error.empty()) {
232 assert(Res && "Error string set with 0 result code!");
233 getDriver().Diag(diag::err_drv_command_failure) << Error;
234 }
235
236 if (Res)
237 FailingCommand = &C;
238
239 return ExecutionFailed ? 1 : Res;
240}
241
243
244static bool ActionFailed(const Action *A,
245 const FailingCommandList &FailingCommands) {
246 if (FailingCommands.empty())
247 return false;
248
249 // CUDA/HIP/SYCL can have the same input source code compiled multiple times
250 // so do not compile again if there are already failures. It is OK to abort
251 // the CUDA/HIP/SYCL pipeline on errors.
254 return true;
255
256 for (const auto &CI : FailingCommands)
257 if (A == &(CI.second->getSource()))
258 return true;
259
260 for (const auto *AI : A->inputs())
261 if (ActionFailed(AI, FailingCommands))
262 return true;
263
264 return false;
265}
266
267static bool ActionDependsOn(const Action *A, const Action *Other) {
268 return A == Other || llvm::any_of(A->inputs(), [&](const Action *Input) {
269 return ActionDependsOn(Input, Other);
270 });
271}
272
274 return !Job.InProcess && !Job.PrintInputFilenames &&
275 !Job.getBoundArch().empty() &&
277}
278
283
284static bool HasDistinctBoundArch(const Command &Candidate,
286 BoundArch CandidateArch = Candidate.getBoundArch();
287 return llvm::none_of(Jobs, [&](const Command *Job) {
288 return Job->getBoundArch() == CandidateArch;
289 });
290}
291
292static std::optional<llvm::ThreadPoolStrategy>
293getParallelOffloadJobsStrategy(const ArgList &Args, unsigned NumJobs) {
294 if (NumJobs < 2)
295 return std::nullopt;
296
297 auto OffloadJobs = tools::parseOffloadJobs(Args);
298 if (!OffloadJobs.isValid())
299 return std::nullopt;
300
301 if (OffloadJobs.K == tools::OffloadJobsOpt::Kind::Jobserver)
302 return llvm::jobserver_concurrency();
303
304 if (OffloadJobs.NumThreads < 2)
305 return std::nullopt;
306
307 return llvm::hardware_concurrency(std::min(OffloadJobs.NumThreads, NumJobs));
308}
309
311 int Res = 0;
312 bool ExecutionFailed = false;
313 std::string Error;
314};
315
316// Device-only compiles in one group can be separated by device links.
317static bool
318tryExecuteParallelOffloadJobGroup(const Driver &D, const ArgList &Args,
319 ArrayRef<std::optional<StringRef>> Redirects,
320 const JobList::list_type &JobStorage,
321 size_t StartIndex,
322 llvm::SmallPtrSetImpl<const Command *> &Done,
323 FailingCommandList &FailingCommands) {
324 const Command &Job = *JobStorage[StartIndex];
326 return false;
327
328 // The start job's dependencies precede it in the topologically ordered job
329 // list and have already run, so it is always safe to run here.
330 SmallVector<const Command *, 4> ParallelJobs{&Job};
331 for (size_t I = StartIndex + 1; I < JobStorage.size(); ++I) {
332 const Command &Candidate = *JobStorage[I];
333 if (Done.contains(&Candidate) ||
334 ActionFailed(&Candidate.getSource(), FailingCommands) ||
336 !SameParallelOffloadJobGroup(Job, Candidate) ||
337 !HasDistinctBoundArch(Candidate, ParallelJobs))
338 continue;
339
340 // In this topologically ordered list, only the candidate can depend on
341 // an earlier job, such as preprocessing with -save-temps.
342 auto EarlierJobs = llvm::make_range(JobStorage.begin() + StartIndex,
343 JobStorage.begin() + I);
344 if (!llvm::all_of(EarlierJobs, [&](const auto &Other) {
345 return Done.contains(Other.get()) ||
346 !ActionDependsOn(&Candidate.getSource(), &Other->getSource());
347 }))
348 continue;
349
350 ParallelJobs.push_back(&Candidate);
351 }
352
353 std::optional<llvm::ThreadPoolStrategy> Strategy =
354 getParallelOffloadJobsStrategy(Args, ParallelJobs.size());
355 if (!Strategy)
356 return false;
357
358 SmallVector<ParallelJobResult, 4> Results(ParallelJobs.size());
359 llvm::DefaultThreadPool Pool(*Strategy);
360 for (auto IndexedJob : llvm::enumerate(ParallelJobs)) {
361 size_t Index = IndexedJob.index();
362 const Command *ParallelJob = IndexedJob.value();
363 Pool.async([&, Index, ParallelJob] {
364 Results[Index].Res = ParallelJob->Execute(
365 Redirects, &Results[Index].Error, &Results[Index].ExecutionFailed);
366 });
367 }
368 Pool.wait();
369
370 for (auto [Index, ParallelJob] : llvm::enumerate(ParallelJobs)) {
371 ParallelJobResult &Result = Results[Index];
372 if (!Result.Error.empty()) {
373 assert(Result.Res && "Error string set with 0 result code!");
374 D.Diag(diag::err_drv_command_failure) << Result.Error;
375 }
376
377 if (Result.Res) {
378 FailingCommands.push_back(
379 std::make_pair(Result.ExecutionFailed ? 1 : Result.Res, ParallelJob));
380 }
381 }
382
383 for (const Command *ParallelJob : ParallelJobs)
384 Done.insert(ParallelJob);
385 return true;
386}
387
389 FailingCommandList &FailingCommands,
390 bool LogOnly) const {
391 // According to UNIX standard, driver need to continue compiling all the
392 // inputs on the command line even one of them failed.
393 // In all but CLMode, execute all the jobs unless the necessary inputs for the
394 // job is missing due to previous failures.
395 bool CanRunJobsInParallel =
396 !LogOnly && !getDriver().CCPrintOptions &&
398 !getDriver().IsCLMode() && !getArgs().hasArg(options::OPT_v) &&
399 Redirects.empty() && !PostCallback;
400
401 // Jobs run as part of a parallel offload group. Group members are not
402 // necessarily adjacent, so track them and skip them when the loop reaches
403 // them.
405 const auto &JobStorage = Jobs.getJobs();
406 for (size_t I = 0; I < JobStorage.size(); ++I) {
407 const auto &Job = *JobStorage[I];
408 if (Done.contains(&Job))
409 continue;
410 if (ActionFailed(&Job.getSource(), FailingCommands))
411 continue;
412
413 if (CanRunJobsInParallel &&
415 JobStorage, I, Done, FailingCommands))
416 continue;
417
418 const Command *FailingCommand = nullptr;
419 if (int Res = ExecuteCommand(Job, FailingCommand, LogOnly)) {
420 FailingCommands.push_back(std::make_pair(Res, FailingCommand));
421 // Bail as soon as one command fails in cl driver mode.
422 if (TheDriver.IsCLMode())
423 return;
424 }
425 }
426}
427
429 ForDiagnostics = true;
430
431 // Free actions and jobs.
432 Actions.clear();
433 AllActions.clear();
434 Jobs.clear();
435
436 // Remove temporary files.
437 if (!TheDriver.isSaveTempsEnabled() && !ForceKeepTempFiles)
438 CleanupFileList(TempFiles);
439
440 // Clear temporary/results file lists.
441 TempFiles.clear();
442 ResultFiles.clear();
443 FailureResultFiles.clear();
444
445 // Remove any user specified output. Claim any unclaimed arguments, so as
446 // to avoid emitting warnings about unused args.
447 OptSpecifier OutputOpts[] = {
448 options::OPT_o, options::OPT_MD, options::OPT_MMD, options::OPT_M,
449 options::OPT_MM, options::OPT_MF, options::OPT_MG, options::OPT_MJ,
450 options::OPT_MQ, options::OPT_MT, options::OPT_MV};
451 for (const auto &Opt : OutputOpts) {
452 if (TranslatedArgs->hasArg(Opt))
453 TranslatedArgs->eraseArg(Opt);
454 }
455 TranslatedArgs->ClaimAllArgs();
456
457 // Force re-creation of the toolchain Args, otherwise our modifications just
458 // above will have no effect.
459 for (auto Arg : TCArgs)
460 if (Arg.second != TranslatedArgs)
461 delete Arg.second;
462 TCArgs.clear();
463
464 // Redirect stdout/stderr to /dev/null.
465 Redirects = {std::nullopt, {""}, {""}};
466
467 // Temporary files added by diagnostics should be kept.
468 ForceKeepTempFiles = true;
469}
470
471StringRef Compilation::getSysRoot() const {
472 return getDriver().SysRoot;
473}
474
475void Compilation::Redirect(ArrayRef<std::optional<StringRef>> Redirects) {
476 this->Redirects = Redirects;
477}
static bool ActionFailed(const Action *A, const FailingCommandList &FailingCommands)
static bool tryExecuteParallelOffloadJobGroup(const Driver &D, const ArgList &Args, ArrayRef< std::optional< StringRef > > Redirects, const JobList::list_type &JobStorage, size_t StartIndex, llvm::SmallPtrSetImpl< const Command * > &Done, FailingCommandList &FailingCommands)
static bool HasDistinctBoundArch(const Command &Candidate, ArrayRef< const Command * > Jobs)
static bool ActionDependsOn(const Action *A, const Action *Other)
static bool SameParallelOffloadJobGroup(const Command &A, const Command &B)
SmallVectorImpl< std::pair< int, const Command * > > FailingCommandList
static bool CanRunInParallelOffloadJobGroup(const Command &Job)
static std::optional< llvm::ThreadPoolStrategy > getParallelOffloadJobsStrategy(const ArgList &Args, unsigned NumJobs)
Result
Implement __builtin_bit_cast and related operations.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Action - Represent an abstract compilation step to perform.
Definition Action.h:48
input_range inputs()
Definition Action.h:162
bool isOffloading(OffloadKind OKind) const
Definition Action.h:229
static llvm::opt::DerivedArgList * translateArgs(const llvm::opt::DerivedArgList &Args, const llvm::Triple &HostTriple, const llvm::opt::DerivedArgList &Owner)
Translate a filtered list that may contain new clang-cl options, replacing earlier /O expansions.
Command - An executable path/name and argument vector to execute.
Definition Job.h:107
const Action & getSource() const
getSource - Return the Action which caused the creation of this job.
Definition Job.h:196
StringRef getOffloadDeviceParallelJobGroup() const
Definition Job.h:205
bool PrintInputFilenames
Whether to print the input filenames when executing.
Definition Job.h:175
bool InProcess
Whether the command will be executed in this process or not.
Definition Job.h:178
BoundArch getBoundArch() const
Return the bound architecture for this command, if any.
Definition Job.h:202
virtual int Execute(ArrayRef< std::optional< StringRef > > Redirects, std::string *ErrMsg, bool *ExecutionFailed) const
Definition Job.cpp:325
int ExecuteCommand(const Command &C, const Command *&FailingCommand, bool LogOnly=false) const
ExecuteCommand - Execute an actual command.
bool CleanupFileMap(const ArgStringMap &Files, const JobAction *JA, bool IssueErrors=false) const
CleanupFileMap - Remove the files in the given map.
bool CleanupFile(const char *File, bool IssueErrors=false) const
CleanupFile - Delete a given file.
Compilation(const Driver &D, const ToolChain &DefaultToolChain, llvm::opt::InputArgList *Args, llvm::opt::DerivedArgList *TranslatedArgs, bool ContainsError)
bool CleanupFileList(const llvm::opt::ArgStringList &Files, bool IssueErrors=false) const
CleanupFileList - Remove the files in the given list.
const llvm::opt::DerivedArgList & getArgsForToolChain(const ToolChain *TC, BoundArch BA, Action::OffloadKind DeviceOffloadKind)
getArgsForToolChain - Return the derived argument list for the tool chain TC (or the default tool cha...
StringRef getSysRoot() const
Returns the sysroot path.
void Redirect(ArrayRef< std::optional< StringRef > > Redirects)
Redirect - Redirect output of this compilation.
void initCompilationForDiagnostics()
initCompilationForDiagnostics - Remove stale state and suppress output so compilation can be reexecut...
ArrayRef< StringRef > getIGCADevices(const ToolChain *TC, StringRef Target) const
const llvm::opt::DerivedArgList & getArgs() const
void ExecuteJobs(const JobList &Jobs, SmallVectorImpl< std::pair< int, const Command * > > &FailingCommands, bool LogOnly=false) const
ExecuteJob - Execute a single job.
const ToolChain * getSingleOffloadToolChain() const
Return an offload toolchain of the provided kind.
const Driver & getDriver() const
void addIGCADevice(const ToolChain *TC, StringRef Target, StringRef Device)
Add the Intel GPU Device to the GPUs of the IGCA target Target for the device toolchain TC.
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:93
std::string SysRoot
sysroot, if present
Definition Driver.h:193
unsigned CCPrintProcessStats
Set CC_PRINT_PROC_STAT mode, which causes the driver to dump performance report to CC_PRINT_PROC_STAT...
Definition Driver.h:276
bool IsCLMode() const
Whether the driver should follow cl.exe like behavior.
Definition Driver.h:229
unsigned CCGenDiagnostics
Whether the driver is generating diagnostics for debugging purposes.
Definition Driver.h:271
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:157
unsigned CCPrintOptions
Set CC_PRINT_OPTIONS mode, which is like -v but logs the commands to CCPrintOptionsFilename or to std...
Definition Driver.h:245
JobList - A sequence of jobs to perform.
Definition Job.h:279
SmallVector< std::unique_ptr< Command >, 4 > list_type
Definition Job.h:281
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:92
virtual llvm::opt::DerivedArgList * TranslateArgs(const llvm::opt::DerivedArgList &Args, BoundArch BA, Action::OffloadKind DeviceOffloadKind) const
TranslateArgs - Create a new derived argument list for any argument translations this ToolChain may w...
Definition ToolChain.h:394
const llvm::Triple & getTriple() const
Definition ToolChain.h:281
virtual llvm::opt::DerivedArgList * TranslateOpenMPTargetArgs(const llvm::opt::DerivedArgList &Args, const llvm::Triple &HostTriple, SmallVectorImpl< llvm::opt::Arg * > &AllocatedArgs) const
TranslateOpenMPTargetArgs - Create a new derived argument list for that contains the OpenMP target sp...
virtual void TranslateXarchArgs(const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A, llvm::opt::DerivedArgList *DAL, SmallVectorImpl< llvm::opt::Arg * > *AllocatedArgs=nullptr) const
Append the argument following A to DAL assuming A is an Xarch argument.
OffloadJobsOpt parseOffloadJobs(const llvm::opt::ArgList &Args)
llvm::DenseMap< const JobAction *, const char * > ArgStringMap
ArgStringMap - Type used to map a JobAction to its result file.
Definition Util.h:22
Top level wrappers for InstallAPI frontend operations.
@ Success
Annotation was successful.
Definition Parser.h:65
Represents a bound architecture for offload / multiple architecture compilation.
bool empty() const