aboutsummaryrefslogtreecommitdiff
path: root/tools/llvmc/CompilerDriver.cpp
blob: 038274b72aa6b54978ff866d60a85a42547b90f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
//===- CompilerDriver.cpp - The LLVM Compiler Driver ------------*- C++ -*-===//
//
// 
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the 
// University of Illinois Open Source License. See LICENSE.TXT for details.
// 
//===----------------------------------------------------------------------===//
//
// This file implements the bulk of the LLVM Compiler Driver (llvmc).
//
//===------------------------------------------------------------------------===

#include "CompilerDriver.h"
#include "ConfigLexer.h"
#include <iostream>

using namespace llvm;

namespace {
  inline std::string RemoveSuffix(const std::string& fullName) {
    size_t dotpos = fullName.rfind('.',fullName.size());
    if ( dotpos == std::string::npos ) return fullName;
    return fullName.substr(0, dotpos);
  }

  inline std::string GetSuffix(const std::string& fullName) {
    size_t dotpos = fullName.rfind('.',fullName.size());
    if ( dotpos = std::string::npos ) return "";
    return fullName.substr(dotpos+1);
  }

  const char OutputSuffix[] = ".o";

  void WriteAction(CompilerDriver::Action* a ) {
    std::cerr << a->program;
    std::vector<std::string>::iterator I = a->args.begin();
    while (I != a->args.end()) {
      std::cerr << " " + *I;
      ++I;
    }
    std::cerr << "\n";
  }

  void DumpAction(CompilerDriver::Action* a) {
    std::cerr << "command = " << a->program;
    std::vector<std::string>::iterator I = a->args.begin();
    while (I != a->args.end()) {
      std::cerr << " " + *I;
      ++I;
    }
    std::cerr << "\n";
    std::cerr << "flags = " << a->flags << "\n";
    std::cerr << "inputAt = " << a->inputAt << "\n";
    std::cerr << "outputAt = " << a->outputAt << "\n";
  }

  void DumpConfigData(CompilerDriver::ConfigData* cd, const std::string& type ){
    std::cerr << "Configuration Data For '" << cd->langName << "' (" << type 
      << ")\n";
    std::cerr << "PreProcessor: ";
    DumpAction(&cd->PreProcessor);
    std::cerr << "Translator: ";
    DumpAction(&cd->Translator);
    std::cerr << "Optimizer: ";
    DumpAction(&cd->Optimizer);
    std::cerr << "Assembler: ";
    DumpAction(&cd->Assembler);
    std::cerr << "Linker: ";
    DumpAction(&cd->Linker);
  }
}


CompilerDriver::CompilerDriver(ConfigDataProvider& confDatProv )
  : cdp(&confDatProv)
  , finalPhase(LINKING)
  , optLevel(OPT_FAST_COMPILE) 
  , isDryRun(false)
  , isVerbose(false)
  , isDebug(false)
  , timeActions(false)
  , emitRawCode(false)
  , emitNativeCode(false)
  , machine()
  , LibraryPaths()
  , PreprocessorOptions()
  , TranslatorOptions()
  , OptimizerOptions()
  , AssemblerOptions()
  , LinkerOptions()
{
  // FIXME: These libraries are platform specific
  LibraryPaths.push_back("/lib");
  LibraryPaths.push_back("/usr/lib");
}

CompilerDriver::~CompilerDriver() {
  cdp = 0;
  LibraryPaths.clear();
  PreprocessorOptions.clear();
  TranslatorOptions.clear();
  OptimizerOptions.clear();
  AssemblerOptions.clear();
  LinkerOptions.clear();
}

void CompilerDriver::error( const std::string& errmsg ) {
  std::cerr << "Error: " << errmsg << ".\n";
  exit(1);
}

inline std::string makeDashO(CompilerDriver::OptimizationLevels lev) {
  if (lev == CompilerDriver::OPT_NONE) return "";
  std::string result("-O");
  switch (lev) {
    case CompilerDriver::OPT_FAST_COMPILE :     result.append("1"); break;
    case CompilerDriver::OPT_SIMPLE:            result.append("2"); break;
    case CompilerDriver::OPT_AGGRESSIVE:        result.append("3"); break;
    case CompilerDriver::OPT_LINK_TIME:         result.append("4"); break;
    case CompilerDriver::OPT_AGGRESSIVE_LINK_TIME: result.append("5"); break;
    default:                    assert(!"Invalid optimization level!");
  }
  return result;
}

