slang_rs_context.cpp revision 2d2512c5703bb238b7935ab5228beff6563f2f94
1/*
2 * Copyright 2010, 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/Type.h"
25
26#include "clang/Basic/Linkage.h"
27#include "clang/Basic/TargetInfo.h"
28
29#include "clang/Index/ASTLocation.h"
30
31#include "llvm/LLVMContext.h"
32
33#include "llvm/Target/TargetData.h"
34
35#include "slang.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    : mPP(PP),
49      mCtx(Ctx),
50      mTarget(Target),
51      mTargetData(NULL),
52      mLLVMContext(llvm::getGlobalContext()),
53      mLicenseNote(NULL) {
54  // For #pragma rs export_type
55  PP.AddPragmaHandler(
56      "rs", RSPragmaHandler::CreatePragmaExportTypeHandler(this));
57
58  // For #pragma rs java_package_name
59  PP.AddPragmaHandler(
60      "rs", RSPragmaHandler::CreatePragmaJavaPackageNameHandler(this));
61
62  // For #pragma rs set_reflect_license
63  PP.AddPragmaHandler(
64      "rs", RSPragmaHandler::CreatePragmaReflectLicenseHandler(this));
65
66  // Prepare target data
67  mTargetData = new llvm::TargetData(Target.getTargetDescription());
68
69  return;
70}
71
72bool RSContext::processExportVar(const clang::VarDecl *VD) {
73  assert(!VD->getName().empty() && "Variable name should not be empty");
74
75  // TODO(zonr): some check on variable
76
77  RSExportType *ET = RSExportType::CreateFromDecl(this, VD);
78  if (!ET)
79    return false;
80
81  RSExportVar *EV = new RSExportVar(this, VD, ET);
82  if (EV == NULL)
83    return false;
84  else
85    mExportVars.push_back(EV);
86
87  return true;
88}
89
90static bool isSpecialRSFunc(const llvm::StringRef& Name) {
91  static llvm::StringRef FuncInit("init");
92  static llvm::StringRef FuncRoot("root");
93  return Name.equals(FuncInit) || Name.equals(FuncRoot);
94}
95
96bool RSContext::processExportFunc(const clang::FunctionDecl *FD) {
97  assert(!FD->getName().empty() && "Function name should not be empty");
98
99  if (!FD->isThisDeclarationADefinition()) {
100    return true;
101  }
102
103  if (FD->getStorageClass() != clang::SC_None) {
104    fprintf(stderr, "RSContext::processExportFunc : cannot export extern or "
105                    "static function '%s'\n", FD->getName().str().c_str());
106    return false;
107  }
108
109  // Do not reflect specialized RS functions like init/root.
110  if (isSpecialRSFunc(FD->getName())) {
111    return true;
112  }
113
114  RSExportFunc *EF = RSExportFunc::Create(this, FD);
115  if (EF == NULL)
116    return false;
117  else
118    mExportFuncs.push_back(EF);
119
120  return true;
121}
122
123
124bool RSContext::processExportType(const llvm::StringRef &Name) {
125  clang::TranslationUnitDecl *TUDecl = mCtx.getTranslationUnitDecl();
126
127  assert(TUDecl != NULL && "Translation unit declaration (top-level "
128                           "declaration) is null object");
129
130  const clang::IdentifierInfo *II = mPP.getIdentifierInfo(Name);
131  if (II == NULL)
132    // TODO(zonr): alert identifier @Name mark as an exportable type cannot be
133    //             found
134    return false;
135
136  clang::DeclContext::lookup_const_result R = TUDecl->lookup(II);
137  RSExportType *ET = NULL;
138
139  RSExportPointerType::IntegerType = mCtx.IntTy.getTypePtr();
140
141  for (clang::DeclContext::lookup_const_iterator I = R.first, E = R.second;
142       I != E;
143       I++) {
144    clang::NamedDecl *const ND = *I;
145    const clang::Type *T = NULL;
146
147    switch (ND->getKind()) {
148      case clang::Decl::Typedef: {
149        T = static_cast<const clang::TypedefDecl*>(
150            ND)->getCanonicalDecl()->getUnderlyingType().getTypePtr();
151        break;
152      }
153      case clang::Decl::Record: {
154        T = static_cast<const clang::RecordDecl*>(ND)->getTypeForDecl();
155        break;
156      }
157      default: {
158        // unsupported, skip
159        break;
160      }
161    }
162
163    if (T != NULL)
164      ET = RSExportType::Create(this, T);
165  }
166
167  RSExportPointerType::IntegerType = NULL;
168
169  return (ET != NULL);
170}
171
172void RSContext::processExport() {
173  // Export variable
174  clang::TranslationUnitDecl *TUDecl = mCtx.getTranslationUnitDecl();
175  for (clang::DeclContext::decl_iterator DI = TUDecl->decls_begin(),
176           DE = TUDecl->decls_end();
177       DI != TUDecl->decls_end();
178       DI++) {
179    if (DI->getKind() == clang::Decl::Var) {
180      clang::VarDecl *VD = (clang::VarDecl*) (*DI);
181      if (VD->getLinkage() == clang::ExternalLinkage) {
182        if (!processExportVar(VD)) {
183          fprintf(stderr, "RSContext::processExport : failed to export var "
184                          "'%s'\n", VD->getNameAsString().c_str());
185        }
186      }
187    } else if (DI->getKind() == clang::Decl::Function) {
188      // Export functions
189      clang::FunctionDecl *FD = (clang::FunctionDecl*) (*DI);
190      if (FD->getLinkage() == clang::ExternalLinkage) {
191        if (!processExportFunc(FD)) {
192          fprintf(stderr, "RSContext::processExport : failed to export func "
193                          "'%s'\n", FD->getNameAsString().c_str());
194        }
195      }
196    }
197  }
198
199  // Finally, export type forcely set to be exported by user
200  for (NeedExportTypeSet::const_iterator EI = mNeedExportTypes.begin(),
201           EE = mNeedExportTypes.end();
202       EI != EE;
203       EI++) {
204    if (!processExportType(EI->getKey())) {
205      fprintf(stderr, "RSContext::processExport : failed to export type "
206              "'%s'\n", EI->getKey().str().c_str());
207    }
208  }
209
210  return;
211}
212
213bool RSContext::insertExportType(const llvm::StringRef &TypeName,
214                                 RSExportType *ET) {
215  ExportTypeMap::value_type *NewItem =
216      ExportTypeMap::value_type::Create(TypeName.begin(),
217                                        TypeName.end(),
218                                        mExportTypes.getAllocator(),
219                                        ET);
220
221  if (mExportTypes.insert(NewItem)) {
222    return true;
223  } else {
224    free(NewItem);
225    return false;
226  }
227}
228
229bool RSContext::reflectToJava(const std::string &OutputPathBase,
230                              const std::string &OutputPackageName,
231                              const std::string &InputFileName,
232                              const std::string &OutputBCFileName,
233                              std::string *RealPackageName) {
234  if (RealPackageName != NULL)
235    RealPackageName->clear();
236
237  const std::string &PackageName =
238      ((OutputPackageName.empty()) ? mReflectJavaPackageName :
239                                     OutputPackageName);
240  if (PackageName.empty())
241    // no package name, just return
242    return true;
243
244  // Copy back the really applied package name
245  RealPackageName->assign(PackageName);
246
247  RSReflection *R = new RSReflection(this);
248  bool ret = R->reflect(OutputPathBase, PackageName,
249                        InputFileName, OutputBCFileName);
250  if (!ret)
251    fprintf(stderr, "RSContext::reflectToJava : failed to do reflection "
252                    "(%s)\n", R->getLastError());
253  delete R;
254  return ret;
255}
256
257RSContext::~RSContext() {
258  delete mLicenseNote;
259  delete mTargetData;
260  for (ExportableList::iterator I = mExportables.begin(),
261          E = mExportables.end();
262       I != E;
263       I++) {
264    if (!(*I)->isKeep())
265      delete *I;
266  }
267}
268
269}  // namespace slang
270