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