CompilerDriver::Action* CompilerDriver::GetAction(ConfigData* cd, 
                          const std::string& input, 
                          const std::string& output,
                          Phases phase)
{
  Action* pat = 0;
  // Get the action pattern
  switch (phase) {
    case PREPROCESSING: pat = &cd->PreProcessor; break;
    case TRANSLATION:   pat = &cd->Translator; break;
    case OPTIMIZATION:  pat = &cd->Optimizer; break;
    case ASSEMBLY:      pat = &cd->Assembler; break;
    case LINKING:       pat = &cd->Linker; break;
    default:
      assert(!"Invalid driver phase!");
      break;
  }
  assert(pat != 0 && "Invalid command pattern");

  // Create the resulting action
  Action* a = new Action(*pat);

  // Replace the substitution arguments
  if (pat->inputAt < a->args.size())
    a->args[pat->inputAt] = input;
  if (pat->outputAt < a->args.size())
    a->args[pat->outputAt] = output;

  // Insert specific options for each kind of action type
  switch (phase) {
    case PREPROCESSING:
      a->args.insert(a->args.begin(), PreprocessorOptions.begin(), 
                    PreprocessorOptions.end());
      break;
    case TRANSLATION:   
      a->args.insert(a->args.begin(), TranslatorOptions.begin(), 
                    TranslatorOptions.end());
      if (a->isSet(GROKS_DASH_O_FLAG))
        a->args.insert(a->args.begin(), makeDashO(optLevel));
      else if (a->isSet(GROKS_O10N_FLAG))
        a->args.insert(a->args.begin(), cd->opts[optLevel].begin(),
            cd->opts[optLevel].end());
      break;
    case OPTIMIZATION:  
      a->args.insert(a->args.begin(), OptimizerOptions.begin(), 
                    OptimizerOptions.end());
      if (a->isSet(GROKS_DASH_O_FLAG))
        a->args.insert(a->args.begin(), makeDashO(optLevel));
      else if (a->isSet(GROKS_O10N_FLAG))
        a->args.insert(a->args.begin(), cd->opts[optLevel].begin(),
            cd->opts[optLevel].end());
      break;
    case ASSEMBLY:      
      a->args.insert(a->args.begin(), AssemblerOptions.begin(), 
                    AssemblerOptions.end());
      break;
    case LINKING:       
      a->args.insert(a->args.begin(), LinkerOptions.begin(), 
                    LinkerOptions.end());
      if (a->isSet(GROKS_DASH_O_FLAG))
        a->args.insert(a->args.begin(), makeDashO(optLevel));
      else if (a->isSet(GROKS_O10N_FLAG))
        a->args.insert(a->args.begin(), cd->opts[optLevel].begin(),
            cd->opts[optLevel].end());
      break;
    default:
      assert(!"Invalid driver phase!");
      break;
  }
  return a;
}

void CompilerDriver::DoAction(Action*a)
{
  if (isVerbose)
    WriteAction(a);
  if (!isDryRun) {
    std::cerr << "execve(\"" << a->program << "\",[\"";
    std::vector<std::string>::iterator I = a->args.begin();
    while (I != a->args.end()) {
      std::cerr << *I;
      ++I;
      if (I != a->args.end())
        std::cerr << "\",\"";
    }
    std::cerr << "\"],ENV);\n";
  }
}

