15e4511cfSEugene Zelenko //===- Compilation.cpp - Compilation Task Implementation ------------------===//
2544ecd14SDaniel Dunbar //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6544ecd14SDaniel Dunbar //
7544ecd14SDaniel Dunbar //===----------------------------------------------------------------------===//
8544ecd14SDaniel Dunbar 
9544ecd14SDaniel Dunbar #include "clang/Driver/Compilation.h"
105e4511cfSEugene Zelenko #include "clang/Basic/LLVM.h"
11f0eddb85SDaniel Dunbar #include "clang/Driver/Action.h"
126c17bfd9SDaniel Dunbar #include "clang/Driver/Driver.h"
136c17bfd9SDaniel Dunbar #include "clang/Driver/DriverDiagnostic.h"
145e4511cfSEugene Zelenko #include "clang/Driver/Job.h"
15da13faf9SDaniel Dunbar #include "clang/Driver/Options.h"
163ce436d2SDaniel Dunbar #include "clang/Driver/ToolChain.h"
175e4511cfSEugene Zelenko #include "clang/Driver/Util.h"
185e4511cfSEugene Zelenko #include "llvm/ADT/None.h"
19be10f985SChad Rosier #include "llvm/ADT/STLExtras.h"
205e4511cfSEugene Zelenko #include "llvm/ADT/SmallVector.h"
215e4511cfSEugene Zelenko #include "llvm/ADT/Triple.h"
22898229abSReid Kleckner #include "llvm/Option/ArgList.h"
235e4511cfSEugene Zelenko #include "llvm/Option/OptSpecifier.h"
245e4511cfSEugene Zelenko #include "llvm/Option/Option.h"
25fc92e845SRafael Espindola #include "llvm/Support/FileSystem.h"
263a02247dSChandler Carruth #include "llvm/Support/raw_ostream.h"
275e4511cfSEugene Zelenko #include <cassert>
285e4511cfSEugene Zelenko #include <string>
295e4511cfSEugene Zelenko #include <system_error>
305e4511cfSEugene Zelenko #include <utility>
3124fc69e5SFrancois Pichet 
3224fc69e5SFrancois Pichet using namespace clang;
335e4511cfSEugene Zelenko using namespace driver;
34898229abSReid Kleckner using namespace llvm::opt;
35544ecd14SDaniel Dunbar 
Compilation(const Driver & D,const ToolChain & _DefaultToolChain,InputArgList * _Args,DerivedArgList * _TranslatedArgs,bool ContainsError)36775d4060SDaniel Dunbar Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
3743c0f486SBenjamin Kramer                          InputArgList *_Args, DerivedArgList *_TranslatedArgs,
3843c0f486SBenjamin Kramer                          bool ContainsError)
395e4511cfSEugene Zelenko     : TheDriver(D), DefaultToolChain(_DefaultToolChain), Args(_Args),
405e4511cfSEugene Zelenko       TranslatedArgs(_TranslatedArgs), ContainsError(ContainsError) {
41c1ffba50SSamuel Antao   // The offloading host toolchain is the default toolchain.
42c1ffba50SSamuel Antao   OrderedOffloadingToolchains.insert(
43c1ffba50SSamuel Antao       std::make_pair(Action::OFK_Host, &DefaultToolChain));
44c1ffba50SSamuel Antao }
45544ecd14SDaniel Dunbar 
~Compilation()46544ecd14SDaniel Dunbar Compilation::~Compilation() {
473891885cSDavid Stenberg   // Remove temporary files. This must be done before arguments are freed, as
483891885cSDavid Stenberg   // the file names might be derived from the input arguments.
493891885cSDavid Stenberg   if (!TheDriver.isSaveTempsEnabled() && !ForceKeepTempFiles)
503891885cSDavid Stenberg     CleanupFileList(TempFiles);
513891885cSDavid Stenberg 
52775d4060SDaniel Dunbar   delete TranslatedArgs;
533ce436d2SDaniel Dunbar   delete Args;
543ce436d2SDaniel Dunbar 
553ce436d2SDaniel Dunbar   // Free any derived arg lists.
56c50b1a26SMehdi Amini   for (auto Arg : TCArgs)
57c50b1a26SMehdi Amini     if (Arg.second != TranslatedArgs)
58c50b1a26SMehdi Amini       delete Arg.second;
593ce436d2SDaniel Dunbar }
603ce436d2SDaniel Dunbar 
6131fef989SSamuel Antao const DerivedArgList &
getArgsForToolChain(const ToolChain * TC,StringRef BoundArch,Action::OffloadKind DeviceOffloadKind)6231fef989SSamuel Antao Compilation::getArgsForToolChain(const ToolChain *TC, StringRef BoundArch,
6331fef989SSamuel Antao                                  Action::OffloadKind DeviceOffloadKind) {
643ce436d2SDaniel Dunbar   if (!TC)
653ce436d2SDaniel Dunbar     TC = &DefaultToolChain;
663ce436d2SDaniel Dunbar 
6731fef989SSamuel Antao   DerivedArgList *&Entry = TCArgs[{TC, BoundArch, DeviceOffloadKind}];
68775d4060SDaniel Dunbar   if (!Entry) {
6985f19958SJonas Hahnfeld     SmallVector<Arg *, 4> AllocatedArgs;
70bbf56fb6SJonas Hahnfeld     DerivedArgList *OpenMPArgs = nullptr;
7147e0cf37SGheorghe-Teodor Bercea     // Translate OpenMP toolchain arguments provided via the -Xopenmp-target flags.
72bbf56fb6SJonas Hahnfeld     if (DeviceOffloadKind == Action::OFK_OpenMP) {
73bbf56fb6SJonas Hahnfeld       const ToolChain *HostTC = getSingleOffloadToolChain<Action::OFK_Host>();
74bbf56fb6SJonas Hahnfeld       bool SameTripleAsHost = (TC->getTriple() == HostTC->getTriple());
75bbf56fb6SJonas Hahnfeld       OpenMPArgs = TC->TranslateOpenMPTargetArgs(
76bbf56fb6SJonas Hahnfeld           *TranslatedArgs, SameTripleAsHost, AllocatedArgs);
77bbf56fb6SJonas Hahnfeld     }
78bbf56fb6SJonas Hahnfeld 
792ae25647SYaxun (Sam) Liu     DerivedArgList *NewDAL = nullptr;
80bcfdd786SGheorghe-Teodor Bercea     if (!OpenMPArgs) {
812ae25647SYaxun (Sam) Liu       NewDAL = TC->TranslateXarchArgs(*TranslatedArgs, BoundArch,
822ae25647SYaxun (Sam) Liu                                       DeviceOffloadKind, &AllocatedArgs);
832ae25647SYaxun (Sam) Liu     } else {
842ae25647SYaxun (Sam) Liu       NewDAL = TC->TranslateXarchArgs(*OpenMPArgs, BoundArch, DeviceOffloadKind,
852ae25647SYaxun (Sam) Liu                                       &AllocatedArgs);
862ae25647SYaxun (Sam) Liu       if (!NewDAL)
872ae25647SYaxun (Sam) Liu         NewDAL = OpenMPArgs;
882ae25647SYaxun (Sam) Liu       else
892ae25647SYaxun (Sam) Liu         delete OpenMPArgs;
902ae25647SYaxun (Sam) Liu     }
912ae25647SYaxun (Sam) Liu 
922ae25647SYaxun (Sam) Liu     if (!NewDAL) {
93bcfdd786SGheorghe-Teodor Bercea       Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch, DeviceOffloadKind);
94aabaac47SDaniel Dunbar       if (!Entry)
95775d4060SDaniel Dunbar         Entry = TranslatedArgs;
96102c333dSJonas Hahnfeld     } else {
972ae25647SYaxun (Sam) Liu       Entry = TC->TranslateArgs(*NewDAL, BoundArch, DeviceOffloadKind);
98102c333dSJonas Hahnfeld       if (!Entry)
992ae25647SYaxun (Sam) Liu         Entry = NewDAL;
100102c333dSJonas Hahnfeld       else
1012ae25647SYaxun (Sam) Liu         delete NewDAL;
102102c333dSJonas Hahnfeld     }
10385f19958SJonas Hahnfeld 
10485f19958SJonas Hahnfeld     // Add allocated arguments to the final DAL.
1055e4511cfSEugene Zelenko     for (auto ArgPtr : AllocatedArgs)
10685f19958SJonas Hahnfeld       Entry->AddSynthesizedArg(ArgPtr);
10785f19958SJonas Hahnfeld   }
1083ce436d2SDaniel Dunbar 
109aabaac47SDaniel Dunbar   return *Entry;
110544ecd14SDaniel Dunbar }
111544ecd14SDaniel Dunbar 
CleanupFile(const char * File,bool IssueErrors) const112633dcdc5SChad Rosier bool Compilation::CleanupFile(const char *File, bool IssueErrors) const {
11303bc6826SRafael Espindola   // FIXME: Why are we trying to remove files that we have not created? For
11403bc6826SRafael Espindola   // example we should only try to remove a temporary assembly file if
11503bc6826SRafael Espindola   // "clang -cc1" succeed in writing it. Was this a workaround for when
11603bc6826SRafael Espindola   // clang was writing directly to a .s file and sometimes leaving it behind
11703bc6826SRafael Espindola   // during a failure?
11803bc6826SRafael Espindola 
11903bc6826SRafael Espindola   // FIXME: If this is necessary, we can still try to split
12003bc6826SRafael Espindola   // llvm::sys::fs::remove into a removeFile and a removeDir and avoid the
12103bc6826SRafael Espindola   // duplicated stat from is_regular_file.
1226c17bfd9SDaniel Dunbar 
123462e7ed4SDaniel Dunbar   // Don't try to remove files which we don't have write access to (but may be
124582b2ab0SDaniel Dunbar   // able to remove), or non-regular files. Underlying tools may have
125582b2ab0SDaniel Dunbar   // intentionally not overwritten them.
12603bc6826SRafael Espindola   if (!llvm::sys::fs::can_write(File) || !llvm::sys::fs::is_regular_file(File))
127633dcdc5SChad Rosier     return true;
128462e7ed4SDaniel Dunbar 
129c080917eSRafael Espindola   if (std::error_code EC = llvm::sys::fs::remove(File)) {
13003bc6826SRafael Espindola     // Failure is only failure if the file exists and is "regular". We checked
13103bc6826SRafael Espindola     // for it being regular before, and llvm::sys::fs::remove ignores ENOENT,
13203bc6826SRafael Espindola     // so we don't need to check again.
1336c17bfd9SDaniel Dunbar 
1346c17bfd9SDaniel Dunbar     if (IssueErrors)
1355e4511cfSEugene Zelenko       getDriver().Diag(diag::err_drv_unable_to_remove_file)
13603bc6826SRafael Espindola         << EC.message();
137633dcdc5SChad Rosier     return false;
1386c17bfd9SDaniel Dunbar   }
139633dcdc5SChad Rosier   return true;
1406c17bfd9SDaniel Dunbar }
1416c17bfd9SDaniel Dunbar 
CleanupFileList(const llvm::opt::ArgStringList & Files,bool IssueErrors) const1420a3bb819SSimon Pilgrim bool Compilation::CleanupFileList(const llvm::opt::ArgStringList &Files,
143633dcdc5SChad Rosier                                   bool IssueErrors) const {
144633dcdc5SChad Rosier   bool Success = true;
1455e4511cfSEugene Zelenko   for (const auto &File: Files)
1465e4511cfSEugene Zelenko     Success &= CleanupFile(File, IssueErrors);
147633dcdc5SChad Rosier   return Success;
148633dcdc5SChad Rosier }
149633dcdc5SChad Rosier 
CleanupFileMap(const ArgStringMap & Files,const JobAction * JA,bool IssueErrors) const150633dcdc5SChad Rosier bool Compilation::CleanupFileMap(const ArgStringMap &Files,
151633dcdc5SChad Rosier                                  const JobAction *JA,
152633dcdc5SChad Rosier                                  bool IssueErrors) const {
153633dcdc5SChad Rosier   bool Success = true;
1545e4511cfSEugene Zelenko   for (const auto &File : Files) {
155633dcdc5SChad Rosier     // If specified, only delete the files associated with the JobAction.
156633dcdc5SChad Rosier     // Otherwise, delete all files in the map.
1575e4511cfSEugene Zelenko     if (JA && File.first != JA)
158633dcdc5SChad Rosier       continue;
1595e4511cfSEugene Zelenko     Success &= CleanupFile(File.second, IssueErrors);
160633dcdc5SChad Rosier   }
1616c17bfd9SDaniel Dunbar   return Success;
1626c17bfd9SDaniel Dunbar }
1636c17bfd9SDaniel Dunbar 
ExecuteCommand(const Command & C,const Command * & FailingCommand,bool LogOnly) const164aa246cafSDaniel Dunbar int Compilation::ExecuteCommand(const Command &C,
165*c12577c6SJan Svoboda                                 const Command *&FailingCommand,
166*c12577c6SJan Svoboda                                 bool LogOnly) const {
1678c424545SRafael Espindola   if ((getDriver().CCPrintOptions ||
168be10f985SChad Rosier        getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {
1690e62c1ccSChris Lattner     raw_ostream *OS = &llvm::errs();
1700e5f9157SNico Weber     std::unique_ptr<llvm::raw_fd_ostream> OwnedStream;
1716a8efa8aSDaniel Dunbar 
1726a8efa8aSDaniel Dunbar     // Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
1736a8efa8aSDaniel Dunbar     // output stream.
1747e0cc45cSSean Perry     if (getDriver().CCPrintOptions &&
1757e0cc45cSSean Perry         !getDriver().CCPrintOptionsFilename.empty()) {
176dae941a6SRafael Espindola       std::error_code EC;
1770e5f9157SNico Weber       OwnedStream.reset(new llvm::raw_fd_ostream(
178b8debabbSKazu Hirata           getDriver().CCPrintOptionsFilename, EC,
17982b3e28eSAbhina Sreeskantharajan           llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF));
180dae941a6SRafael Espindola       if (EC) {
1815e4511cfSEugene Zelenko         getDriver().Diag(diag::err_drv_cc_print_options_failure)
182dae941a6SRafael Espindola             << EC.message();
1836a8efa8aSDaniel Dunbar         FailingCommand = &C;
1846a8efa8aSDaniel Dunbar         return 1;
1856a8efa8aSDaniel Dunbar       }
1860e5f9157SNico Weber       OS = OwnedStream.get();
1876a8efa8aSDaniel Dunbar     }
1886a8efa8aSDaniel Dunbar 
1896a8efa8aSDaniel Dunbar     if (getDriver().CCPrintOptions)
190133a7e63SAlexandre Ganea       *OS << "[Logging clang options]\n";
1916a8efa8aSDaniel Dunbar 
192b212b34fSHans Wennborg     C.Print(*OS, "\n", /*Quote=*/getDriver().CCPrintOptions);
1936a8efa8aSDaniel Dunbar   }
19464316c49SDaniel Dunbar 
195*c12577c6SJan Svoboda   if (LogOnly)
196*c12577c6SJan Svoboda     return 0;
197*c12577c6SJan Svoboda 
19864316c49SDaniel Dunbar   std::string Error;
199d1475775SChad Rosier   bool ExecutionFailed;
200e8677ef5SHans Wennborg   int Res = C.Execute(Redirects, &Error, &ExecutionFailed);
20120b4f4f7SSerge Pavlov   if (PostCallback)
20220b4f4f7SSerge Pavlov     PostCallback(C, Res);
20364316c49SDaniel Dunbar   if (!Error.empty()) {
20464316c49SDaniel Dunbar     assert(Res && "Error string set with 0 result code!");
2055e4511cfSEugene Zelenko     getDriver().Diag(diag::err_drv_command_failure) << Error;
20664316c49SDaniel Dunbar   }
20764316c49SDaniel Dunbar 
208aa246cafSDaniel Dunbar   if (Res)
209aa246cafSDaniel Dunbar     FailingCommand = &C;
210aa246cafSDaniel Dunbar 
211d1475775SChad Rosier   return ExecutionFailed ? 1 : Res;
2121da82ae5SDaniel Dunbar }
2131da82ae5SDaniel Dunbar 
2149278019eSSteven Wu using FailingCommandList = SmallVectorImpl<std::pair<int, const Command *>>;
2159278019eSSteven Wu 
ActionFailed(const Action * A,const FailingCommandList & FailingCommands)2169278019eSSteven Wu static bool ActionFailed(const Action *A,
2179278019eSSteven Wu                          const FailingCommandList &FailingCommands) {
2189278019eSSteven Wu   if (FailingCommands.empty())
2199278019eSSteven Wu     return false;
2209278019eSSteven Wu 
221398612b4SYaxun Liu   // CUDA/HIP can have the same input source code compiled multiple times so do
222398612b4SYaxun Liu   // not compiled again if there are already failures. It is OK to abort the
223398612b4SYaxun Liu   // CUDA pipeline on errors.
224398612b4SYaxun Liu   if (A->isOffloading(Action::OFK_Cuda) || A->isOffloading(Action::OFK_HIP))
2259278019eSSteven Wu     return true;
2269278019eSSteven Wu 
2279278019eSSteven Wu   for (const auto &CI : FailingCommands)
2289278019eSSteven Wu     if (A == &(CI.second->getSource()))
2299278019eSSteven Wu       return true;
2309278019eSSteven Wu 
2315e4511cfSEugene Zelenko   for (const auto *AI : A->inputs())
2329278019eSSteven Wu     if (ActionFailed(AI, FailingCommands))
2339278019eSSteven Wu       return true;
2349278019eSSteven Wu 
2359278019eSSteven Wu   return false;
2369278019eSSteven Wu }
2379278019eSSteven Wu 
InputsOk(const Command & C,const FailingCommandList & FailingCommands)2389278019eSSteven Wu static bool InputsOk(const Command &C,
2399278019eSSteven Wu                      const FailingCommandList &FailingCommands) {
2409278019eSSteven Wu   return !ActionFailed(&C.getSource(), FailingCommands);
2419278019eSSteven Wu }
2429278019eSSteven Wu 
ExecuteJobs(const JobList & Jobs,FailingCommandList & FailingCommands,bool LogOnly) const2439278019eSSteven Wu void Compilation::ExecuteJobs(const JobList &Jobs,
244*c12577c6SJan Svoboda                               FailingCommandList &FailingCommands,
245*c12577c6SJan Svoboda                               bool LogOnly) const {
2469278019eSSteven Wu   // According to UNIX standard, driver need to continue compiling all the
2479278019eSSteven Wu   // inputs on the command line even one of them failed.
2489278019eSSteven Wu   // In all but CLMode, execute all the jobs unless the necessary inputs for the
2499278019eSSteven Wu   // job is missing due to previous failures.
250932b3198SRafael Espindola   for (const auto &Job : Jobs) {
2519278019eSSteven Wu     if (!InputsOk(Job, FailingCommands))
2529278019eSSteven Wu       continue;
253932b3198SRafael Espindola     const Command *FailingCommand = nullptr;
254*c12577c6SJan Svoboda     if (int Res = ExecuteCommand(Job, FailingCommand, LogOnly)) {
255932b3198SRafael Espindola       FailingCommands.push_back(std::make_pair(Res, FailingCommand));
2569278019eSSteven Wu       // Bail as soon as one command fails in cl driver mode.
2579278019eSSteven Wu       if (TheDriver.IsCLMode())
2588671c441SJustin Lebar         return;
2598671c441SJustin Lebar     }
26064316c49SDaniel Dunbar   }
26164316c49SDaniel Dunbar }
262be10f985SChad Rosier 
initCompilationForDiagnostics()263b2aa9234SDmitri Gribenko void Compilation::initCompilationForDiagnostics() {
264332a5e52SJustin Bogner   ForDiagnostics = true;
265332a5e52SJustin Bogner 
266be10f985SChad Rosier   // Free actions and jobs.
26741094615SJustin Lebar   Actions.clear();
26841094615SJustin Lebar   AllActions.clear();
269be10f985SChad Rosier   Jobs.clear();
270be10f985SChad Rosier 
2713891885cSDavid Stenberg   // Remove temporary files.
2723891885cSDavid Stenberg   if (!TheDriver.isSaveTempsEnabled() && !ForceKeepTempFiles)
2733891885cSDavid Stenberg     CleanupFileList(TempFiles);
2743891885cSDavid Stenberg 
275be10f985SChad Rosier   // Clear temporary/results file lists.
276be10f985SChad Rosier   TempFiles.clear();
277be10f985SChad Rosier   ResultFiles.clear();
278c5103c3fSChad Rosier   FailureResultFiles.clear();
279be10f985SChad Rosier 
280be10f985SChad Rosier   // Remove any user specified output.  Claim any unclaimed arguments, so as
281be10f985SChad Rosier   // to avoid emitting warnings about unused args.
28275f09b54SAlexandre Ganea   OptSpecifier OutputOpts[] = {
28375f09b54SAlexandre Ganea       options::OPT_o,  options::OPT_MD, options::OPT_MMD, options::OPT_M,
28475f09b54SAlexandre Ganea       options::OPT_MM, options::OPT_MF, options::OPT_MG,  options::OPT_MJ,
28575f09b54SAlexandre Ganea       options::OPT_MQ, options::OPT_MT, options::OPT_MV};
286f15014ffSBenjamin Kramer   for (unsigned i = 0, e = llvm::array_lengthof(OutputOpts); i != e; ++i) {
2879b515cb0SPeter Collingbourne     if (TranslatedArgs->hasArg(OutputOpts[i]))
2889b515cb0SPeter Collingbourne       TranslatedArgs->eraseArg(OutputOpts[i]);
2899b515cb0SPeter Collingbourne   }
290be10f985SChad Rosier   TranslatedArgs->ClaimAllArgs();
291be10f985SChad Rosier 
29275f09b54SAlexandre Ganea   // Force re-creation of the toolchain Args, otherwise our modifications just
29375f09b54SAlexandre Ganea   // above will have no effect.
29475f09b54SAlexandre Ganea   for (auto Arg : TCArgs)
29575f09b54SAlexandre Ganea     if (Arg.second != TranslatedArgs)
29675f09b54SAlexandre Ganea       delete Arg.second;
29775f09b54SAlexandre Ganea   TCArgs.clear();
29875f09b54SAlexandre Ganea 
299be10f985SChad Rosier   // Redirect stdout/stderr to /dev/null.
3009707aa74SAlexander Kornienko   Redirects = {None, {""}, {""}};
3013891885cSDavid Stenberg 
3023891885cSDavid Stenberg   // Temporary files added by diagnostics should be kept.
3033891885cSDavid Stenberg   ForceKeepTempFiles = true;
304be10f985SChad Rosier }
305980920a3SSebastian Pop 
getSysRoot() const306b2aa9234SDmitri Gribenko StringRef Compilation::getSysRoot() const {
307980920a3SSebastian Pop   return getDriver().SysRoot;
308980920a3SSebastian Pop }
3099c366cdfSNikolay Haustov 
Redirect(ArrayRef<Optional<StringRef>> Redirects)3109707aa74SAlexander Kornienko void Compilation::Redirect(ArrayRef<Optional<StringRef>> Redirects) {
3119c366cdfSNikolay Haustov   this->Redirects = Redirects;
3129c366cdfSNikolay Haustov }
313