RSInfoExtractor.cpp revision c5e607adff80a66bc5420baffd299862abdf368d
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//===----------------------------------------------------------------------===//
18// This file implements RSInfo::ExtractFromSource()
19//===----------------------------------------------------------------------===//
20#include "bcc/Renderscript/RSInfo.h"
21
22#include <llvm/IR/Constants.h>
23#include <llvm/IR/Metadata.h>
24#include <llvm/IR/Module.h>
25
26#include "bcc/Source.h"
27#include "bcc/Support/Log.h"
28
29using namespace bcc;
30
31namespace {
32
33// Name of metadata node where pragma info resides (should be synced with
34// slang.cpp)
35const llvm::StringRef pragma_metadata_name("#pragma");
36
37/*
38 * The following names should be synced with the one appeared in
39 * slang_rs_metadata.h.
40 */
41// Name of metadata node where exported variable names reside
42const llvm::StringRef export_var_metadata_name("#rs_export_var");
43
44// Name of metadata node where exported function names reside
45const llvm::StringRef export_func_metadata_name("#rs_export_func");
46
47// Name of metadata node where exported ForEach name information resides
48const llvm::StringRef export_foreach_name_metadata_name("#rs_export_foreach_name");
49
50// Name of metadata node where exported ForEach signature information resides
51const llvm::StringRef export_foreach_metadata_name("#rs_export_foreach");
52
53// Name of metadata node where RS object slot info resides (should be
54const llvm::StringRef object_slot_metadata_name("#rs_object_slots");
55
56inline llvm::StringRef getStringFromOperand(const llvm::Value *pString) {
57  if ((pString != NULL) && (pString->getValueID() == llvm::Value::MDStringVal)) {
58    return static_cast<const llvm::MDString *>(pString)->getString();
59  }
60  return llvm::StringRef();
61}
62
63template<size_t NumOperands>
64inline size_t getMetadataStringLength(const llvm::NamedMDNode *pMetadata) {
65  if (pMetadata == NULL) {
66    return 0;
67  }
68
69  size_t string_size = 0;
70  for (unsigned i = 0, e = pMetadata->getNumOperands(); i < e; i++) {
71    llvm::MDNode *node = pMetadata->getOperand(i);
72    if ((node != NULL) && (node->getNumOperands() >= NumOperands)) {
73      // Compiler try its best to unroll this loop since NumOperands is a
74      // template parameter (therefore the number of iteration can be determined
75      // at compile-time and it's usually small.)
76      for (unsigned j = 0; j < NumOperands; j++) {
77        llvm::StringRef s = getStringFromOperand(node->getOperand(j));
78        if (s.size() > 0) {
79          // +1 is for the null-terminator at the end of string.
80          string_size += (s.size() + 1);
81        }
82      }
83    }
84  }
85
86  return string_size;
87}
88
89// Write a string pString to the string pool pStringPool at offset pWriteStart.
90// Return the pointer the pString resides within the string pool.
91const char *writeString(const llvm::StringRef &pString, char *pStringPool,
92                        off_t *pWriteStart) {
93  if (pString.empty()) {
94    return pStringPool;
95  }
96
97  char *pStringWriteStart = pStringPool + *pWriteStart;
98  // Copy the string.
99  ::memcpy(pStringWriteStart, pString.data(), pString.size());
100  // Write null-terminator at the end of the string.
101  pStringWriteStart[ pString.size() ] = '\0';
102  // Update pWriteStart.
103  *pWriteStart += (pString.size() + 1);
104
105  return pStringWriteStart;
106}
107
108} // end anonymous namespace
109
110RSInfo *RSInfo::ExtractFromSource(const Source &pSource,
111                                  const DependencyHashTy &pSourceHashToEmbed)
112{
113  const llvm::Module &module = pSource.getModule();
114  const char *module_name = module.getModuleIdentifier().c_str();
115
116  const llvm::NamedMDNode *pragma =
117      module.getNamedMetadata(pragma_metadata_name);
118  const llvm::NamedMDNode *export_var =
119      module.getNamedMetadata(export_var_metadata_name);
120  const llvm::NamedMDNode *export_func =
121      module.getNamedMetadata(export_func_metadata_name);
122  const llvm::NamedMDNode *export_foreach_name =
123      module.getNamedMetadata(export_foreach_name_metadata_name);
124  const llvm::NamedMDNode *export_foreach_signature =
125      module.getNamedMetadata(export_foreach_metadata_name);
126  const llvm::NamedMDNode *object_slots =
127      module.getNamedMetadata(object_slot_metadata_name);
128
129  // Always write a byte 0x0 at the beginning of the string pool.
130  size_t string_pool_size = 1;
131  off_t cur_string_pool_offset = 0;
132
133  RSInfo *result = NULL;
134
135  // Handle legacy case for pre-ICS bitcode that doesn't contain a metadata
136  // section for ForEach. We generate a full signature for a "root" function.
137  if ((export_foreach_name == NULL) || (export_foreach_signature == NULL)) {
138    export_foreach_name = NULL;
139    export_foreach_signature = NULL;
140    string_pool_size += 5;  // insert "root\0" for #rs_export_foreach_name
141  }
142
143  string_pool_size += getMetadataStringLength<2>(pragma);
144  string_pool_size += getMetadataStringLength<1>(export_var);
145  string_pool_size += getMetadataStringLength<1>(export_func);
146  string_pool_size += getMetadataStringLength<1>(export_foreach_name);
147
148  // Reserve the space for the source hash.
149  string_pool_size += SHA1_DIGEST_LENGTH;
150
151  // Allocate result object
152  result = new (std::nothrow) RSInfo(string_pool_size);
153  if (result == NULL) {
154    ALOGE("Out of memory when create RSInfo object for %s!", module_name);
155    goto bail;
156  }
157
158  // Check string pool.
159  if (result->mStringPool == NULL) {
160    ALOGE("Out of memory when allocate string pool in RSInfo object for %s!",
161          module_name);
162    goto bail;
163  }
164
165  // First byte of string pool should be an empty string
166  result->mStringPool[ cur_string_pool_offset++ ] = '\0';
167
168  // Populate all the strings and data.
169#define FOR_EACH_NODE_IN(_metadata, _node)  \
170  for (unsigned i = 0, e = (_metadata)->getNumOperands(); i != e; i++)  \
171    if (((_node) = (_metadata)->getOperand(i)) != NULL)
172  //===--------------------------------------------------------------------===//
173  // #pragma
174  //===--------------------------------------------------------------------===//
175  // Pragma is actually a key-value pair. The value can be an empty string while
176  // the key cannot.
177  if (pragma != NULL) {
178    llvm::MDNode *node;
179    FOR_EACH_NODE_IN(pragma, node) {
180        llvm::StringRef key = getStringFromOperand(node->getOperand(0));
181        llvm::StringRef val = getStringFromOperand(node->getOperand(1));
182        if (key.empty()) {
183          ALOGW("%s contains pragma metadata with empty key (skip)!",
184                module_name);
185        } else {
186          result->mPragmas.push(std::make_pair(
187              writeString(key, result->mStringPool, &cur_string_pool_offset),
188              writeString(val, result->mStringPool, &cur_string_pool_offset)));
189        } // key.empty()
190    } // FOR_EACH_NODE_IN
191  } // pragma != NULL
192
193  //===--------------------------------------------------------------------===//
194  // #rs_export_var
195  //===--------------------------------------------------------------------===//
196  if (export_var != NULL) {
197    llvm::MDNode *node;
198    FOR_EACH_NODE_IN(export_var, node) {
199      llvm::StringRef name = getStringFromOperand(node->getOperand(0));
200      if (name.empty()) {
201        ALOGW("%s contains empty entry in #rs_export_var metadata (skip)!",
202              module_name);
203      } else {
204          result->mExportVarNames.push(
205              writeString(name, result->mStringPool, &cur_string_pool_offset));
206      }
207    }
208  }
209
210  //===--------------------------------------------------------------------===//
211  // #rs_export_func
212  //===--------------------------------------------------------------------===//
213  if (export_func != NULL) {
214    llvm::MDNode *node;
215    FOR_EACH_NODE_IN(export_func, node) {
216      llvm::StringRef name = getStringFromOperand(node->getOperand(0));
217      if (name.empty()) {
218        ALOGW("%s contains empty entry in #rs_export_func metadata (skip)!",
219              module_name);
220      } else {
221        result->mExportFuncNames.push(
222            writeString(name, result->mStringPool, &cur_string_pool_offset));
223      }
224    }
225  }
226
227  //===--------------------------------------------------------------------===//
228  // #rs_export_foreach and #rs_export_foreach_name
229  //===--------------------------------------------------------------------===//
230  // It's a little bit complicated to deal with #rs_export_foreach (the
231  // signature of foreach-able function) and #rs_export_foreach_name (the name
232  // of function which is foreach-able). We have to maintain a legacy case:
233  //
234  //  In pre-ICS bitcode, forEach feature only supports non-graphic root()
235  //  function and only one signature corresponded to that non-graphic root()
236  //  was written to the #rs_export_foreach metadata section. There's no
237  //  #rs_export_foreach_name metadata section.
238  //
239  // Currently, not only non-graphic root() is supported but also other
240  // functions that are exportable. Therefore, a new metadata section
241  // #rs_export_foreach_name is added to specify which functions are
242  // for-eachable. In this case, #rs_export_foreach (the function name) and
243  // #rs_export_foreach metadata (the signature) is one-to-one mapping among
244  // their entries.
245  if ((export_foreach_name != NULL) && (export_foreach_signature != NULL)) {
246    unsigned num_foreach_function;
247
248    // Should be one-to-one mapping.
249    if (export_foreach_name->getNumOperands() !=
250        export_foreach_signature->getNumOperands()) {
251      ALOGE("Mismatch number of foreach-able function names (%u) in "
252            "#rs_export_foreach_name and number of signatures (%u) "
253            "in %s!", export_foreach_name->getNumOperands(),
254            export_foreach_signature->getNumOperands(), module_name);
255      goto bail;
256    }
257
258    num_foreach_function = export_foreach_name->getNumOperands();
259    for (unsigned i = 0; i < num_foreach_function; i++) {
260      llvm::MDNode *name_node = export_foreach_name->getOperand(i);
261      llvm::MDNode *signature_node = export_foreach_signature->getOperand(i);
262
263      llvm::StringRef name, signature_string;
264      if (name_node != NULL) {
265        name = getStringFromOperand(name_node->getOperand(0));
266      }
267      if (signature_node != NULL) {
268        signature_string = getStringFromOperand(signature_node->getOperand(0));
269      }
270
271      if (!name.empty() && !signature_string.empty()) {
272        // Both name_node and signature_node are not NULL nodes.
273        uint32_t signature;
274        if (signature_string.getAsInteger(10, signature)) {
275          ALOGE("Non-integer signature value '%s' for function %s found in %s!",
276                signature_string.str().c_str(), name.str().c_str(), module_name);
277          goto bail;
278        }
279        result->mExportForeachFuncs.push(std::make_pair(
280              writeString(name, result->mStringPool, &cur_string_pool_offset),
281              signature));
282      } else {
283        // One or both of the name and signature value are empty. It's safe only
284        // if both of them are empty.
285        if (name.empty() && signature_string.empty()) {
286          ALOGW("Entries #%u at #rs_export_foreach_name and #rs_export_foreach"
287                " are both NULL in %s! (skip)", i, module_name);
288          continue;
289        } else {
290          ALOGE("Entries #%u at %s is NULL in %s! (skip)", i,
291                (name.empty() ? "#rs_export_foreach_name" :
292                                "#rs_export_foreach"), module_name);
293          goto bail;
294        }
295      }
296    } // end for
297  } else {
298    // To handle the legacy case, we generate a full signature for a "root"
299    // function which means that we need to set the bottom 5 bits (0x1f) in the
300    // mask.
301    result->mExportForeachFuncs.push(std::make_pair(
302          writeString(llvm::StringRef("root"), result->mStringPool,
303                      &cur_string_pool_offset), 0x1f));
304  }
305
306  //===--------------------------------------------------------------------===//
307  // #rs_object_slots
308  //===--------------------------------------------------------------------===//
309  if (object_slots != NULL) {
310    llvm::MDNode *node;
311    for (unsigned int i = 0; i <= export_var->getNumOperands(); i++) {
312      result->mObjectSlots.push(0);
313    }
314    FOR_EACH_NODE_IN(object_slots, node) {
315      llvm::StringRef val = getStringFromOperand(node->getOperand(0));
316      if (val.empty()) {
317        ALOGW("%s contains empty entry in #rs_object_slots (skip)!",
318              module.getModuleIdentifier().c_str());
319      } else {
320        uint32_t slot;
321        if (val.getAsInteger(10, slot)) {
322          ALOGE("Non-integer object slot value '%s' in %s!", val.str().c_str(),
323                module.getModuleIdentifier().c_str());
324          goto bail;
325        } else {
326          result->mObjectSlots.editItemAt(slot) = 1;
327        }
328      }
329    }
330  }
331#undef FOR_EACH_NODE_IN
332
333  //===------------------------------------------------------------------===//
334  // Record dependency information.
335  //===------------------------------------------------------------------===//
336  {
337      // Store the SHA-1 in the string pool but without a null-terminator.
338      result->mHeader.sourceSha1Idx = cur_string_pool_offset;
339      uint8_t* sha1 = reinterpret_cast<uint8_t*>(result->mStringPool + cur_string_pool_offset);
340      ::memcpy(sha1, pSourceHashToEmbed, SHA1_DIGEST_LENGTH);
341      // Update the string pool pointer.
342      cur_string_pool_offset += SHA1_DIGEST_LENGTH;
343      result->mSourceHash = sha1;
344  }
345
346  //===--------------------------------------------------------------------===//
347  // Determine whether the bitcode contains debug information
348  //===--------------------------------------------------------------------===//
349  // The root context of the debug information in the bitcode is put under
350  // the metadata named "llvm.dbg.cu".
351  result->mHeader.hasDebugInformation =
352      static_cast<uint8_t>(module.getNamedMetadata("llvm.dbg.cu") != NULL);
353
354  assert((cur_string_pool_offset == string_pool_size) &&
355            "Unexpected string pool size!");
356
357  return result;
358
359bail:
360  delete result;
361  return NULL;
362}
363