1/*
2 * Copyright 2011-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 "bcinfo/BitcodeTranslator.h"
18
19#include "bcinfo/BitcodeWrapper.h"
20
21#include "BitReader_2_7/BitReader_2_7.h"
22#include "BitReader_3_0/BitReader_3_0.h"
23
24#define LOG_TAG "bcinfo"
25#include <cutils/log.h>
26
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/Bitcode/BitstreamWriter.h"
29#include "llvm/Bitcode/ReaderWriter.h"
30#include "llvm/LLVMContext.h"
31#include "llvm/Module.h"
32#include "llvm/Support/MemoryBuffer.h"
33#include "llvm/Support/raw_ostream.h"
34
35#include <cstdlib>
36
37namespace bcinfo {
38
39/**
40 * Define minimum and maximum target API versions. These correspond to the
41 * same API levels used by the standard Android SDK.
42 *
43 * LLVM 2.7
44 *  11 - Honeycomb
45 *  12 - Honeycomb MR1
46 *  13 - Honeycomb MR2
47 *
48 * LLVM 3.0
49 *  14 - Ice Cream Sandwich
50 *  15 - Ice Cream Sandwich MR1
51 *
52 * LLVM 3.1
53 *  16 - Ice Cream Sandwich MR2
54 */
55static const unsigned int kMinimumAPIVersion = 11;
56static const unsigned int kMaximumAPIVersion = BCINFO_API_VERSION;
57static const unsigned int kCurrentAPIVersion = 10000;
58
59/**
60 * The minimum version which does not require translation (i.e. is already
61 * compatible with LLVM's default bitcode reader).
62 */
63static const unsigned int kMinimumUntranslatedVersion = 16;
64static const unsigned int kMinimumCompatibleVersion_LLVM_3_0 = 14;
65static const unsigned int kMinimumCompatibleVersion_LLVM_2_7 = 11;
66
67
68BitcodeTranslator::BitcodeTranslator(const char *bitcode, size_t bitcodeSize,
69                                     unsigned int version)
70    : mBitcode(bitcode), mBitcodeSize(bitcodeSize), mTranslatedBitcode(NULL),
71      mTranslatedBitcodeSize(0), mVersion(version) {
72  return;
73}
74
75
76BitcodeTranslator::~BitcodeTranslator() {
77  if (mVersion < kMinimumUntranslatedVersion) {
78    // We didn't actually do a translation in the alternate case, so deleting
79    // the bitcode would be improper.
80    delete [] mTranslatedBitcode;
81  }
82  mTranslatedBitcode = NULL;
83  return;
84}
85
86
87bool BitcodeTranslator::translate() {
88  if (!mBitcode || !mBitcodeSize) {
89    ALOGE("Invalid/empty bitcode");
90    return false;
91  }
92
93  BitcodeWrapper BCWrapper(mBitcode, mBitcodeSize);
94  if (BCWrapper.getTargetAPI() != mVersion) {
95    ALOGE("Bitcode wrapper (%u) and translator (%u) disagree about target API",
96          BCWrapper.getTargetAPI(), mVersion);
97  }
98
99  if ((mVersion != kCurrentAPIVersion) &&
100      ((mVersion < kMinimumAPIVersion) ||
101       (mVersion > kMaximumAPIVersion))) {
102    ALOGE("Invalid API version: %u is out of range ('%u' - '%u')", mVersion,
103         kMinimumAPIVersion, kMaximumAPIVersion);
104    return false;
105  }
106
107  // We currently don't need to transcode any API version higher than 14 or
108  // the current API version (i.e. 10000)
109  if (mVersion >= kMinimumUntranslatedVersion) {
110    mTranslatedBitcode = mBitcode;
111    mTranslatedBitcodeSize = mBitcodeSize;
112    return true;
113  }
114
115  // Do the actual transcoding by invoking a 2.7-era bitcode reader that can
116  // then write the bitcode back out in a more modern (acceptable) version.
117  llvm::OwningPtr<llvm::LLVMContext> mContext(new llvm::LLVMContext());
118  llvm::OwningPtr<llvm::MemoryBuffer> MEM(
119    llvm::MemoryBuffer::getMemBuffer(
120      llvm::StringRef(mBitcode, mBitcodeSize), "", false));
121  std::string error;
122
123  // Module ownership is handled by the context, so we don't need to free it.
124  llvm::Module *module = NULL;
125
126  if (mVersion >= kMinimumCompatibleVersion_LLVM_3_0) {
127    module = llvm_3_0::ParseBitcodeFile(MEM.get(), *mContext, &error);
128  } else if (mVersion >= kMinimumCompatibleVersion_LLVM_2_7) {
129    module = llvm_2_7::ParseBitcodeFile(MEM.get(), *mContext, &error);
130  } else {
131    ALOGE("No compatible bitcode reader for API version %d", mVersion);
132    return false;
133  }
134
135  if (!module) {
136    ALOGE("Could not parse bitcode file");
137    ALOGE("%s", error.c_str());
138    return false;
139  }
140
141  std::string Buffer;
142
143  llvm::raw_string_ostream OS(Buffer);
144  llvm::WriteBitcodeToFile(module, OS);
145  OS.flush();
146
147  AndroidBitcodeWrapper wrapper;
148  size_t actualWrapperLen = writeAndroidBitcodeWrapper(
149      &wrapper, Buffer.size(), BCWrapper.getTargetAPI(),
150      BCWrapper.getCompilerVersion(), BCWrapper.getOptimizationLevel());
151  if (!actualWrapperLen) {
152    ALOGE("Couldn't produce bitcode wrapper!");
153    return false;
154  }
155
156  mTranslatedBitcodeSize = actualWrapperLen + Buffer.size();
157  char *c = new char[mTranslatedBitcodeSize];
158  memcpy(c, &wrapper, actualWrapperLen);
159  memcpy(c + actualWrapperLen, Buffer.c_str(), Buffer.size());
160
161  mTranslatedBitcode = c;
162
163  return true;
164}
165
166}  // namespace bcinfo
167
168