]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/llvm/tools/clang/tools/driver/driver.cpp
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / contrib / llvm / tools / clang / tools / driver / driver.cpp
1 //===-- driver.cpp - Clang GCC-Compatible Driver --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is the entry point to the clang driver; it is a thin wrapper
11 // for functionality in the Driver clang library.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "clang/Driver/Compilation.h"
16 #include "clang/Driver/Driver.h"
17 #include "clang/Driver/Option.h"
18 #include "clang/Frontend/DiagnosticOptions.h"
19 #include "clang/Frontend/TextDiagnosticPrinter.h"
20
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/OwningPtr.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/PrettyStackTrace.h"
31 #include "llvm/Support/Regex.h"
32 #include "llvm/Support/Timer.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/Program.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include "llvm/Support/system_error.h"
41 #include <cctype>
42 using namespace clang;
43 using namespace clang::driver;
44
45 llvm::sys::Path GetExecutablePath(const char *Argv0, bool CanonicalPrefixes) {
46   if (!CanonicalPrefixes)
47     return llvm::sys::Path(Argv0);
48
49   // This just needs to be some symbol in the binary; C++ doesn't
50   // allow taking the address of ::main however.
51   void *P = (void*) (intptr_t) GetExecutablePath;
52   return llvm::sys::Path::GetMainExecutable(Argv0, P);
53 }
54
55 static const char *SaveStringInSet(std::set<std::string> &SavedStrings,
56                                    StringRef S) {
57   return SavedStrings.insert(S).first->c_str();
58 }
59
60 /// ApplyQAOverride - Apply a list of edits to the input argument lists.
61 ///
62 /// The input string is a space separate list of edits to perform,
63 /// they are applied in order to the input argument lists. Edits
64 /// should be one of the following forms:
65 ///
66 ///  '#': Silence information about the changes to the command line arguments.
67 ///
68 ///  '^': Add FOO as a new argument at the beginning of the command line.
69 ///
70 ///  '+': Add FOO as a new argument at the end of the command line.
71 ///
72 ///  's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
73 ///  line.
74 ///
75 ///  'xOPTION': Removes all instances of the literal argument OPTION.
76 ///
77 ///  'XOPTION': Removes all instances of the literal argument OPTION,
78 ///  and the following argument.
79 ///
80 ///  'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
81 ///  at the end of the command line.
82 ///
83 /// \param OS - The stream to write edit information to.
84 /// \param Args - The vector of command line arguments.
85 /// \param Edit - The override command to perform.
86 /// \param SavedStrings - Set to use for storing string representations.
87 static void ApplyOneQAOverride(raw_ostream &OS,
88                                SmallVectorImpl<const char*> &Args,
89                                StringRef Edit,
90                                std::set<std::string> &SavedStrings) {
91   // This does not need to be efficient.
92
93   if (Edit[0] == '^') {
94     const char *Str =
95       SaveStringInSet(SavedStrings, Edit.substr(1));
96     OS << "### Adding argument " << Str << " at beginning\n";
97     Args.insert(Args.begin() + 1, Str);
98   } else if (Edit[0] == '+') {
99     const char *Str =
100       SaveStringInSet(SavedStrings, Edit.substr(1));
101     OS << "### Adding argument " << Str << " at end\n";
102     Args.push_back(Str);
103   } else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") &&
104              Edit.slice(2, Edit.size()-1).find('/') != StringRef::npos) {
105     StringRef MatchPattern = Edit.substr(2).split('/').first;
106     StringRef ReplPattern = Edit.substr(2).split('/').second;
107     ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);
108
109     for (unsigned i = 1, e = Args.size(); i != e; ++i) {
110       std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
111
112       if (Repl != Args[i]) {
113         OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
114         Args[i] = SaveStringInSet(SavedStrings, Repl);
115       }
116     }
117   } else if (Edit[0] == 'x' || Edit[0] == 'X') {
118     std::string Option = Edit.substr(1, std::string::npos);
119     for (unsigned i = 1; i < Args.size();) {
120       if (Option == Args[i]) {
121         OS << "### Deleting argument " << Args[i] << '\n';
122         Args.erase(Args.begin() + i);
123         if (Edit[0] == 'X') {
124           if (i < Args.size()) {
125             OS << "### Deleting argument " << Args[i] << '\n';
126             Args.erase(Args.begin() + i);
127           } else
128             OS << "### Invalid X edit, end of command line!\n";
129         }
130       } else
131         ++i;
132     }
133   } else if (Edit[0] == 'O') {
134     for (unsigned i = 1; i < Args.size();) {
135       const char *A = Args[i];
136       if (A[0] == '-' && A[1] == 'O' &&
137           (A[2] == '\0' ||
138            (A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
139                              ('0' <= A[2] && A[2] <= '9'))))) {
140         OS << "### Deleting argument " << Args[i] << '\n';
141         Args.erase(Args.begin() + i);
142       } else
143         ++i;
144     }
145     OS << "### Adding argument " << Edit << " at end\n";
146     Args.push_back(SaveStringInSet(SavedStrings, '-' + Edit.str()));
147   } else {
148     OS << "### Unrecognized edit: " << Edit << "\n";
149   }
150 }
151
152 /// ApplyQAOverride - Apply a comma separate list of edits to the
153 /// input argument lists. See ApplyOneQAOverride.
154 static void ApplyQAOverride(SmallVectorImpl<const char*> &Args,
155                             const char *OverrideStr,
156                             std::set<std::string> &SavedStrings) {
157   raw_ostream *OS = &llvm::errs();
158
159   if (OverrideStr[0] == '#') {
160     ++OverrideStr;
161     OS = &llvm::nulls();
162   }
163
164   *OS << "### QA_OVERRIDE_GCC3_OPTIONS: " << OverrideStr << "\n";
165
166   // This does not need to be efficient.
167
168   const char *S = OverrideStr;
169   while (*S) {
170     const char *End = ::strchr(S, ' ');
171     if (!End)
172       End = S + strlen(S);
173     if (End != S)
174       ApplyOneQAOverride(*OS, Args, std::string(S, End), SavedStrings);
175     S = End;
176     if (*S != '\0')
177       ++S;
178   }
179 }
180
181 extern int cc1_main(const char **ArgBegin, const char **ArgEnd,
182                     const char *Argv0, void *MainAddr);
183 extern int cc1as_main(const char **ArgBegin, const char **ArgEnd,
184                       const char *Argv0, void *MainAddr);
185
186 static void ExpandArgsFromBuf(const char *Arg,
187                               SmallVectorImpl<const char*> &ArgVector,
188                               std::set<std::string> &SavedStrings) {
189   const char *FName = Arg + 1;
190   llvm::OwningPtr<llvm::MemoryBuffer> MemBuf;
191   if (llvm::MemoryBuffer::getFile(FName, MemBuf)) {
192     ArgVector.push_back(SaveStringInSet(SavedStrings, Arg));
193     return;
194   }
195
196   const char *Buf = MemBuf->getBufferStart();
197   char InQuote = ' ';
198   std::string CurArg;
199
200   for (const char *P = Buf; ; ++P) {
201     if (*P == '\0' || (isspace(*P) && InQuote == ' ')) {
202       if (!CurArg.empty()) {
203
204         if (CurArg[0] != '@') {
205           ArgVector.push_back(SaveStringInSet(SavedStrings, CurArg));
206         } else {
207           ExpandArgsFromBuf(CurArg.c_str(), ArgVector, SavedStrings);
208         }
209
210         CurArg = "";
211       }
212       if (*P == '\0')
213         break;
214       else
215         continue;
216     }
217
218     if (isspace(*P)) {
219       if (InQuote != ' ')
220         CurArg.push_back(*P);
221       continue;
222     }
223
224     if (*P == '"' || *P == '\'') {
225       if (InQuote == *P)
226         InQuote = ' ';
227       else if (InQuote == ' ')
228         InQuote = *P;
229       else
230         CurArg.push_back(*P);
231       continue;
232     }
233
234     if (*P == '\\') {
235       ++P;
236       if (*P != '\0')
237         CurArg.push_back(*P);
238       continue;
239     }
240     CurArg.push_back(*P);
241   }
242 }
243
244 static void ExpandArgv(int argc, const char **argv,
245                        SmallVectorImpl<const char*> &ArgVector,
246                        std::set<std::string> &SavedStrings) {
247   for (int i = 0; i < argc; ++i) {
248     const char *Arg = argv[i];
249     if (Arg[0] != '@') {
250       ArgVector.push_back(SaveStringInSet(SavedStrings, std::string(Arg)));
251       continue;
252     }
253
254     ExpandArgsFromBuf(Arg, ArgVector, SavedStrings);
255   }
256 }
257
258 static void ParseProgName(SmallVectorImpl<const char *> &ArgVector,
259                           std::set<std::string> &SavedStrings,
260                           Driver &TheDriver)
261 {
262   // Try to infer frontend type and default target from the program name.
263
264   // suffixes[] contains the list of known driver suffixes.
265   // Suffixes are compared against the program name in order.
266   // If there is a match, the frontend type is updated as necessary (CPP/C++).
267   // If there is no match, a second round is done after stripping the last
268   // hyphen and everything following it. This allows using something like
269   // "clang++-2.9".
270
271   // If there is a match in either the first or second round,
272   // the function tries to identify a target as prefix. E.g.
273   // "x86_64-linux-clang" as interpreted as suffix "clang" with
274   // target prefix "x86_64-linux". If such a target prefix is found,
275   // is gets added via -ccc-host-triple as implicit first argument.
276   static const struct {
277     const char *Suffix;
278     bool IsCXX;
279     bool IsCPP;
280   } suffixes [] = {
281     { "clang", false, false },
282     { "clang++", true, false },
283     { "clang-c++", true, false },
284     { "clang-cc", false, false },
285     { "clang-cpp", false, true },
286     { "clang-g++", true, false },
287     { "clang-gcc", false, false },
288     { "cc", false, false },
289     { "cpp", false, true },
290     { "++", true, false },
291   };
292   std::string ProgName(llvm::sys::path::stem(ArgVector[0]));
293   StringRef ProgNameRef(ProgName);
294   StringRef Prefix;
295
296   for (int Components = 2; Components; --Components) {
297     bool FoundMatch = false;
298     size_t i;
299
300     for (i = 0; i < sizeof(suffixes) / sizeof(suffixes[0]); ++i) {
301       if (ProgNameRef.endswith(suffixes[i].Suffix)) {
302         FoundMatch = true;
303         if (suffixes[i].IsCXX)
304           TheDriver.CCCIsCXX = true;
305         if (suffixes[i].IsCPP)
306           TheDriver.CCCIsCPP = true;
307         break;
308       }
309     }
310
311     if (FoundMatch) {
312       StringRef::size_type LastComponent = ProgNameRef.rfind('-',
313         ProgNameRef.size() - strlen(suffixes[i].Suffix));
314       if (LastComponent != StringRef::npos)
315         Prefix = ProgNameRef.slice(0, LastComponent);
316       break;
317     }
318
319     StringRef::size_type LastComponent = ProgNameRef.rfind('-');
320     if (LastComponent == StringRef::npos)
321       break;
322     ProgNameRef = ProgNameRef.slice(0, LastComponent);
323   }
324
325   if (Prefix.empty())
326     return;
327
328   std::string IgnoredError;
329   if (llvm::TargetRegistry::lookupTarget(Prefix, IgnoredError)) {
330     SmallVectorImpl<const char *>::iterator it = ArgVector.begin();
331     if (it != ArgVector.end())
332       ++it;
333     ArgVector.insert(it, SaveStringInSet(SavedStrings, Prefix));
334     ArgVector.insert(it,
335       SaveStringInSet(SavedStrings, std::string("-ccc-host-triple")));
336   }
337 }
338
339 int main(int argc_, const char **argv_) {
340   llvm::sys::PrintStackTraceOnErrorSignal();
341   llvm::PrettyStackTraceProgram X(argc_, argv_);
342
343   std::set<std::string> SavedStrings;
344   SmallVector<const char*, 256> argv;
345
346   ExpandArgv(argc_, argv_, argv, SavedStrings);
347
348   // Handle -cc1 integrated tools.
349   if (argv.size() > 1 && StringRef(argv[1]).startswith("-cc1")) {
350     StringRef Tool = argv[1] + 4;
351
352     if (Tool == "")
353       return cc1_main(argv.data()+2, argv.data()+argv.size(), argv[0],
354                       (void*) (intptr_t) GetExecutablePath);
355     if (Tool == "as")
356       return cc1as_main(argv.data()+2, argv.data()+argv.size(), argv[0],
357                       (void*) (intptr_t) GetExecutablePath);
358
359     // Reject unknown tools.
360     llvm::errs() << "error: unknown integrated tool '" << Tool << "'\n";
361     return 1;
362   }
363
364   bool CanonicalPrefixes = true;
365   for (int i = 1, size = argv.size(); i < size; ++i) {
366     if (StringRef(argv[i]) == "-no-canonical-prefixes") {
367       CanonicalPrefixes = false;
368       break;
369     }
370   }
371
372   llvm::sys::Path Path = GetExecutablePath(argv[0], CanonicalPrefixes);
373
374   TextDiagnosticPrinter *DiagClient
375     = new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions());
376   DiagClient->setPrefix(llvm::sys::path::stem(Path.str()));
377   llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
378   DiagnosticsEngine Diags(DiagID, DiagClient);
379
380 #ifdef CLANG_IS_PRODUCTION
381   const bool IsProduction = true;
382 #else
383   const bool IsProduction = false;
384 #endif
385   Driver TheDriver(Path.str(), llvm::sys::getHostTriple(),
386                    "a.out", IsProduction, Diags);
387
388   // Attempt to find the original path used to invoke the driver, to determine
389   // the installed path. We do this manually, because we want to support that
390   // path being a symlink.
391   {
392     llvm::SmallString<128> InstalledPath(argv[0]);
393
394     // Do a PATH lookup, if there are no directory components.
395     if (llvm::sys::path::filename(InstalledPath) == InstalledPath) {
396       llvm::sys::Path Tmp = llvm::sys::Program::FindProgramByName(
397         llvm::sys::path::filename(InstalledPath.str()));
398       if (!Tmp.empty())
399         InstalledPath = Tmp.str();
400     }
401     llvm::sys::fs::make_absolute(InstalledPath);
402     InstalledPath = llvm::sys::path::parent_path(InstalledPath);
403     bool exists;
404     if (!llvm::sys::fs::exists(InstalledPath.str(), exists) && exists)
405       TheDriver.setInstalledDir(InstalledPath);
406   }
407
408   llvm::InitializeAllTargets();
409   ParseProgName(argv, SavedStrings, TheDriver);
410
411   // Handle CC_PRINT_OPTIONS and CC_PRINT_OPTIONS_FILE.
412   TheDriver.CCPrintOptions = !!::getenv("CC_PRINT_OPTIONS");
413   if (TheDriver.CCPrintOptions)
414     TheDriver.CCPrintOptionsFilename = ::getenv("CC_PRINT_OPTIONS_FILE");
415
416   // Handle CC_PRINT_HEADERS and CC_PRINT_HEADERS_FILE.
417   TheDriver.CCPrintHeaders = !!::getenv("CC_PRINT_HEADERS");
418   if (TheDriver.CCPrintHeaders)
419     TheDriver.CCPrintHeadersFilename = ::getenv("CC_PRINT_HEADERS_FILE");
420
421   // Handle CC_LOG_DIAGNOSTICS and CC_LOG_DIAGNOSTICS_FILE.
422   TheDriver.CCLogDiagnostics = !!::getenv("CC_LOG_DIAGNOSTICS");
423   if (TheDriver.CCLogDiagnostics)
424     TheDriver.CCLogDiagnosticsFilename = ::getenv("CC_LOG_DIAGNOSTICS_FILE");
425
426   // Handle QA_OVERRIDE_GCC3_OPTIONS and CCC_ADD_ARGS, used for editing a
427   // command line behind the scenes.
428   if (const char *OverrideStr = ::getenv("QA_OVERRIDE_GCC3_OPTIONS")) {
429     // FIXME: Driver shouldn't take extra initial argument.
430     ApplyQAOverride(argv, OverrideStr, SavedStrings);
431   } else if (const char *Cur = ::getenv("CCC_ADD_ARGS")) {
432     // FIXME: Driver shouldn't take extra initial argument.
433     std::vector<const char*> ExtraArgs;
434
435     for (;;) {
436       const char *Next = strchr(Cur, ',');
437
438       if (Next) {
439         ExtraArgs.push_back(SaveStringInSet(SavedStrings,
440                                             std::string(Cur, Next)));
441         Cur = Next + 1;
442       } else {
443         if (*Cur != '\0')
444           ExtraArgs.push_back(SaveStringInSet(SavedStrings, Cur));
445         break;
446       }
447     }
448
449     argv.insert(&argv[1], ExtraArgs.begin(), ExtraArgs.end());
450   }
451
452   llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(argv));
453   int Res = 0;
454   const Command *FailingCommand = 0;
455   if (C.get())
456     Res = TheDriver.ExecuteCompilation(*C, FailingCommand);
457
458   // If result status is < 0, then the driver command signalled an error.
459   // In this case, generate additional diagnostic information if possible.
460   if (Res < 0)
461     TheDriver.generateCompilationDiagnostics(*C, FailingCommand);
462
463   // If any timers were active but haven't been destroyed yet, print their
464   // results now.  This happens in -disable-free mode.
465   llvm::TimerGroup::printAll(llvm::errs());
466   
467   llvm::llvm_shutdown();
468
469   return Res;
470 }