RSCompilerDriver.cpp revision fc9c55b0c248a04a325c3540b75ecd3ae64fd91f
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/RSCompilerDriver.h"
18
19#include "Assert.h"
20#include "FileMutex.h"
21#include "InputFile.h"
22#include "Log.h"
23#include "OutputFile.h"
24#include "RSScriptGroupFusion.h"
25
26#include "bcc/BCCContext.h"
27#include "bcc/Compiler.h"
28#include "bcc/CompilerConfig.h"
29#include "bcc/Config.h"
30#include "bcc/Initialization.h"
31#include "bcc/Script.h"
32#include "bcc/Source.h"
33#include "bcinfo/BitcodeWrapper.h"
34#include "bcinfo/MetadataExtractor.h"
35
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/IR/AssemblyAnnotationWriter.h"
38#include <llvm/IR/Module.h>
39#include "llvm/Linker/Linker.h"
40#include <llvm/Support/CommandLine.h>
41#include <llvm/Support/Path.h>
42#include <llvm/Support/raw_ostream.h>
43#include <llvm/Target/TargetMachine.h>
44
45#include <sstream>
46#include <string>
47
48#ifdef __ANDROID__
49#include <cutils/properties.h>
50#endif
51#include <utils/StopWatch.h>
52
53using namespace bcc;
54
55RSCompilerDriver::RSCompilerDriver() :
56    mConfig(nullptr), mCompiler(), mDebugContext(false),
57    mLinkRuntimeCallback(nullptr), mEnableGlobalMerge(true),
58    mEmbedGlobalInfo(false), mEmbedGlobalInfoSkipConstant(false) {
59  init::Initialize();
60}
61
62RSCompilerDriver::~RSCompilerDriver() {
63  delete mConfig;
64}
65
66
67#if defined(PROVIDE_ARM_CODEGEN)
68extern llvm::cl::opt<bool> EnableGlobalMerge;
69#endif
70
71bool RSCompilerDriver::setupConfig(const Script &pScript) {
72  bool changed = false;
73
74  const llvm::CodeGenOpt::Level script_opt_level = pScript.getOptimizationLevel();
75
76#if defined(PROVIDE_ARM_CODEGEN)
77  EnableGlobalMerge = mEnableGlobalMerge;
78#endif
79
80  if (mConfig != nullptr) {
81    // Renderscript bitcode may have their optimization flag configuration
82    // different than the previous run of RS compilation.
83    if (mConfig->getOptimizationLevel() != script_opt_level) {
84      mConfig->setOptimizationLevel(script_opt_level);
85      changed = true;
86    }
87  } else {
88    // Haven't run the compiler ever.
89    mConfig = new (std::nothrow) CompilerConfig(DEFAULT_TARGET_TRIPLE_STRING);
90    if (mConfig == nullptr) {
91      // Return false since mConfig remains NULL and out-of-memory.
92      return false;
93    }
94    mConfig->setOptimizationLevel(script_opt_level);
95    changed = true;
96  }
97
98#if defined(PROVIDE_ARM_CODEGEN)
99  bcinfo::MetadataExtractor me(&pScript.getSource().getModule());
100  if (!me.extract()) {
101    bccAssert("Could not extract RS pragma metadata for module!");
102  }
103
104  bool script_full_prec = (me.getRSFloatPrecision() == bcinfo::RS_FP_Full);
105  if (mConfig->getFullPrecision() != script_full_prec) {
106    mConfig->setFullPrecision(script_full_prec);
107    changed = true;
108  }
109#endif
110
111  return changed;
112}
113
114Compiler::ErrorCode RSCompilerDriver::compileScript(Script& pScript, const char* pScriptName,
115                                                    const char* pOutputPath,
116                                                    const char* pRuntimePath,
117                                                    const char* pBuildChecksum,
118                                                    bool pDumpIR) {
119  // embed build checksum metadata into the source
120  if (pBuildChecksum != nullptr && strlen(pBuildChecksum) > 0) {
121    pScript.getSource().addBuildChecksumMetadata(pBuildChecksum);
122  }
123
124  // Verify that the only external functions in pScript are Renderscript
125  // functions.  Fail if verification returns an error.
126  if (mCompiler.screenGlobalFunctions(pScript) != Compiler::kSuccess) {
127    return Compiler::kErrInvalidSource;
128  }
129
130  // For (32-bit) x86, translate GEPs on structs or arrays of structs to GEPs on
131  // int8* with byte offsets.  This is to ensure that layout of structs with
132  // 64-bit scalar fields matches frontend-generated code that adheres to ARM
133  // data layout.
134  //
135  // The translation is done before RenderScript runtime library is linked
136  // (during LinkRuntime below) to ensure that RenderScript-driver-provided
137  // structs (like Allocation_t) don't get forced into using the ARM layout
138  // rules.
139  if (mCompiler.getTargetMachine().getTargetTriple().getArch() == llvm::Triple::x86) {
140    mCompiler.translateGEPs(pScript);
141  }
142
143  //===--------------------------------------------------------------------===//
144  // Link RS script with Renderscript runtime.
145  //===--------------------------------------------------------------------===//
146  if (!pScript.LinkRuntime(pRuntimePath)) {
147    ALOGE("Failed to link script '%s' with Renderscript runtime %s!",
148          pScriptName, pRuntimePath);
149    return Compiler::kErrInvalidSource;
150  }
151
152  {
153    // FIXME(srhines): Windows compilation can't use locking like this, but
154    // we also don't need to worry about concurrent writers of the same file.
155#ifndef _WIN32
156    //===------------------------------------------------------------------===//
157    // Acquire the write lock for writing output object file.
158    //===------------------------------------------------------------------===//
159    FileMutex write_output_mutex(pOutputPath);
160
161    if (write_output_mutex.hasError() || !write_output_mutex.lockMutex()) {
162      ALOGE("Unable to acquire the lock for writing %s! (%s)",
163            pOutputPath, write_output_mutex.getErrorMessage().c_str());
164      return Compiler::kErrInvalidSource;
165    }
166#endif
167
168    // Open the output file for write.
169    OutputFile output_file(pOutputPath,
170                           FileBase::kTruncate | FileBase::kBinary);
171
172    if (output_file.hasError()) {
173        ALOGE("Unable to open %s for write! (%s)", pOutputPath,
174              output_file.getErrorMessage().c_str());
175      return Compiler::kErrInvalidSource;
176    }
177
178    // Setup the config to the compiler.
179    bool compiler_need_reconfigure = setupConfig(pScript);
180
181    if (mConfig == nullptr) {
182      ALOGE("Failed to setup config for RS compiler to compile %s!",
183            pOutputPath);
184      return Compiler::kErrInvalidSource;
185    }
186
187    if (compiler_need_reconfigure) {
188      Compiler::ErrorCode err = mCompiler.config(*mConfig);
189      if (err != Compiler::kSuccess) {
190        ALOGE("Failed to config the RS compiler for %s! (%s)",pOutputPath,
191              Compiler::GetErrorString(err));
192        return Compiler::kErrInvalidSource;
193      }
194    }
195
196    OutputFile *ir_file = nullptr;
197    llvm::raw_fd_ostream *IRStream = nullptr;
198    if (pDumpIR) {
199      std::string path(pOutputPath);
200      path.append(".ll");
201      ir_file = new OutputFile(path.c_str(), FileBase::kTruncate);
202      IRStream = ir_file->dup();
203    }
204
205    // Run the compiler.
206    Compiler::ErrorCode compile_result =
207        mCompiler.compile(pScript, output_file, IRStream);
208
209    if (ir_file) {
210      ir_file->close();
211      delete ir_file;
212    }
213
214    if (compile_result != Compiler::kSuccess) {
215      ALOGE("Unable to compile the source to file %s! (%s)", pOutputPath,
216            Compiler::GetErrorString(compile_result));
217      return Compiler::kErrInvalidSource;
218    }
219  }
220
221  return Compiler::kSuccess;
222}
223
224bool RSCompilerDriver::build(BCCContext &pContext,
225                             const char *pCacheDir,
226                             const char *pResName,
227                             const char *pBitcode,
228                             size_t pBitcodeSize,
229                             const char *pBuildChecksum,
230                             const char *pRuntimePath,
231                             RSLinkRuntimeCallback pLinkRuntimeCallback,
232                             bool pDumpIR) {
233    //  android::StopWatch build_time("bcc: RSCompilerDriver::build time");
234  //===--------------------------------------------------------------------===//
235  // Check parameters.
236  //===--------------------------------------------------------------------===//
237  if ((pCacheDir == nullptr) || (pResName == nullptr)) {
238    ALOGE("Invalid parameter passed to RSCompilerDriver::build()! (cache dir: "
239          "%s, resource name: %s)", ((pCacheDir) ? pCacheDir : "(null)"),
240                                    ((pResName) ? pResName : "(null)"));
241    return false;
242  }
243
244  if ((pBitcode == nullptr) || (pBitcodeSize <= 0)) {
245    ALOGE("No bitcode supplied! (bitcode: %p, size of bitcode: %u)",
246          pBitcode, static_cast<unsigned>(pBitcodeSize));
247    return false;
248  }
249
250  //===--------------------------------------------------------------------===//
251  // Construct output path.
252  // {pCacheDir}/{pResName}.o
253  //===--------------------------------------------------------------------===//
254  llvm::SmallString<80> output_path(pCacheDir);
255  llvm::sys::path::append(output_path, pResName);
256  llvm::sys::path::replace_extension(output_path, ".o");
257
258  //===--------------------------------------------------------------------===//
259  // Load the bitcode and create script.
260  //===--------------------------------------------------------------------===//
261  Source *source = Source::CreateFromBuffer(pContext, pResName,
262                                            pBitcode, pBitcodeSize);
263  if (source == nullptr) {
264    return false;
265  }
266
267  Script script(source);
268  script.setOptimizationLevel(getConfig()->getOptimizationLevel());
269  if (pLinkRuntimeCallback) {
270    setLinkRuntimeCallback(pLinkRuntimeCallback);
271  }
272
273  script.setLinkRuntimeCallback(getLinkRuntimeCallback());
274
275  script.setEmbedGlobalInfo(mEmbedGlobalInfo);
276  script.setEmbedGlobalInfoSkipConstant(mEmbedGlobalInfoSkipConstant);
277
278  // Read information from bitcode wrapper.
279  bcinfo::BitcodeWrapper wrapper(pBitcode, pBitcodeSize);
280  script.setCompilerVersion(wrapper.getCompilerVersion());
281  script.setOptimizationLevel(static_cast<llvm::CodeGenOpt::Level>(
282                              wrapper.getOptimizationLevel()));
283
284// Assertion-enabled builds can't compile legacy bitcode (due to the use of
285// getName() with anonymous structure definitions).
286#ifdef _DEBUG
287  static const uint32_t kSlangMinimumFixedStructureNames = 2310;
288  uint32_t version = wrapper.getCompilerVersion();
289  if (version < kSlangMinimumFixedStructureNames) {
290    ALOGE("Found invalid legacy bitcode compiled with a version %u llvm-rs-cc "
291          "used with an assertion build", version);
292    ALOGE("Please recompile this apk with a more recent llvm-rs-cc "
293          "(at least %u)", kSlangMinimumFixedStructureNames);
294    return false;
295  }
296#endif
297
298  //===--------------------------------------------------------------------===//
299  // Compile the script
300  //===--------------------------------------------------------------------===//
301  Compiler::ErrorCode status = compileScript(script, pResName,
302                                             output_path.c_str(),
303                                             pRuntimePath,
304                                             pBuildChecksum,
305                                             pDumpIR);
306
307  return status == Compiler::kSuccess;
308}
309
310bool RSCompilerDriver::buildScriptGroup(
311    BCCContext& Context, const char* pOutputFilepath, const char* pRuntimePath,
312    const char* pRuntimeRelaxedPath, bool dumpIR, const char* buildChecksum,
313    const std::vector<Source*>& sources,
314    const std::list<std::list<std::pair<int, int>>>& toFuse,
315    const std::list<std::string>& fused,
316    const std::list<std::list<std::pair<int, int>>>& invokes,
317    const std::list<std::string>& invokeBatchNames) {
318
319  // Read and store metadata before linking the modules together
320  std::vector<bcinfo::MetadataExtractor*> metadata;
321  for (Source* source : sources) {
322    if (!source->extractMetadata()) {
323      ALOGE("Cannot extract metadata from module");
324      return false;
325    }
326  }
327
328  // ---------------------------------------------------------------------------
329  // Link all input modules into a single module
330  // ---------------------------------------------------------------------------
331
332  llvm::LLVMContext& context = Context.getLLVMContext();
333  llvm::Module module("Merged Script Group", context);
334
335  llvm::Linker linker(module);
336  for (Source* source : sources) {
337    std::unique_ptr<llvm::Module> sourceModule(&source->getModule());
338    if (linker.linkInModule(std::move(sourceModule))) {
339      ALOGE("Linking for module in source failed.");
340      return false;
341    }
342    // source->getModule() is destroyed after linking.
343    source->markModuleDestroyed();
344  }
345
346  // ---------------------------------------------------------------------------
347  // Create fused kernels
348  // ---------------------------------------------------------------------------
349
350  auto inputIter = toFuse.begin();
351  for (const std::string& nameOfFused : fused) {
352    auto inputKernels = *inputIter++;
353    std::vector<Source*> sourcesToFuse;
354    std::vector<int> slots;
355
356    for (auto p : inputKernels) {
357      sourcesToFuse.push_back(sources[p.first]);
358      slots.push_back(p.second);
359    }
360
361    if (!fuseKernels(Context, sourcesToFuse, slots, nameOfFused, &module)) {
362      return false;
363    }
364  }
365
366  // ---------------------------------------------------------------------------
367  // Rename invokes
368  // ---------------------------------------------------------------------------
369
370  auto invokeIter = invokes.begin();
371  for (const std::string& newName : invokeBatchNames) {
372    auto inputInvoke = *invokeIter++;
373    auto p = inputInvoke.front();
374    Source* source = sources[p.first];
375    int slot = p.second;
376
377    if (!renameInvoke(Context, source, slot, newName, &module)) {
378      return false;
379    }
380  }
381
382  // ---------------------------------------------------------------------------
383  // Compile the new module with fused kernels
384  // ---------------------------------------------------------------------------
385
386  const std::unique_ptr<Source> source(
387      Source::CreateFromModule(Context, pOutputFilepath, module, true));
388  Script script(source.get());
389
390  // Embed the info string directly in the ELF
391  script.setEmbedInfo(true);
392  // TODO jeanluc Should we override the config's optimization?
393  // i.e., why not script.setOptimizationLevel(getConfig()->getOptimizationLevel)?
394  script.setOptimizationLevel(llvm::CodeGenOpt::Level::Aggressive);
395  script.setEmbedGlobalInfo(mEmbedGlobalInfo);
396  script.setEmbedGlobalInfoSkipConstant(mEmbedGlobalInfoSkipConstant);
397
398  llvm::SmallString<80> output_path(pOutputFilepath);
399  llvm::sys::path::replace_extension(output_path, ".o");
400
401  // Pick the right runtime lib
402  const char* coreLibPath = pRuntimePath;
403  if (strcmp(pRuntimeRelaxedPath, "")) {
404      bcinfo::MetadataExtractor me(&module);
405      me.extract();
406      if (me.getRSFloatPrecision() == bcinfo::RS_FP_Relaxed) {
407          coreLibPath = pRuntimeRelaxedPath;
408      }
409  }
410
411  compileScript(script, pOutputFilepath, output_path.c_str(), coreLibPath,
412                buildChecksum, dumpIR);
413
414  return true;
415}
416
417bool RSCompilerDriver::buildForCompatLib(Script &pScript, const char *pOut,
418                                         const char *pBuildChecksum,
419                                         const char *pRuntimePath,
420                                         bool pDumpIR) {
421  // Embed the info string directly in the ELF, since this path is for an
422  // offline (host) compilation.
423  pScript.setEmbedInfo(true);
424
425  pScript.setEmbedGlobalInfo(mEmbedGlobalInfo);
426  pScript.setEmbedGlobalInfoSkipConstant(mEmbedGlobalInfoSkipConstant);
427  pScript.setLinkRuntimeCallback(getLinkRuntimeCallback());
428
429  Compiler::ErrorCode status = compileScript(pScript, pOut, pOut, pRuntimePath,
430                                             pBuildChecksum, pDumpIR);
431  if (status != Compiler::kSuccess) {
432    return false;
433  }
434
435  return true;
436}
437