1/*
2 * Copyright 2012, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <string>
18#include <vector>
19
20#include <stdlib.h>
21
22#include <llvm/ADT/STLExtras.h>
23#include <llvm/ADT/SmallString.h>
24#include <llvm/Config/config.h>
25#include <llvm/Support/CommandLine.h>
26#include <llvm/Support/FileSystem.h>
27#include <llvm/Support/Path.h>
28#include <llvm/Support/raw_ostream.h>
29
30#include <bcc/BCCContext.h>
31#include <bcc/Compiler.h>
32#include <bcc/Config/Config.h>
33#include <bcc/ExecutionEngine/SymbolResolverProxy.h>
34#include <bcc/ExecutionEngine/SymbolResolvers.h>
35#include <bcc/Renderscript/RSCompilerDriver.h>
36#include <bcc/Script.h>
37#include <bcc/Source.h>
38#include <bcc/Support/CompilerConfig.h>
39#include <bcc/Support/Initialization.h>
40#include <bcc/Support/InputFile.h>
41#include <bcc/Support/OutputFile.h>
42
43using namespace bcc;
44
45//===----------------------------------------------------------------------===//
46// General Options
47//===----------------------------------------------------------------------===//
48namespace {
49
50llvm::cl::list<std::string>
51OptInputFilenames(llvm::cl::Positional, llvm::cl::OneOrMore,
52                  llvm::cl::desc("<input bitcode files>"));
53
54llvm::cl::opt<std::string>
55OptOutputFilename("o", llvm::cl::desc("Specify the output filename"),
56                  llvm::cl::value_desc("filename"));
57
58llvm::cl::opt<std::string>
59OptRuntimePath("rt-path", llvm::cl::desc("Specify the runtime library path"),
60               llvm::cl::value_desc("path"));
61
62llvm::cl::opt<std::string>
63OptTargetTriple("mtriple",
64                llvm::cl::desc("Specify the target triple (default: "
65                               DEFAULT_TARGET_TRIPLE_STRING ")"),
66                llvm::cl::init(DEFAULT_TARGET_TRIPLE_STRING),
67                llvm::cl::value_desc("triple"));
68
69llvm::cl::alias OptTargetTripleC("C", llvm::cl::NotHidden,
70                                 llvm::cl::desc("Alias for -mtriple"),
71                                 llvm::cl::aliasopt(OptTargetTriple));
72
73//===----------------------------------------------------------------------===//
74// Compiler Options
75//===----------------------------------------------------------------------===//
76llvm::cl::opt<bool>
77OptPIC("fPIC", llvm::cl::desc("Generate fully relocatable, position independent"
78                              " code"));
79
80llvm::cl::opt<char>
81OptOptLevel("O", llvm::cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
82                                "(default: -O2)"),
83            llvm::cl::Prefix, llvm::cl::ZeroOrMore, llvm::cl::init('2'));
84
85llvm::cl::opt<bool>
86OptC("c", llvm::cl::desc("Compile and assemble, but do not link."));
87
88//===----------------------------------------------------------------------===//
89// Linker Options
90//===----------------------------------------------------------------------===//
91// FIXME: this option will be removed in the future when MCLinker is capable
92//        of generating shared library directly from given bitcode. It only
93//        takes effect when -shared is supplied.
94llvm::cl::opt<std::string>
95OptImmObjectOutput("or", llvm::cl::desc("Specify the filename for output the "
96                                        "intermediate relocatable when linking "
97                                        "the input bitcode to the shared "
98                                        "library"), llvm::cl::ValueRequired);
99
100llvm::cl::opt<bool>
101OptShared("shared", llvm::cl::desc("Create a shared library from input bitcode "
102                                   "files"));
103
104
105// Override "bcc -version" since the LLVM version information is not correct on
106// Android build.
107void BCCVersionPrinter() {
108  llvm::raw_ostream &os = llvm::outs();
109  os << "libbcc (The Android Open Source Project, http://www.android.com/):\n"
110     << "  Default target: " << DEFAULT_TARGET_TRIPLE_STRING << "\n\n"
111     << "LLVM (http://llvm.org/):\n"
112     << "  Version: " << PACKAGE_VERSION << "\n";
113  return;
114}
115
116} // end anonymous namespace
117
118RSScript *PrepareRSScript(BCCContext &pContext,
119                          const llvm::cl::list<std::string> &pBitcodeFiles) {
120  RSScript *result = NULL;
121
122  for (unsigned i = 0; i < pBitcodeFiles.size(); i++) {
123    const std::string &input_bitcode = pBitcodeFiles[i];
124    Source *source = Source::CreateFromFile(pContext, input_bitcode);
125    if (source == NULL) {
126      llvm::errs() << "Failed to load llvm module from file `" << input_bitcode
127                   << "'!\n";
128      return NULL;
129    }
130
131    if (result != NULL) {
132      if (!result->mergeSource(*source, /* pPreserveSource */false)) {
133        llvm::errs() << "Failed to merge the llvm module `" << input_bitcode
134                     << "' to compile!\n";
135        delete source;
136        return NULL;
137      }
138    } else {
139      result = new (std::nothrow) RSScript(*source);
140      if (result == NULL) {
141        llvm::errs() << "Out of memory when create script for file `"
142                     << input_bitcode << "'!\n";
143        delete source;
144        return NULL;
145      }
146    }
147  }
148
149  return result;
150}
151
152static inline
153bool ConfigCompiler(RSCompilerDriver &pCompilerDriver) {
154  RSCompiler *compiler = pCompilerDriver.getCompiler();
155  CompilerConfig *config = NULL;
156
157  config = new (std::nothrow) CompilerConfig(OptTargetTriple);
158  if (config == NULL) {
159    llvm::errs() << "Out of memory when create the compiler configuration!\n";
160    return false;
161  }
162
163  // Explicitly set ARM feature vector
164  if (config->getTriple().find("arm") != std::string::npos) {
165    std::vector<std::string> fv;
166    fv.push_back("+vfp3");
167    fv.push_back("+d16");
168    fv.push_back("-neon");
169    fv.push_back("-neonfp");
170    config->setFeatureString(fv);
171  }
172
173  // Compatibility mode on x86 requires atom code generation.
174  if (config->getTriple().find("i686") != std::string::npos) {
175    config->setCPU("atom");
176  }
177
178  // Setup the config according to the value of command line option.
179  if (OptPIC) {
180    config->setRelocationModel(llvm::Reloc::PIC_);
181  }
182  switch (OptOptLevel) {
183    case '0': config->setOptimizationLevel(llvm::CodeGenOpt::None); break;
184    case '1': config->setOptimizationLevel(llvm::CodeGenOpt::Less); break;
185    case '3': config->setOptimizationLevel(llvm::CodeGenOpt::Aggressive); break;
186    case '2':
187    default: {
188      config->setOptimizationLevel(llvm::CodeGenOpt::Default);
189      break;
190    }
191  }
192
193  pCompilerDriver.setConfig(config);
194  Compiler::ErrorCode result = compiler->config(*config);
195
196  if (result != Compiler::kSuccess) {
197    llvm::errs() << "Failed to configure the compiler! (detail: "
198                 << Compiler::GetErrorString(result) << ")\n";
199    return false;
200  }
201
202  return true;
203}
204
205#define DEFAULT_OUTPUT_PATH   "/sdcard/a.out"
206static inline
207std::string DetermineOutputFilename(const std::string &pOutputPath) {
208  if (!pOutputPath.empty()) {
209    return pOutputPath;
210  }
211
212  // User doesn't specify the value to -o.
213  if (OptInputFilenames.size() > 1) {
214    llvm::errs() << "Use " DEFAULT_OUTPUT_PATH " for output file!\n";
215    return DEFAULT_OUTPUT_PATH;
216  }
217
218  // There's only one input bitcode file.
219  const std::string &input_path = OptInputFilenames[0];
220  llvm::SmallString<200> output_path(input_path);
221
222  std::error_code err = llvm::sys::fs::make_absolute(output_path);
223  if (err) {
224    llvm::errs() << "Failed to determine the absolute path of `" << input_path
225                 << "'! (detail: " << err.message() << ")\n";
226    return "";
227  }
228
229  if (OptC) {
230    // -c was specified. Replace the extension to .o.
231    llvm::sys::path::replace_extension(output_path, "o");
232  } else {
233    // Use a.out under current working directory when compile executable or
234    // shared library.
235    llvm::sys::path::remove_filename(output_path);
236    llvm::sys::path::append(output_path, "a.out");
237  }
238
239  return output_path.c_str();
240}
241
242int main(int argc, char **argv) {
243  llvm::cl::SetVersionPrinter(BCCVersionPrinter);
244  llvm::cl::ParseCommandLineOptions(argc, argv);
245  init::Initialize();
246
247  if (OptRuntimePath.empty()) {
248    fprintf(stderr, "You must set \"-rt-path </path/to/libclcore.bc>\" with "
249                    "this tool\n");
250    return EXIT_FAILURE;
251  }
252
253  BCCContext context;
254  RSCompilerDriver rscd(false);
255  Compiler compiler;
256
257  if (!ConfigCompiler(rscd)) {
258    return EXIT_FAILURE;
259  }
260
261  std::string OutputFilename = DetermineOutputFilename(OptOutputFilename);
262  if (OutputFilename.empty()) {
263    return EXIT_FAILURE;
264  }
265
266  RSScript *s = NULL;
267  s = PrepareRSScript(context, OptInputFilenames);
268  if (!rscd.buildForCompatLib(*s, OutputFilename.c_str(), OptRuntimePath.c_str())) {
269    fprintf(stderr, "Failed to compile script!");
270    return EXIT_FAILURE;
271  }
272
273  return EXIT_SUCCESS;
274}
275