Path: blob/main/contrib/llvm-project/clang/lib/Driver/Compilation.cpp
35233 views
//===- Compilation.cpp - Compilation Task Implementation ------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "clang/Driver/Compilation.h"9#include "clang/Basic/LLVM.h"10#include "clang/Driver/Action.h"11#include "clang/Driver/Driver.h"12#include "clang/Driver/DriverDiagnostic.h"13#include "clang/Driver/Job.h"14#include "clang/Driver/Options.h"15#include "clang/Driver/ToolChain.h"16#include "clang/Driver/Util.h"17#include "llvm/ADT/STLExtras.h"18#include "llvm/ADT/SmallVector.h"19#include "llvm/Option/ArgList.h"20#include "llvm/Option/OptSpecifier.h"21#include "llvm/Option/Option.h"22#include "llvm/Support/FileSystem.h"23#include "llvm/Support/raw_ostream.h"24#include "llvm/TargetParser/Triple.h"25#include <cassert>26#include <string>27#include <system_error>28#include <utility>2930using namespace clang;31using namespace driver;32using namespace llvm::opt;3334Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,35InputArgList *_Args, DerivedArgList *_TranslatedArgs,36bool ContainsError)37: TheDriver(D), DefaultToolChain(_DefaultToolChain), Args(_Args),38TranslatedArgs(_TranslatedArgs), ContainsError(ContainsError) {39// The offloading host toolchain is the default toolchain.40OrderedOffloadingToolchains.insert(41std::make_pair(Action::OFK_Host, &DefaultToolChain));42}4344Compilation::~Compilation() {45// Remove temporary files. This must be done before arguments are freed, as46// the file names might be derived from the input arguments.47if (!TheDriver.isSaveTempsEnabled() && !ForceKeepTempFiles)48CleanupFileList(TempFiles);4950delete TranslatedArgs;51delete Args;5253// Free any derived arg lists.54for (auto Arg : TCArgs)55if (Arg.second != TranslatedArgs)56delete Arg.second;57}5859const DerivedArgList &60Compilation::getArgsForToolChain(const ToolChain *TC, StringRef BoundArch,61Action::OffloadKind DeviceOffloadKind) {62if (!TC)63TC = &DefaultToolChain;6465DerivedArgList *&Entry = TCArgs[{TC, BoundArch, DeviceOffloadKind}];66if (!Entry) {67SmallVector<Arg *, 4> AllocatedArgs;68DerivedArgList *OpenMPArgs = nullptr;69// Translate OpenMP toolchain arguments provided via the -Xopenmp-target flags.70if (DeviceOffloadKind == Action::OFK_OpenMP) {71const ToolChain *HostTC = getSingleOffloadToolChain<Action::OFK_Host>();72bool SameTripleAsHost = (TC->getTriple() == HostTC->getTriple());73OpenMPArgs = TC->TranslateOpenMPTargetArgs(74*TranslatedArgs, SameTripleAsHost, AllocatedArgs);75}7677DerivedArgList *NewDAL = nullptr;78if (!OpenMPArgs) {79NewDAL = TC->TranslateXarchArgs(*TranslatedArgs, BoundArch,80DeviceOffloadKind, &AllocatedArgs);81} else {82NewDAL = TC->TranslateXarchArgs(*OpenMPArgs, BoundArch, DeviceOffloadKind,83&AllocatedArgs);84if (!NewDAL)85NewDAL = OpenMPArgs;86else87delete OpenMPArgs;88}8990if (!NewDAL) {91Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch, DeviceOffloadKind);92if (!Entry)93Entry = TranslatedArgs;94} else {95Entry = TC->TranslateArgs(*NewDAL, BoundArch, DeviceOffloadKind);96if (!Entry)97Entry = NewDAL;98else99delete NewDAL;100}101102// Add allocated arguments to the final DAL.103for (auto *ArgPtr : AllocatedArgs)104Entry->AddSynthesizedArg(ArgPtr);105}106107return *Entry;108}109110bool Compilation::CleanupFile(const char *File, bool IssueErrors) const {111// FIXME: Why are we trying to remove files that we have not created? For112// example we should only try to remove a temporary assembly file if113// "clang -cc1" succeed in writing it. Was this a workaround for when114// clang was writing directly to a .s file and sometimes leaving it behind115// during a failure?116117// FIXME: If this is necessary, we can still try to split118// llvm::sys::fs::remove into a removeFile and a removeDir and avoid the119// duplicated stat from is_regular_file.120121// Don't try to remove files which we don't have write access to (but may be122// able to remove), or non-regular files. Underlying tools may have123// intentionally not overwritten them.124if (!llvm::sys::fs::can_write(File) || !llvm::sys::fs::is_regular_file(File))125return true;126127if (std::error_code EC = llvm::sys::fs::remove(File)) {128// Failure is only failure if the file exists and is "regular". We checked129// for it being regular before, and llvm::sys::fs::remove ignores ENOENT,130// so we don't need to check again.131132if (IssueErrors)133getDriver().Diag(diag::err_drv_unable_to_remove_file)134<< EC.message();135return false;136}137return true;138}139140bool Compilation::CleanupFileList(const llvm::opt::ArgStringList &Files,141bool IssueErrors) const {142bool Success = true;143for (const auto &File: Files)144Success &= CleanupFile(File, IssueErrors);145return Success;146}147148bool Compilation::CleanupFileMap(const ArgStringMap &Files,149const JobAction *JA,150bool IssueErrors) const {151bool Success = true;152for (const auto &File : Files) {153// If specified, only delete the files associated with the JobAction.154// Otherwise, delete all files in the map.155if (JA && File.first != JA)156continue;157Success &= CleanupFile(File.second, IssueErrors);158}159return Success;160}161162int Compilation::ExecuteCommand(const Command &C,163const Command *&FailingCommand,164bool LogOnly) const {165if ((getDriver().CCPrintOptions ||166getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {167raw_ostream *OS = &llvm::errs();168std::unique_ptr<llvm::raw_fd_ostream> OwnedStream;169170// Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the171// output stream.172if (getDriver().CCPrintOptions &&173!getDriver().CCPrintOptionsFilename.empty()) {174std::error_code EC;175OwnedStream.reset(new llvm::raw_fd_ostream(176getDriver().CCPrintOptionsFilename, EC,177llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF));178if (EC) {179getDriver().Diag(diag::err_drv_cc_print_options_failure)180<< EC.message();181FailingCommand = &C;182return 1;183}184OS = OwnedStream.get();185}186187if (getDriver().CCPrintOptions)188*OS << "[Logging clang options]\n";189190C.Print(*OS, "\n", /*Quote=*/getDriver().CCPrintOptions);191}192193if (LogOnly)194return 0;195196std::string Error;197bool ExecutionFailed;198int Res = C.Execute(Redirects, &Error, &ExecutionFailed);199if (PostCallback)200PostCallback(C, Res);201if (!Error.empty()) {202assert(Res && "Error string set with 0 result code!");203getDriver().Diag(diag::err_drv_command_failure) << Error;204}205206if (Res)207FailingCommand = &C;208209return ExecutionFailed ? 1 : Res;210}211212using FailingCommandList = SmallVectorImpl<std::pair<int, const Command *>>;213214static bool ActionFailed(const Action *A,215const FailingCommandList &FailingCommands) {216if (FailingCommands.empty())217return false;218219// CUDA/HIP can have the same input source code compiled multiple times so do220// not compiled again if there are already failures. It is OK to abort the221// CUDA pipeline on errors.222if (A->isOffloading(Action::OFK_Cuda) || A->isOffloading(Action::OFK_HIP))223return true;224225for (const auto &CI : FailingCommands)226if (A == &(CI.second->getSource()))227return true;228229for (const auto *AI : A->inputs())230if (ActionFailed(AI, FailingCommands))231return true;232233return false;234}235236static bool InputsOk(const Command &C,237const FailingCommandList &FailingCommands) {238return !ActionFailed(&C.getSource(), FailingCommands);239}240241void Compilation::ExecuteJobs(const JobList &Jobs,242FailingCommandList &FailingCommands,243bool LogOnly) const {244// According to UNIX standard, driver need to continue compiling all the245// inputs on the command line even one of them failed.246// In all but CLMode, execute all the jobs unless the necessary inputs for the247// job is missing due to previous failures.248for (const auto &Job : Jobs) {249if (!InputsOk(Job, FailingCommands))250continue;251const Command *FailingCommand = nullptr;252if (int Res = ExecuteCommand(Job, FailingCommand, LogOnly)) {253FailingCommands.push_back(std::make_pair(Res, FailingCommand));254// Bail as soon as one command fails in cl driver mode.255if (TheDriver.IsCLMode())256return;257}258}259}260261void Compilation::initCompilationForDiagnostics() {262ForDiagnostics = true;263264// Free actions and jobs.265Actions.clear();266AllActions.clear();267Jobs.clear();268269// Remove temporary files.270if (!TheDriver.isSaveTempsEnabled() && !ForceKeepTempFiles)271CleanupFileList(TempFiles);272273// Clear temporary/results file lists.274TempFiles.clear();275ResultFiles.clear();276FailureResultFiles.clear();277278// Remove any user specified output. Claim any unclaimed arguments, so as279// to avoid emitting warnings about unused args.280OptSpecifier OutputOpts[] = {281options::OPT_o, options::OPT_MD, options::OPT_MMD, options::OPT_M,282options::OPT_MM, options::OPT_MF, options::OPT_MG, options::OPT_MJ,283options::OPT_MQ, options::OPT_MT, options::OPT_MV};284for (const auto &Opt : OutputOpts) {285if (TranslatedArgs->hasArg(Opt))286TranslatedArgs->eraseArg(Opt);287}288TranslatedArgs->ClaimAllArgs();289290// Force re-creation of the toolchain Args, otherwise our modifications just291// above will have no effect.292for (auto Arg : TCArgs)293if (Arg.second != TranslatedArgs)294delete Arg.second;295TCArgs.clear();296297// Redirect stdout/stderr to /dev/null.298Redirects = {std::nullopt, {""}, {""}};299300// Temporary files added by diagnostics should be kept.301ForceKeepTempFiles = true;302}303304StringRef Compilation::getSysRoot() const {305return getDriver().SysRoot;306}307308void Compilation::Redirect(ArrayRef<std::optional<StringRef>> Redirects) {309this->Redirects = Redirects;310}311312313