slang_rs_context.cpp revision d3f7527b105d21f1c69d3473eb88a762f2c3ab5a
1/*
2 * Copyright 2010-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 "slang_rs_context.h"
18
19#include <string>
20
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/Decl.h"
23#include "clang/AST/DeclBase.h"
24#include "clang/AST/Mangle.h"
25#include "clang/AST/Type.h"
26
27#include "clang/Basic/Linkage.h"
28#include "clang/Basic/TargetInfo.h"
29
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/DataLayout.h"
32
33#include "slang.h"
34#include "slang_assert.h"
35#include "slang_rs_export_foreach.h"
36#include "slang_rs_export_func.h"
37#include "slang_rs_export_type.h"
38#include "slang_rs_export_var.h"
39#include "slang_rs_exportable.h"
40#include "slang_rs_pragma_handler.h"
41#include "slang_rs_reflection.h"
42
43namespace slang {
44
45RSContext::RSContext(clang::Preprocessor &PP,
46                     clang::ASTContext &Ctx,
47                     const clang::TargetInfo &Target,
48                     PragmaList *Pragmas,
49                     unsigned int TargetAPI,
50                     std::vector<std::string> *GeneratedFileNames)
51    : mPP(PP),
52      mCtx(Ctx),
53      mTarget(Target),
54      mPragmas(Pragmas),
55      mTargetAPI(TargetAPI),
56      mGeneratedFileNames(GeneratedFileNames),
57      mDataLayout(NULL),
58      mLLVMContext(llvm::getGlobalContext()),
59      mLicenseNote(NULL),
60      mRSPackageName("android.renderscript"),
61      version(0),
62      mIsCompatLib(false),
63      mMangleCtx(Ctx.createMangleContext()) {
64  slangAssert(mGeneratedFileNames && "Must supply GeneratedFileNames");
65
66  // For #pragma rs export_type
67  PP.AddPragmaHandler(
68      "rs", RSPragmaHandler::CreatePragmaExportTypeHandler(this));
69
70  // For #pragma rs java_package_name
71  PP.AddPragmaHandler(
72      "rs", RSPragmaHandler::CreatePragmaJavaPackageNameHandler(this));
73
74  // For #pragma rs set_reflect_license
75  PP.AddPragmaHandler(
76      "rs", RSPragmaHandler::CreatePragmaReflectLicenseHandler(this));
77
78  // For #pragma version
79  PP.AddPragmaHandler(RSPragmaHandler::CreatePragmaVersionHandler(this));
80
81  // Prepare target data
82  mDataLayout = new llvm::DataLayout(Target.getTargetDescription());
83
84  return;
85}
86
87bool RSContext::processExportVar(const clang::VarDecl *VD) {
88  slangAssert(!VD->getName().empty() && "Variable name should not be empty");
89
90  // TODO(zonr): some check on variable
91
92  RSExportType *ET = RSExportType::CreateFromDecl(this, VD);
93  if (!ET)
94    return false;
95
96  RSExportVar *EV = new RSExportVar(this, VD, ET);
97  if (EV == NULL)
98    return false;
99  else
100    mExportVars.push_back(EV);
101
102  return true;
103}
104
105bool RSContext::processExportFunc(const clang::FunctionDecl *FD) {
106  slangAssert(!FD->getName().empty() && "Function name should not be empty");
107
108  if (!FD->isThisDeclarationADefinition()) {
109    return true;
110  }
111
112  if (FD->getStorageClass() != clang::SC_None) {
113    fprintf(stderr, "RSContext::processExportFunc : cannot export extern or "
114                    "static function '%s'\n", FD->getName().str().c_str());
115    return false;
116  }
117
118  if (RSExportForEach::isSpecialRSFunc(mTargetAPI, FD)) {
119    // Do not reflect specialized functions like init, dtor, or graphics root.
120    return RSExportForEach::validateSpecialFuncDecl(mTargetAPI, this, FD);
121  } else if (RSExportForEach::isRSForEachFunc(mTargetAPI, this, FD)) {
122    RSExportForEach *EFE = RSExportForEach::Create(this, FD);
123    if (EFE == NULL)
124      return false;
125    else
126      mExportForEach.push_back(EFE);
127    return true;
128  }
129
130  RSExportFunc *EF = RSExportFunc::Create(this, FD);
131  if (EF == NULL)
132    return false;
133  else
134    mExportFuncs.push_back(EF);
135
136  return true;
137}
138
139
140bool RSContext::processExportType(const llvm::StringRef &Name) {
141  clang::TranslationUnitDecl *TUDecl = mCtx.getTranslationUnitDecl();
142
143  slangAssert(TUDecl != NULL && "Translation unit declaration (top-level "
144                                "declaration) is null object");
145
146  const clang::IdentifierInfo *II = mPP.getIdentifierInfo(Name);
147  if (II == NULL)
148    // TODO(zonr): alert identifier @Name mark as an exportable type cannot be
149    //             found
150    return false;
151
152  clang::DeclContext::lookup_const_result R = TUDecl->lookup(II);
153  RSExportType *ET = NULL;
154
155  for (clang::DeclContext::lookup_const_iterator I = R.begin(), E = R.end();
156       I != E;
157       I++) {
158    clang::NamedDecl *const ND = *I;
159    const clang::Type *T = NULL;
160
161    switch (ND->getKind()) {
162      case clang::Decl::Typedef: {
163        T = static_cast<const clang::TypedefDecl*>(
164            ND)->getCanonicalDecl()->getUnderlyingType().getTypePtr();
165        break;
166      }
167      case clang::Decl::Record: {
168        T = static_cast<const clang::RecordDecl*>(ND)->getTypeForDecl();
169        break;
170      }
171      default: {
172        // unsupported, skip
173        break;
174      }
175    }
176
177    if (T != NULL)
178      ET = RSExportType::Create(this, T);
179  }
180
181  return (ET != NULL);
182}
183
184
185// Possibly re-order ForEach exports (maybe generating a dummy "root" function).
186// We require "root" to be listed as slot 0 of our exported compute kernels,
187// so this only needs to be created if we have other non-root kernels.
188void RSContext::cleanupForEach() {
189  bool foundNonRoot = false;
190  ExportForEachList::iterator begin = mExportForEach.begin();
191
192  for (ExportForEachList::iterator I = begin, E = mExportForEach.end();
193       I != E;
194       I++) {
195    RSExportForEach *EFE = *I;
196    if (!EFE->getName().compare("root")) {
197      if (I == begin) {
198        // Nothing to do, since it is the first function
199        return;
200      }
201
202      mExportForEach.erase(I);
203      mExportForEach.push_front(EFE);
204      return;
205    } else {
206      foundNonRoot = true;
207    }
208  }
209
210  // If we found a non-root kernel, but no root() function, we need to add a
211  // dummy version (so that script->script calls of rsForEach don't behave
212  // erratically).
213  if (foundNonRoot) {
214    RSExportForEach *DummyRoot = RSExportForEach::CreateDummyRoot(this);
215    mExportForEach.push_front(DummyRoot);
216  }
217}
218
219
220bool RSContext::processExport() {
221  bool valid = true;
222
223  if (getDiagnostics()->hasErrorOccurred()) {
224    return false;
225  }
226
227  // Export variable
228  clang::TranslationUnitDecl *TUDecl = mCtx.getTranslationUnitDecl();
229  for (clang::DeclContext::decl_iterator DI = TUDecl->decls_begin(),
230           DE = TUDecl->decls_end();
231       DI != DE;
232       DI++) {
233    if (DI->getKind() == clang::Decl::Var) {
234      clang::VarDecl *VD = (clang::VarDecl*) (*DI);
235      if (VD->getFormalLinkage() == clang::ExternalLinkage) {
236        if (!processExportVar(VD)) {
237          valid = false;
238        }
239      }
240    } else if (DI->getKind() == clang::Decl::Function) {
241      // Export functions
242      clang::FunctionDecl *FD = (clang::FunctionDecl*) (*DI);
243      if (FD->getFormalLinkage() == clang::ExternalLinkage) {
244        if (!processExportFunc(FD)) {
245          valid = false;
246        }
247      }
248    }
249  }
250
251  if (valid) {
252    cleanupForEach();
253  }
254
255  // Finally, export type forcely set to be exported by user
256  for (NeedExportTypeSet::const_iterator EI = mNeedExportTypes.begin(),
257           EE = mNeedExportTypes.end();
258       EI != EE;
259       EI++) {
260    if (!processExportType(EI->getKey())) {
261      valid = false;
262    }
263  }
264
265  return valid;
266}
267
268bool RSContext::insertExportType(const llvm::StringRef &TypeName,
269                                 RSExportType *ET) {
270  ExportTypeMap::value_type *NewItem =
271      ExportTypeMap::value_type::Create(TypeName.begin(),
272                                        TypeName.end(),
273                                        mExportTypes.getAllocator(),
274                                        ET);
275
276  if (mExportTypes.insert(NewItem)) {
277    return true;
278  } else {
279    free(NewItem);
280    return false;
281  }
282}
283
284bool RSContext::reflectToJava(const std::string &OutputPathBase,
285                              const std::string &RSPackageName,
286                              const std::string &InputFileName,
287                              const std::string &OutputBCFileName) {
288  if (!RSPackageName.empty()) {
289    mRSPackageName = RSPackageName;
290  }
291
292  // If we are not targeting the actual Android Renderscript classes,
293  // we should reflect code that works with the compatibility library.
294  if (mRSPackageName.compare("android.renderscript") != 0) {
295    mIsCompatLib = true;
296  }
297
298  RSReflection *R = new RSReflection(this, mGeneratedFileNames);
299  bool ret = R->reflect(OutputPathBase, mReflectJavaPackageName, mRSPackageName,
300                        InputFileName, OutputBCFileName);
301  if (!ret)
302    fprintf(stderr, "RSContext::reflectToJava : failed to do reflection "
303                    "(%s)\n", R->getLastError());
304  delete R;
305  return ret;
306}
307
308RSContext::~RSContext() {
309  delete mLicenseNote;
310  delete mDataLayout;
311  for (ExportableList::iterator I = mExportables.begin(),
312          E = mExportables.end();
313       I != E;
314       I++) {
315    if (!(*I)->isKeep())
316      delete *I;
317  }
318}
319
320clang::DiagnosticBuilder RSContext::Report(
321    clang::DiagnosticsEngine::Level Level, const char *Message) {
322  clang::DiagnosticsEngine *DiagEngine = getDiagnostics();
323  return DiagEngine->Report(DiagEngine->getCustomDiagID(Level, Message));
324}
325
326clang::DiagnosticBuilder RSContext::Report(
327    clang::DiagnosticsEngine::Level Level, const clang::SourceLocation Loc,
328    const char *Message) {
329  clang::DiagnosticsEngine *DiagEngine = getDiagnostics();
330  const clang::SourceManager *SM = getSourceManager();
331  return DiagEngine->Report(clang::FullSourceLoc(Loc, *SM),
332                            DiagEngine->getCustomDiagID(Level, Message));
333}
334
335}  // namespace slang
336