int CompilerDriver::execute(const InputList& InpList, 
                            const sys::Path& Output ) {
  // Echo the configuration of options if we're running verbose
  if (isDebug)
  {
    std::cerr << "Compiler Driver Options:\n";
    std::cerr << "DryRun = " << isDryRun << "\n";
    std::cerr << "Verbose = " << isVerbose << " \n";
    std::cerr << "TimeActions = " << timeActions << "\n";
    std::cerr << "EmitRawCode = " << emitRawCode << "\n";
    std::cerr << "OutputMachine = " << machine << "\n";
    std::cerr << "EmitNativeCode = " << emitNativeCode << "\n";
    InputList::const_iterator I = InpList.begin();
    while ( I != InpList.end() ) {
      std::cerr << "Input: " << I->first << "(" << I->second << ")\n";
      ++I;
    }
    std::cerr << "Output: " << Output << "\n";
  }

  // If there's no input, we're done.
  if (InpList.empty())
    error("Nothing to compile.");

  // If they are asking for linking and didn't provide an output
  // file then its an error (no way for us to "make up" a meaningful
  // file name based on the various linker input files).
  if (finalPhase == LINKING && Output.empty())
    error("An output file name must be specified for linker output");

  // This vector holds all the resulting actions of the following loop.
  std::vector<Action*> actions;

  // Create a temporary directory for our temporary files
  sys::Path TempDir(sys::Path::CONSTRUCT_TEMP_DIR);
  sys::Path TempPreprocessorOut;
  sys::Path TempTranslatorOut;
  sys::Path TempOptimizerOut;
  sys::Path TempAssemblerOut;
  sys::Path TempLinkerOut;

  /// PRE-PROCESSING / TRANSLATION / OPTIMIZATION / ASSEMBLY phases
  // for each input item
  std::vector<std::string> LinkageItems;
  InputList::const_iterator I = InpList.begin();
  while ( I != InpList.end() ) {
    // Get the suffix of the file name
    std::string suffix = GetSuffix(I->first);

    // If its a library, bytecode file, or object file, save 
    // it for linking below and short circuit the 
    // pre-processing/translation/assembly phases
    if (I->second.empty() || suffix == "o" || suffix == "bc") {
      // We shouldn't get any of these types of files unless we're 
      // later going to link. Enforce this limit now.
      if (finalPhase != LINKING) {
        error("Pre-compiled objects found but linking not requested");
      }
      LinkageItems.push_back(I->first);
      continue; // short circuit remainder of loop
    }

    // At this point, we know its something we need to translate
    // and/or optimize. See if we can get the configuration data
    // for this kind of file.
    ConfigData* cd = cdp->ProvideConfigData(I->second);
    if (cd == 0)
      error(std::string("Files of type '") + I->second + 
            "' are not recognized." ); 
    if (isDebug)
      DumpConfigData(cd,I->second);

    // We have valid configuration data, now figure out where the output
    // of compilation should end up.
    std::string OutFile;
    if (finalPhase != LINKING) {
      if (InpList.size() == 1 && !Output.empty()) 
        OutFile = Output;
      else
        OutFile = RemoveSuffix(I->first) + OutputSuffix;
    } else {
      OutFile = Output;
    }

    // PRE-PROCESSING PHASE
    Action& a = cd->PreProcessor;

    // Get the preprocessing action, if needed, or error if appropriate
    if (!a.program.empty()) {
      if (a.isSet(REQUIRED_FLAG) || finalPhase == PREPROCESSING) {
        TempPreprocessorOut = TempDir;
        TempPreprocessorOut.append_file("preproc.out");
        actions.push_back(GetAction(cd,I->first,
              TempPreprocessorOut,PREPROCESSING));
      }
    } else if (finalPhase == PREPROCESSING) {
      error(cd->langName + " does not support pre-processing");
    } else if (a.isSet(REQUIRED_FLAG)) {
      error(std::string("Don't know how to pre-process ") + 
            cd->langName + " files");
    }
    // Short-circuit remaining actions if all they want is pre-processing
    if (finalPhase == PREPROCESSING) { ++I; continue; };

    /// TRANSLATION PHASE
    a = cd->Translator;

    // Get the translation action, if needed, or error if appropriate
    if (!a.program.empty()) {
      if (a.isSet(REQUIRED_FLAG) || finalPhase == TRANSLATION) {
        TempTranslatorOut = TempDir;
        TempTranslatorOut.append_file("trans.out");
        actions.push_back(GetAction(cd,I->first,TempTranslatorOut,TRANSLATION));
      }
    } else if (finalPhase == TRANSLATION) {
      error(cd->langName + " does not support translation");
    } else if (a.isSet(REQUIRED_FLAG)) {
      error(std::string("Don't know how to translate ") + 
            cd->langName + " files");
    }
    // Short-circuit remaining actions if all they want is translation
    if (finalPhase == TRANSLATION) { ++I; continue; }

    /// OPTIMIZATION PHASE
    a = cd->Optimizer;

    // Get the optimization action, if needed, or error if appropriate
    if (!a.program.empty()) {
      TempOptimizerOut = TempDir;
      TempOptimizerOut.append_file("trans.out");
      actions.push_back(GetAction(cd,I->first,TempOptimizerOut,OPTIMIZATION));
    } else if (finalPhase == OPTIMIZATION) {
      error(cd->langName + " does not support optimization");
    } else if (a.isSet(REQUIRED_FLAG)) {
      error(std::string("Don't know how to optimize ") + 
            cd->langName + " files");
    }
    // Short-circuit remaining actions if all they want is optimization
    if (finalPhase == OPTIMIZATION) { ++I; continue; }

    ++I;
  }

  /// LINKING PHASE

  /// RUN THE ACTIONS
  std::vector<Action*>::iterator aIter = actions.begin();
  while (aIter != actions.end()) {
    DoAction(*aIter);
    aIter++;
  }

  // Cleanup files
  if (TempPreprocessorOut.exists())
    TempPreprocessorOut.remove_file();
  if (TempTranslatorOut.exists())
    TempTranslatorOut.remove_file();
  if (TempOptimizerOut.exists())
    TempOptimizerOut.remove_file();
  if (TempDir.exists())
    TempDir.remove_directory();

  return 0;
}

// vim: sw=2 smartindent smarttab tw=80 autoindent expandtab