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