RSCompilerDriver.cpp revision ad69476ec040ba9ee07176ccb758aabb5ff6d51c
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 "bcc/Renderscript/RSCompilerDriver.h"
18
19#include <llvm/IR/Module.h>
20#include <llvm/Support/CommandLine.h>
21#include <llvm/Support/PathV1.h>
22#include <llvm/Support/raw_ostream.h>
23
24#include "bcinfo/BitcodeWrapper.h"
25
26#include "bcc/Compiler.h"
27#include "bcc/Renderscript/RSExecutable.h"
28#include "bcc/Renderscript/RSScript.h"
29#include "bcc/Support/CompilerConfig.h"
30#include "bcc/Support/TargetCompilerConfigs.h"
31#include "bcc/Source.h"
32#include "bcc/Support/FileMutex.h"
33#include "bcc/Support/Log.h"
34#include "bcc/Support/InputFile.h"
35#include "bcc/Support/Initialization.h"
36#include "bcc/Support/Sha1Util.h"
37#include "bcc/Support/OutputFile.h"
38
39#ifdef HAVE_ANDROID_OS
40#include <cutils/properties.h>
41#endif
42#include <utils/String8.h>
43#include <utils/StopWatch.h>
44
45using namespace bcc;
46
47RSCompilerDriver::RSCompilerDriver(bool pUseCompilerRT) :
48    mConfig(NULL), mCompiler(), mCompilerRuntime(NULL), mDebugContext(false),
49    mEnableGlobalMerge(true) {
50  init::Initialize();
51  // Chain the symbol resolvers for compiler_rt and RS runtimes.
52  if (pUseCompilerRT) {
53    mCompilerRuntime = new CompilerRTSymbolResolver();
54    mResolver.chainResolver(*mCompilerRuntime);
55  }
56  mResolver.chainResolver(mRSRuntime);
57}
58
59RSCompilerDriver::~RSCompilerDriver() {
60  delete mCompilerRuntime;
61  delete mConfig;
62}
63
64RSExecutable *
65RSCompilerDriver::loadScript(const char *pCacheDir, const char *pResName,
66                             const char *pBitcode, size_t pBitcodeSize) {
67  //android::StopWatch load_time("bcc: RSCompilerDriver::loadScript time");
68  if ((pCacheDir == NULL) || (pResName == NULL)) {
69    ALOGE("Missing pCacheDir and/or pResName");
70    return NULL;
71  }
72
73  if ((pBitcode == NULL) || (pBitcodeSize <= 0)) {
74    ALOGE("No bitcode supplied! (bitcode: %p, size of bitcode: %zu)",
75          pBitcode, pBitcodeSize);
76    return NULL;
77  }
78
79  RSInfo::DependencyTableTy dep_info;
80  uint8_t bitcode_sha1[20];
81  Sha1Util::GetSHA1DigestFromBuffer(bitcode_sha1, pBitcode, pBitcodeSize);
82
83  llvm::sys::Path output_path(pCacheDir);
84
85  // {pCacheDir}/{pResName}
86  if (!output_path.appendComponent(pResName)) {
87    ALOGE("Failed to construct output path %s/%s!", pCacheDir, pResName);
88    return NULL;
89  }
90
91  // {pCacheDir}/{pResName}.o
92  output_path.appendSuffix("o");
93
94  dep_info.push(std::make_pair(output_path.c_str(), bitcode_sha1));
95
96  //===--------------------------------------------------------------------===//
97  // Acquire the read lock for reading the Script object file.
98  //===--------------------------------------------------------------------===//
99  FileMutex<FileBase::kReadLock> read_output_mutex(output_path.c_str());
100
101  if (read_output_mutex.hasError() || !read_output_mutex.lock()) {
102    ALOGE("Unable to acquire the read lock for %s! (%s)", output_path.c_str(),
103          read_output_mutex.getErrorMessage().c_str());
104    return NULL;
105  }
106
107  //===--------------------------------------------------------------------===//
108  // Read the output object file.
109  //===--------------------------------------------------------------------===//
110  InputFile *object_file = new (std::nothrow) InputFile(output_path.c_str());
111
112  if ((object_file == NULL) || object_file->hasError()) {
113      //      ALOGE("Unable to open the %s for read! (%s)", output_path.c_str(),
114      //            object_file->getErrorMessage().c_str());
115    delete object_file;
116    return NULL;
117  }
118
119  //===--------------------------------------------------------------------===//
120  // Acquire the read lock on object_file for reading its RS info file.
121  //===--------------------------------------------------------------------===//
122  android::String8 info_path = RSInfo::GetPath(output_path.c_str());
123
124  if (!object_file->lock()) {
125    ALOGE("Unable to acquire the read lock on %s for reading %s! (%s)",
126          output_path.c_str(), info_path.string(),
127          object_file->getErrorMessage().c_str());
128    delete object_file;
129    return NULL;
130  }
131
132 //===---------------------------------------------------------------------===//
133  // Open and load the RS info file.
134  //===--------------------------------------------------------------------===//
135  InputFile info_file(info_path.string());
136  RSInfo *info = RSInfo::ReadFromFile(info_file, dep_info);
137
138  // Release the lock on object_file.
139  object_file->unlock();
140
141  if (info == NULL) {
142    delete object_file;
143    return NULL;
144  }
145
146  //===--------------------------------------------------------------------===//
147  // Create the RSExecutable.
148  //===--------------------------------------------------------------------===//
149  RSExecutable *result = RSExecutable::Create(*info, *object_file, mResolver);
150  if (result == NULL) {
151    delete object_file;
152    delete info;
153    return NULL;
154  }
155
156  return result;
157}
158
159extern llvm::cl::opt<bool> EnableGlobalMerge;
160bool RSCompilerDriver::setupConfig(const RSScript &pScript) {
161  bool changed = false;
162
163  const llvm::CodeGenOpt::Level script_opt_level =
164      static_cast<llvm::CodeGenOpt::Level>(pScript.getOptimizationLevel());
165
166  if (mConfig != NULL) {
167    // Renderscript bitcode may have their optimization flag configuration
168    // different than the previous run of RS compilation.
169    if (mConfig->getOptimizationLevel() != script_opt_level) {
170      mConfig->setOptimizationLevel(script_opt_level);
171      changed = true;
172    }
173  } else {
174    // Haven't run the compiler ever.
175    mConfig = new (std::nothrow) DefaultCompilerConfig();
176    if (mConfig == NULL) {
177      // Return false since mConfig remains NULL and out-of-memory.
178      return false;
179    }
180    mConfig->setOptimizationLevel(script_opt_level);
181    EnableGlobalMerge = mEnableGlobalMerge;
182    changed = true;
183  }
184
185#if defined(DEFAULT_ARM_CODEGEN)
186  // NEON should be disable when full-precision floating point is required.
187  assert((pScript.getInfo() != NULL) && "NULL RS info!");
188  if (pScript.getInfo()->getFloatPrecisionRequirement() == RSInfo::FP_Full) {
189    // Must be ARMCompilerConfig.
190    ARMCompilerConfig *arm_config = static_cast<ARMCompilerConfig *>(mConfig);
191    changed |= arm_config->enableNEON(/* pEnable */false);
192  }
193#endif
194
195  return changed;
196}
197
198Compiler::ErrorCode
199RSCompilerDriver::compileScript(RSScript &pScript,
200                                const char* pScriptName,
201                                const char *pOutputPath,
202                                const char *pRuntimePath,
203                                const RSInfo::DependencyTableTy &pDeps,
204                                bool pSkipLoad, bool pDumpIR) {
205  //android::StopWatch compile_time("bcc: RSCompilerDriver::compileScript time");
206  RSInfo *info = NULL;
207
208  //===--------------------------------------------------------------------===//
209  // Extract RS-specific information from source bitcode.
210  //===--------------------------------------------------------------------===//
211  // RS info may contains configuration (such as #optimization_level) to the
212  // compiler therefore it should be extracted before compilation.
213  info = RSInfo::ExtractFromSource(pScript.getSource(), pDeps);
214  if (info == NULL) {
215    return Compiler::kErrInvalidSource;
216  }
217
218  //===--------------------------------------------------------------------===//
219  // Associate script with its info
220  //===--------------------------------------------------------------------===//
221  // This is required since RS compiler may need information in the info file
222  // to do some transformation (e.g., expand foreach-able function.)
223  pScript.setInfo(info);
224
225  //===--------------------------------------------------------------------===//
226  // Link RS script with Renderscript runtime.
227  //===--------------------------------------------------------------------===//
228  if (!RSScript::LinkRuntime(pScript, pRuntimePath)) {
229    ALOGE("Failed to link script '%s' with Renderscript runtime!", pScriptName);
230    return Compiler::kErrInvalidSource;
231  }
232
233  {
234    // Acquire the write lock for writing output object file.
235    FileMutex<FileBase::kWriteLock> write_output_mutex(pOutputPath);
236
237    if (write_output_mutex.hasError() || !write_output_mutex.lock()) {
238      ALOGE("Unable to acquire the lock for writing %s! (%s)",
239            pOutputPath, write_output_mutex.getErrorMessage().c_str());
240      return Compiler::kErrInvalidSource;
241    }
242
243    // Open the output file for write.
244    OutputFile output_file(pOutputPath, FileBase::kTruncate);
245
246    if (output_file.hasError()) {
247        ALOGE("Unable to open %s for write! (%s)", pOutputPath,
248              output_file.getErrorMessage().c_str());
249      return Compiler::kErrInvalidSource;
250    }
251
252    // Setup the config to the compiler.
253    bool compiler_need_reconfigure = setupConfig(pScript);
254
255    if (mConfig == NULL) {
256      ALOGE("Failed to setup config for RS compiler to compile %s!",
257            pOutputPath);
258      return Compiler::kErrInvalidSource;
259    }
260
261    if (compiler_need_reconfigure) {
262      Compiler::ErrorCode err = mCompiler.config(*mConfig);
263      if (err != Compiler::kSuccess) {
264        ALOGE("Failed to config the RS compiler for %s! (%s)",pOutputPath,
265              Compiler::GetErrorString(err));
266        return Compiler::kErrInvalidSource;
267      }
268    }
269
270    OutputFile *ir_file = NULL;
271    llvm::raw_fd_ostream *IRStream = NULL;
272    if (pDumpIR) {
273      android::String8 path(pOutputPath);
274      path.append(".ll");
275      ir_file = new OutputFile(path.string(), FileBase::kTruncate);
276      IRStream = ir_file->dup();
277    }
278
279    // Run the compiler.
280    Compiler::ErrorCode compile_result = mCompiler.compile(pScript,
281                                                           output_file, IRStream);
282
283    if (ir_file) {
284      ir_file->close();
285      delete ir_file;
286    }
287
288    if (compile_result != Compiler::kSuccess) {
289      ALOGE("Unable to compile the source to file %s! (%s)", pOutputPath,
290            Compiler::GetErrorString(compile_result));
291      return Compiler::kErrInvalidSource;
292    }
293  }
294
295  // No need to produce an RSExecutable in this case.
296  // TODO: Error handling in this case is nonexistent.
297  if (pSkipLoad) {
298    return Compiler::kSuccess;
299  }
300
301  {
302    android::String8 info_path = RSInfo::GetPath(pOutputPath);
303    OutputFile info_file(info_path.string(), FileBase::kTruncate);
304
305    if (info_file.hasError()) {
306      ALOGE("Failed to open the info file %s for write! (%s)",
307            info_path.string(), info_file.getErrorMessage().c_str());
308      return Compiler::kErrInvalidSource;
309    }
310
311    FileMutex<FileBase::kWriteLock> write_info_mutex(info_path.string());
312    if (write_info_mutex.hasError() || !write_info_mutex.lock()) {
313      ALOGE("Unable to acquire the lock for writing %s! (%s)",
314            info_path.string(), write_info_mutex.getErrorMessage().c_str());
315      return Compiler::kErrInvalidSource;
316    }
317
318    // Perform the write.
319    if (!info->write(info_file)) {
320      ALOGE("Failed to sync the RS info file %s!", info_path.string());
321      return Compiler::kErrInvalidSource;
322    }
323  }
324
325  return Compiler::kSuccess;
326}
327
328bool RSCompilerDriver::build(BCCContext &pContext,
329                             const char *pCacheDir,
330                             const char *pResName,
331                             const char *pBitcode,
332                             size_t pBitcodeSize,
333                             const char *pRuntimePath,
334                             RSLinkRuntimeCallback pLinkRuntimeCallback,
335                             bool pDumpIR) {
336    //  android::StopWatch build_time("bcc: RSCompilerDriver::build time");
337  //===--------------------------------------------------------------------===//
338  // Check parameters.
339  //===--------------------------------------------------------------------===//
340  if ((pCacheDir == NULL) || (pResName == NULL)) {
341    ALOGE("Invalid parameter passed to RSCompilerDriver::build()! (cache dir: "
342          "%s, resource name: %s)", ((pCacheDir) ? pCacheDir : "(null)"),
343                                    ((pResName) ? pResName : "(null)"));
344    return false;
345  }
346
347  if ((pBitcode == NULL) || (pBitcodeSize <= 0)) {
348    ALOGE("No bitcode supplied! (bitcode: %p, size of bitcode: %u)",
349          pBitcode, static_cast<unsigned>(pBitcodeSize));
350    return false;
351  }
352
353  //===--------------------------------------------------------------------===//
354  // Prepare dependency information.
355  //===--------------------------------------------------------------------===//
356  RSInfo::DependencyTableTy dep_info;
357  uint8_t bitcode_sha1[20];
358  Sha1Util::GetSHA1DigestFromBuffer(bitcode_sha1, pBitcode, pBitcodeSize);
359
360  //===--------------------------------------------------------------------===//
361  // Construct output path.
362  //===--------------------------------------------------------------------===//
363  llvm::sys::Path output_path(pCacheDir);
364
365  // {pCacheDir}/{pResName}
366  if (!output_path.appendComponent(pResName)) {
367    ALOGE("Failed to construct output path %s/%s!", pCacheDir, pResName);
368    return false;
369  }
370
371  // {pCacheDir}/{pResName}.o
372  output_path.appendSuffix("o");
373
374  dep_info.push(std::make_pair(output_path.c_str(), bitcode_sha1));
375
376  //===--------------------------------------------------------------------===//
377  // Load the bitcode and create script.
378  //===--------------------------------------------------------------------===//
379  Source *source = Source::CreateFromBuffer(pContext, pResName,
380                                            pBitcode, pBitcodeSize);
381  if (source == NULL) {
382    return false;
383  }
384
385  RSScript *script = new (std::nothrow) RSScript(*source);
386  if (script == NULL) {
387    ALOGE("Out of memory when create Script object for '%s'! (output: %s)",
388          pResName, output_path.c_str());
389    delete source;
390    return false;
391  }
392
393  script->setLinkRuntimeCallback(pLinkRuntimeCallback);
394
395  // Read information from bitcode wrapper.
396  bcinfo::BitcodeWrapper wrapper(pBitcode, pBitcodeSize);
397  script->setCompilerVersion(wrapper.getCompilerVersion());
398  script->setOptimizationLevel(static_cast<RSScript::OptimizationLevel>(
399                                   wrapper.getOptimizationLevel()));
400
401  //===--------------------------------------------------------------------===//
402  // Compile the script
403  //===--------------------------------------------------------------------===//
404  Compiler::ErrorCode status = compileScript(*script, pResName,
405                                             output_path.c_str(),
406                                             pRuntimePath, dep_info, false,
407                                             pDumpIR);
408
409  // Script is no longer used. Free it to get more memory.
410  delete script;
411
412  if (status != Compiler::kSuccess) {
413    return false;
414  }
415
416  return true;
417}
418
419
420bool RSCompilerDriver::build(RSScript &pScript, const char *pOut,
421                             const char *pRuntimePath) {
422  RSInfo::DependencyTableTy dep_info;
423  RSInfo *info = RSInfo::ExtractFromSource(pScript.getSource(), dep_info);
424  if (info == NULL) {
425    return false;
426  }
427  pScript.setInfo(info);
428
429  // Embed the info string directly in the ELF, since this path is for an
430  // offline (host) compilation.
431  pScript.setEmbedInfo(true);
432
433  Compiler::ErrorCode status = compileScript(pScript, pOut, pOut, pRuntimePath,
434                                             dep_info, true);
435  if (status != Compiler::kSuccess) {
436    return false;
437  }
438
439  return true;
440}
441
442