blob: 5846c0c7909ebde1fb83c9a57068daf35ab91d9d [file] [log] [blame]
Jean-Luc Brouillet36090672015-04-07 15:15:53 -07001/*
2 * Copyright (C) 2015 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 <algorithm>
Yang Ni12398d82015-09-18 14:57:07 -070018#include <climits>
Jean-Luc Brouillet36090672015-04-07 15:15:53 -070019#include <iostream>
20#include <iterator>
21#include <sstream>
22
23#include "Generator.h"
24#include "Specification.h"
25#include "Utilities.h"
26
27using namespace std;
28
Yang Ni12398d82015-09-18 14:57:07 -070029const unsigned int kMinimumApiLevelForTests = 11;
30const unsigned int kApiLevelWithFirst64Bit = 21;
Jean-Luc Brouillet36090672015-04-07 15:15:53 -070031
32// Used to map the built-in types to their mangled representations
33struct BuiltInMangling {
34 const char* token[3]; // The last two entries can be nullptr
35 const char* equivalence; // The mangled equivalent
36};
37
38BuiltInMangling builtInMangling[] = {
39 {{"long", "long"}, "x"},
40 {{"unsigned", "long", "long"}, "y"},
41 {{"long"}, "l"},
42 {{"unsigned", "long"}, "m"},
43 {{"int"}, "i"},
44 {{"unsigned", "int"}, "j"},
45 {{"short"}, "s"},
46 {{"unsigned", "short"}, "t"},
47 {{"char"}, "c"},
48 {{"unsigned", "char"}, "h"},
49 {{"signed", "char"}, "a"},
50 {{"void"}, "v"},
51 {{"wchar_t"}, "w"},
52 {{"bool"}, "b"},
53 {{"__fp16"}, "Dh"},
54 {{"float"}, "f"},
55 {{"double"}, "d"},
56};
57
58/* For the given API level and bitness (e.g. 32 or 64 bit), try to find a
59 * substitution for the provided type name, as would be done (mostly) by a
60 * preprocessor. Returns empty string if there's no substitution.
61 */
Yang Ni12398d82015-09-18 14:57:07 -070062static string findSubstitute(const string& typeName, unsigned int apiLevel, int intSize) {
Jean-Luc Brouillet36090672015-04-07 15:15:53 -070063 const auto& types = systemSpecification.getTypes();
64 const auto type = types.find(typeName);
65 if (type != types.end()) {
66 for (TypeSpecification* spec : type->second->getSpecifications()) {
67 // Verify this specification applies
68 const VersionInfo info = spec->getVersionInfo();
69 if (!info.includesVersion(apiLevel) || (info.intSize != 0 && info.intSize != intSize)) {
70 continue;
71 }
72 switch (spec->getKind()) {
73 case SIMPLE: {
Stephen Hinesca51c782015-08-25 23:43:34 -070074 return spec->getSimpleType();
75 }
76 case RS_OBJECT: {
77 // Do nothing for RS object types.
Jean-Luc Brouillet36090672015-04-07 15:15:53 -070078 break;
79 }
80 case STRUCT: {
Stephen Hinesca51c782015-08-25 23:43:34 -070081 return spec->getStructName();
Jean-Luc Brouillet36090672015-04-07 15:15:53 -070082 }
83 case ENUM:
84 // Do nothing
85 break;
86 }
87 }
88 }
89 return "";
90}
91
92/* Expand the typedefs found in 'type' into their equivalents and tokenize
93 * the resulting list. 'apiLevel' and 'intSize' specifies the API level and bitness
94 * we are currently processing.
95 */
Yang Ni12398d82015-09-18 14:57:07 -070096list<string> expandTypedefs(const string type, unsigned int apiLevel, int intSize) {
Jean-Luc Brouillet36090672015-04-07 15:15:53 -070097 // Split the string in tokens.
98 istringstream stream(type);
99 list<string> tokens{istream_iterator<string>{stream}, istream_iterator<string>{}};
100 // Try to substitue each token.
101 for (auto i = tokens.begin(); i != tokens.end();) {
102 const string substitute = findSubstitute(*i, apiLevel, intSize);
103 if (substitute.empty()) {
104 // No substitution possible, just go to the next token.
105 i++;
106 } else {
107 // Split the replacement string in tokens.
108 istringstream stream(substitute);
109 list<string> newTokens{istream_iterator<string>{stream}, istream_iterator<string>{}};
110 // Replace the token with the substitution. Don't advance, as the new substitution
111 // might itself be replaced.
112 auto prev = i;
113 --prev;
114 tokens.insert(i, newTokens.begin(), newTokens.end());
115 tokens.erase(i);
116 advance(i, -newTokens.size());
117 }
118 }
119 return tokens;
120}
121
122// Remove the first element of the list if it equals 'prefix'. Return true in that case.
123static bool eatFront(list<string>* tokens, const char* prefix) {
124 if (tokens->front() == prefix) {
125 tokens->pop_front();
126 return true;
127 }
128 return false;
129}
130
131/* Search the table of translations for the built-ins for the mangling that
132 * corresponds to this list of tokens. If a match is found, consume these tokens
133 * and return a pointer to the string. If not, return nullptr.
134 */
135static const char* findManglingOfBuiltInType(list<string>* tokens) {
136 for (const BuiltInMangling& a : builtInMangling) {
137 auto t = tokens->begin();
138 auto end = tokens->end();
139 bool match = true;
140 // We match up to three tokens.
141 for (int i = 0; i < 3; i++) {
142 if (!a.token[i]) {
143 // No more tokens
144 break;
145 }
146 if (t == end || *t++ != a.token[i]) {
147 match = false;
148 }
149 }
150 if (match) {
151 tokens->erase(tokens->begin(), t);
152 return a.equivalence;
153 }
154 }
155 return nullptr;
156}
157
158// Mangle a long name by prefixing it with its length, e.g. "13rs_allocation".
159static inline string mangleLongName(const string& name) {
160 return to_string(name.size()) + name;
161}
162
163/* Mangle the type name that's represented by the vector size and list of tokens.
164 * The mangling will be returned in full form in 'mangling'. 'compressedMangling'
165 * will have the compressed equivalent. This is built using the 'previousManglings'
166 * list. false is returned if an error is encountered.
167 *
168 * This function is recursive because compression is possible at each level of the definition.
169 * See http://mentorembedded.github.io/cxx-abi/abi.html#mangle.type for a description
170 * of the Itanium mangling used by llvm.
171 *
172 * This function mangles correctly the types currently used by RenderScript. It does
173 * not currently mangle more complicated types like function pointers, namespaces,
174 * or other C++ types. In particular, we don't deal correctly with parenthesis.
175 */
176static bool mangleType(string vectorSize, list<string>* tokens, vector<string>* previousManglings,
177 string* mangling, string* compressedMangling) {
178 string delta; // The part of the mangling we're generating for this recursion.
179 bool isTerminal = false; // True if this iteration parses a terminal node in the production.
180 bool canBeCompressed = true; // Will be false for manglings of builtins.
181
182 if (tokens->back() == "*") {
183 delta = "P";
184 tokens->pop_back();
185 } else if (eatFront(tokens, "const")) {
186 delta = "K";
187 } else if (eatFront(tokens, "volatile")) {
188 delta = "V";
189 } else if (vectorSize != "1" && vectorSize != "") {
190 // For vector, prefix with the abbreviation for a vector, including the size.
191 delta = "Dv" + vectorSize + "_";
192 vectorSize.clear(); // Reset to mark the size as consumed.
193 } else if (eatFront(tokens, "struct")) {
194 // For a structure, we just use the structure name
195 if (tokens->size() == 0) {
196 cerr << "Expected a name after struct\n";
197 return false;
198 }
199 delta = mangleLongName(tokens->front());
200 isTerminal = true;
201 tokens->pop_front();
Yang Nifab69472015-11-10 15:41:03 -0800202 } else if (eatFront(tokens, "...")) {
203 delta = "z";
204 isTerminal = true;
Jean-Luc Brouillet36090672015-04-07 15:15:53 -0700205 } else {
206 const char* c = findManglingOfBuiltInType(tokens);
207 if (c) {
208 // It's a basic type. We don't use those directly for compression.
209 delta = c;
210 isTerminal = true;
211 canBeCompressed = false;
212 } else if (tokens->size() > 0) {
213 // It's a complex type name.
214 delta = mangleLongName(tokens->front());
215 isTerminal = true;
216 tokens->pop_front();
217 }
218 }
219
220 if (isTerminal) {
221 // If we're the terminal node, there should be nothing left to mangle.
222 if (tokens->size() > 0) {
223 cerr << "Expected nothing else but found";
224 for (const auto& t : *tokens) {
225 cerr << " " << t;
226 }
227 cerr << "\n";
228 return false;
229 }
230 *mangling = delta;
231 *compressedMangling = delta;
232 } else {
233 // We're not terminal. Recurse and prefix what we've translated this pass.
234 if (tokens->size() == 0) {
235 cerr << "Expected a more complete type\n";
236 return false;
237 }
238 string rest, compressedRest;
239 if (!mangleType(vectorSize, tokens, previousManglings, &rest, &compressedRest)) {
240 return false;
241 }
242 *mangling = delta + rest;
243 *compressedMangling = delta + compressedRest;
244 }
245
246 /* If it's a built-in type, we don't look at previously emitted ones and we
247 * don't keep track of it.
248 */
249 if (!canBeCompressed) {
250 return true;
251 }
252
253 // See if we've encountered this mangling before.
254 for (size_t i = 0; i < previousManglings->size(); ++i) {
255 if ((*previousManglings)[i] == *mangling) {
256 // We have a match, construct an index reference to that previously emitted mangling.
257 ostringstream stream2;
258 stream2 << 'S';
259 if (i > 0) {
260 stream2 << (char)('0' + i - 1);
261 }
262 stream2 << '_';
263 *compressedMangling = stream2.str();
264 return true;
265 }
266 }
267
268 // We have not encountered this before. Add it to the list.
269 previousManglings->push_back(*mangling);
270 return true;
271}
272
273// Write to the stream the mangled representation of each parameter.
274static bool writeParameters(ostringstream* stream, const std::vector<ParameterDefinition*>& params,
Yang Ni12398d82015-09-18 14:57:07 -0700275 unsigned int apiLevel, int intSize) {
Jean-Luc Brouillet36090672015-04-07 15:15:53 -0700276 if (params.empty()) {
277 *stream << "v";
278 return true;
279 }
280 /* We keep track of the previously generated parameter types, as type mangling
281 * is compressed by reusing previous manglings.
282 */
283 vector<string> previousManglings;
284 for (ParameterDefinition* p : params) {
285 // Expand the typedefs and create a tokenized list.
286 list<string> tokens = expandTypedefs(p->rsType, apiLevel, intSize);
287 if (p->isOutParameter) {
288 tokens.push_back("*");
289 }
290 string mangling, compressedMangling;
291 if (!mangleType(p->mVectorSize, &tokens, &previousManglings, &mangling,
292 &compressedMangling)) {
293 return false;
294 }
295 *stream << compressedMangling;
296 }
297 return true;
298}
299
300/* Add the mangling for this permutation of the function. apiLevel and intSize is used
301 * to select the correct type when expanding complex type.
302 */
303static bool addFunctionManglingToSet(const Function& function,
304 const FunctionPermutation& permutation, bool overloadable,
Yang Ni12398d82015-09-18 14:57:07 -0700305 unsigned int apiLevel, int intSize, set<string>* allManglings) {
Jean-Luc Brouillet36090672015-04-07 15:15:53 -0700306 const string& functionName = permutation.getName();
307 string mangling;
308 if (overloadable) {
309 ostringstream stream;
310 stream << "_Z" << mangleLongName(functionName);
311 if (!writeParameters(&stream, permutation.getParams(), apiLevel, intSize)) {
312 cerr << "Error mangling " << functionName << ". See above message.\n";
313 return false;
314 }
315 mangling = stream.str();
316 } else {
317 mangling = functionName;
318 }
319 allManglings->insert(mangling);
320 return true;
321}
322
323/* Add to the set the mangling of each function prototype that can be generated from this
324 * specification, i.e. for all the versions covered and for 32/64 bits. We call this
325 * for each API level because the implementation of a type may have changed in the range
326 * of API levels covered.
327 */
328static bool addManglingsForSpecification(const Function& function,
Yang Ni12398d82015-09-18 14:57:07 -0700329 const FunctionSpecification& spec, unsigned int lastApiLevel,
Jean-Luc Brouillet36090672015-04-07 15:15:53 -0700330 set<string>* allManglings) {
331 // If the function is inlined, we won't generate an unresolved external for that.
332 if (spec.hasInline()) {
333 return true;
334 }
335 const VersionInfo info = spec.getVersionInfo();
Yang Ni12398d82015-09-18 14:57:07 -0700336 unsigned int minApiLevel, maxApiLevel;
337 minApiLevel = info.minVersion ? info.minVersion : kMinimumApiLevelForTests;
338 maxApiLevel = info.maxVersion ? info.maxVersion : lastApiLevel;
Jean-Luc Brouillet36090672015-04-07 15:15:53 -0700339 const bool overloadable = spec.isOverloadable();
340
341 /* We track success rather than aborting early in case of failure so that we
342 * generate all the error messages.
343 */
344 bool success = true;
Yang Ni12398d82015-09-18 14:57:07 -0700345 // Use 64-bit integer here for the loop count to avoid overflow
346 // (minApiLevel == maxApiLevel == UINT_MAX for unreleased API)
347 for (int64_t apiLevel = minApiLevel; apiLevel <= maxApiLevel; ++apiLevel) {
Jean-Luc Brouillet36090672015-04-07 15:15:53 -0700348 for (auto permutation : spec.getPermutations()) {
349 if (info.intSize == 0 || info.intSize == 32) {
350 if (!addFunctionManglingToSet(function, *permutation, overloadable, apiLevel, 32,
351 allManglings)) {
352 success = false;
353 }
354 }
355 if (apiLevel >= kApiLevelWithFirst64Bit && (info.intSize == 0 || info.intSize == 64)) {
356 if (!addFunctionManglingToSet(function, *permutation, overloadable, apiLevel, 64,
357 allManglings)) {
358 success = false;
359 }
360 }
361 }
362 }
363 return success;
364}
365
366/* Generate the white list file of the mangled function prototypes. This generated list is used
367 * to validate unresolved external references. 'lastApiLevel' is the largest api level found in
368 * all spec files.
369 */
Yang Ni12398d82015-09-18 14:57:07 -0700370static bool generateWhiteListFile(unsigned int lastApiLevel) {
Jean-Luc Brouillet36090672015-04-07 15:15:53 -0700371 bool success = true;
372 // We generate all the manglings in a set to remove duplicates and to order them.
373 set<string> allManglings;
374 for (auto f : systemSpecification.getFunctions()) {
375 const Function* function = f.second;
376 for (auto spec : function->getSpecifications()) {
Yang Ni12398d82015-09-18 14:57:07 -0700377 // Compiler intrinsics are not runtime APIs. Do not include them in the whitelist.
378 if (spec->isIntrinsic()) {
379 continue;
380 }
Jean-Luc Brouillet36090672015-04-07 15:15:53 -0700381 if (!addManglingsForSpecification(*function, *spec, lastApiLevel, &allManglings)) {
382 success = false; // We continue so we can generate all errors.
383 }
384 }
385 }
386
387 if (success) {
388 GeneratedFile file;
389 if (!file.start(".", "RSStubsWhiteList.cpp")) {
390 return false;
391 }
392
393 file.writeNotices();
394 file << "#include \"RSStubsWhiteList.h\"\n\n";
395 file << "std::vector<std::string> stubList = {\n";
396 for (const auto& e : allManglings) {
397 file << "\"" << e << "\",\n";
398 }
399 file << "};\n";
400 }
401 return success;
402}
403
404// Add a uniquely named variable definition to the file and return its name.
405static const string addVariable(GeneratedFile* file, unsigned int* variableNumber) {
406 const string name = "buf" + to_string((*variableNumber)++);
407 /* Some data structures like rs_tm can't be exported. We'll just use a dumb buffer
408 * and cast its address later on.
409 */
410 *file << "char " << name << "[200];\n";
411 return name;
412}
413
414/* Write to the file the globals needed to make the call for this permutation. The actual
415 * call is stored in 'calls', as we'll need to generate all the global variable declarations
416 * before the function definition.
417 */
418static void generateTestCall(GeneratedFile* file, ostringstream* calls,
419 unsigned int* variableNumber, const Function& function,
420 const FunctionPermutation& permutation) {
421 *calls << " ";
422
423 // Handle the return type.
424 const auto ret = permutation.getReturn();
425 if (ret && ret->rsType != "void" && ret->rsType != "const void") {
426 *calls << "*(" << ret->rsType << "*)" << addVariable(file, variableNumber) << " = ";
427 }
428
429 *calls << permutation.getName() << "(";
430
431 // Generate the arguments.
432 const char* separator = "";
433 for (auto p : permutation.getParams()) {
434 *calls << separator;
Jean-Luc Brouillet36090672015-04-07 15:15:53 -0700435 if (p->rsType == "rs_kernel_context") {
Yang Ni8ba23102016-02-01 16:20:41 -0800436 // Special case for the kernel context, as it has a special existence.
Jean-Luc Brouillet4324eec2015-08-07 16:58:38 -0700437 *calls << "context";
Yang Ni8ba23102016-02-01 16:20:41 -0800438 } else if (p->rsType == "...") {
439 // Special case for varargs. No need for casting.
440 *calls << addVariable(file, variableNumber);
Jean-Luc Brouillet36090672015-04-07 15:15:53 -0700441 } else if (p->isOutParameter) {
442 *calls << "(" << p->rsType << "*) " << addVariable(file, variableNumber);
443 } else {
444 *calls << "*(" << p->rsType << "*)" << addVariable(file, variableNumber);
445 }
446 separator = ", ";
447 }
448 *calls << ");\n";
449}
450
451/* Generate a test file that will be used in the frameworks/compile/slang/tests unit tests.
452 * This file tests that all RenderScript APIs can be called for the specified API level.
453 * To avoid the compiler agressively pruning out our calls, we use globals as inputs and outputs.
454 *
455 * Since some structures can't be defined at the global level, we use casts of simple byte
456 * buffers to get around that restriction.
457 *
458 * This file can be used to verify the white list that's also generated in this file. To do so,
459 * run "llvm-nm -undefined-only -just-symbol-name" on the resulting bit code.
460 */
Yang Ni12398d82015-09-18 14:57:07 -0700461static bool generateApiTesterFile(const string& slangTestDirectory, unsigned int apiLevel) {
Jean-Luc Brouillet36090672015-04-07 15:15:53 -0700462 GeneratedFile file;
463 if (!file.start(slangTestDirectory, "all" + to_string(apiLevel) + ".rs")) {
464 return false;
465 }
466
467 /* This unusual comment is used by slang/tests/test.py to know which parameter to pass
468 * to llvm-rs-cc when compiling the test.
469 */
470 file << "// -target-api " << apiLevel << " -Wno-deprecated-declarations\n";
471
472 file.writeNotices();
473 file << "#pragma version(1)\n";
474 file << "#pragma rs java_package_name(com.example.renderscript.testallapi)\n\n";
475 if (apiLevel < 23) { // All rs_graphics APIs were deprecated in api level 23.
476 file << "#include \"rs_graphics.rsh\"\n\n";
477 }
478
479 /* The code below emits globals and calls to functions in parallel. We store
480 * the calls in a stream so that we can emit them in the file in the proper order.
481 */
482 ostringstream calls;
483 unsigned int variableNumber = 0; // Used to generate unique names.
484 for (auto f : systemSpecification.getFunctions()) {
485 const Function* function = f.second;
486 for (auto spec : function->getSpecifications()) {
Yang Ni12398d82015-09-18 14:57:07 -0700487 // Do not include internal APIs in the API tests.
488 if (spec->isInternal()) {
489 continue;
490 }
Jean-Luc Brouillet36090672015-04-07 15:15:53 -0700491 VersionInfo info = spec->getVersionInfo();
492 if (!info.includesVersion(apiLevel)) {
493 continue;
494 }
495 if (info.intSize == 32) {
496 calls << "#ifndef __LP64__\n";
497 } else if (info.intSize == 64) {
498 calls << "#ifdef __LP64__\n";
499 }
500 for (auto permutation : spec->getPermutations()) {
501 generateTestCall(&file, &calls, &variableNumber, *function, *permutation);
502 }
503 if (info.intSize != 0) {
504 calls << "#endif\n";
505 }
506 }
507 }
508 file << "\n";
509
510 // Modify the style of kernel as required by the API level.
511 if (apiLevel >= 23) {
Jean-Luc Brouillet4324eec2015-08-07 16:58:38 -0700512 file << "void RS_KERNEL test(int in, rs_kernel_context context) {\n";
Jean-Luc Brouillet36090672015-04-07 15:15:53 -0700513 } else if (apiLevel >= 17) {
514 file << "void RS_KERNEL test(int in) {\n";
515 } else {
516 file << "void root(const int* in) {\n";
517 }
518 file << calls.str();
519 file << "}\n";
520
521 return true;
522}
523
Yang Ni12398d82015-09-18 14:57:07 -0700524bool generateStubsWhiteList(const string& slangTestDirectory, unsigned int maxApiLevel) {
525 unsigned int lastApiLevel = min(systemSpecification.getMaximumApiLevel(), maxApiLevel);
Jean-Luc Brouillet36090672015-04-07 15:15:53 -0700526 if (!generateWhiteListFile(lastApiLevel)) {
527 return false;
528 }
529 // Generate a test file for each apiLevel.
Yang Ni12398d82015-09-18 14:57:07 -0700530 for (unsigned int i = kMinimumApiLevelForTests; i <= lastApiLevel; ++i) {
Jean-Luc Brouillet36090672015-04-07 15:15:53 -0700531 if (!generateApiTesterFile(slangTestDirectory, i)) {
532 return false;
533 }
534 }
535 return true;
536}