816f793bc07dc5ae5d6ba40e156d85a3317d6fd0
[oota-llvm.git] / lib / CompilerDriver / Action.cpp
1 //===--- Action.cpp - The LLVM Compiler Driver ------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open
6 // Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  Action class - implementation and auxiliary functions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CompilerDriver/Action.h"
15 #include "llvm/CompilerDriver/BuiltinOptions.h"
16
17 #include "llvm/System/Program.h"
18
19 #include <iostream>
20 #include <stdexcept>
21
22 using namespace llvm;
23 using namespace llvmc;
24
25 namespace {
26   int ExecuteProgram(const std::string& name,
27                      const StrVector& args) {
28     sys::Path prog = sys::Program::FindProgramByName(name);
29
30     if (prog.isEmpty())
31       throw std::runtime_error("Can't find program '" + name + "'");
32     if (!prog.canExecute())
33       throw std::runtime_error("Program '" + name + "' is not executable.");
34
35     // Build the command line vector and the redirects array.
36     const sys::Path* redirects[3] = {0,0,0};
37     sys::Path stdout_redirect;
38
39     std::vector<const char*> argv;
40     argv.reserve((args.size()+2));
41     argv.push_back(name.c_str());
42
43     for (StrVector::const_iterator B = args.begin(), E = args.end();
44          B!=E; ++B) {
45       if (*B == ">") {
46         ++B;
47         stdout_redirect.set(*B);
48         redirects[1] = &stdout_redirect;
49       }
50       else {
51         argv.push_back((*B).c_str());
52       }
53     }
54     argv.push_back(0);  // null terminate list.
55
56     // Invoke the program.
57     return sys::Program::ExecuteAndWait(prog, &argv[0], 0, &redirects[0]);
58   }
59
60   void print_string (const std::string& str) {
61     std::cerr << str << ' ';
62   }
63 }
64
65 int llvmc::Action::Execute() const {
66   if (DryRun || VerboseMode) {
67     std::cerr << Command_ << " ";
68     std::for_each(Args_.begin(), Args_.end(), print_string);
69     std::cerr << '\n';
70   }
71   if (DryRun)
72     return 0;
73   else
74     return ExecuteProgram(Command_, Args_);
75 }