slang_rs.cpp revision 9207a2e495c8363606861e4f034504ec5c153dab
19066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project/*
29066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project * Copyright 2010, The Android Open Source Project
39066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project *
49066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project * Licensed under the Apache License, Version 2.0 (the "License");
59066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project * you may not use this file except in compliance with the License.
69066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project * You may obtain a copy of the License at
79066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project *
89066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project *     http://www.apache.org/licenses/LICENSE-2.0
99066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project *
109066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project * Unless required by applicable law or agreed to in writing, software
119066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project * distributed under the License is distributed on an "AS IS" BASIS,
129066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
139066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project * See the License for the specific language governing permissions and
149066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project * limitations under the License.
159066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project */
169066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project
179066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project#include "slang_rs.h"
189066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project
199066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project#include <cstring>
209066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project#include <list>
219066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project#include <sstream>
229066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project#include <string>
2336d7549181af397cfaf879f46e407e762e0e8cbaRomain Guy#include <utility>
249066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project#include <vector>
259066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project
269066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project#include "clang/Basic/SourceLocation.h"
279066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project
289066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project#include "clang/Frontend/FrontendDiagnostic.h"
299066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project
309066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project#include "clang/Sema/SemaDiagnostic.h"
319066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project
329066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project#include "llvm/Support/Path.h"
339066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project
349066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project#include "os_sep.h"
359066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project#include "slang_rs_backend.h"
369066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project#include "slang_rs_context.h"
37736c525a04a4d5e1c83541deca009ca97b99ef92Mike Reed#include "slang_rs_export_type.h"
38736c525a04a4d5e1c83541deca009ca97b99ef92Mike Reed
399066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Projectnamespace slang {
40736c525a04a4d5e1c83541deca009ca97b99ef92Mike Reed
41736c525a04a4d5e1c83541deca009ca97b99ef92Mike Reed#define RS_HEADER_SUFFIX  "rsh"
427df951595fa99bb4ead7891a2d70e3281314c51eMike Reed
43736c525a04a4d5e1c83541deca009ca97b99ef92Mike Reed/* RS_HEADER_ENTRY(name) */
447df951595fa99bb4ead7891a2d70e3281314c51eMike Reed#define ENUM_RS_HEADER()  \
457df951595fa99bb4ead7891a2d70e3281314c51eMike Reed  RS_HEADER_ENTRY(rs_allocation) \
467df951595fa99bb4ead7891a2d70e3281314c51eMike Reed  RS_HEADER_ENTRY(rs_atomic) \
477df951595fa99bb4ead7891a2d70e3281314c51eMike Reed  RS_HEADER_ENTRY(rs_cl) \
48736c525a04a4d5e1c83541deca009ca97b99ef92Mike Reed  RS_HEADER_ENTRY(rs_core) \
497df951595fa99bb4ead7891a2d70e3281314c51eMike Reed  RS_HEADER_ENTRY(rs_debug) \
507df951595fa99bb4ead7891a2d70e3281314c51eMike Reed  RS_HEADER_ENTRY(rs_graphics) \
519066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project  RS_HEADER_ENTRY(rs_math) \
529066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project  RS_HEADER_ENTRY(rs_matrix) \
539066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project  RS_HEADER_ENTRY(rs_object) \
549066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project  RS_HEADER_ENTRY(rs_quaternion) \
559066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project  RS_HEADER_ENTRY(rs_time) \
569066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project  RS_HEADER_ENTRY(rs_types) \
579066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project
589066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project
5936bef0bf30d6bae48cf3837df351075ca4fce654Ashok Bhatbool SlangRS::reflectToJava(const std::string &OutputPathBase,
6036bef0bf30d6bae48cf3837df351075ca4fce654Ashok Bhat                            const std::string &OutputPackageName,
619066cfe9886ac131c34d59ed0e2d287b0e3c0087The Android Open Source Project                            std::string *RealPackageName) {
62  return mRSContext->reflectToJava(OutputPathBase,
63                                   OutputPackageName,
64                                   getInputFileName(),
65                                   getOutputFileName(),
66                                   RealPackageName);
67}
68
69bool SlangRS::generateBitcodeAccessor(const std::string &OutputPathBase,
70                                      const std::string &PackageName) {
71  RSSlangReflectUtils::BitCodeAccessorContext BCAccessorContext;
72
73  BCAccessorContext.rsFileName = getInputFileName().c_str();
74  BCAccessorContext.bcFileName = getOutputFileName().c_str();
75  BCAccessorContext.reflectPath = OutputPathBase.c_str();
76  BCAccessorContext.packageName = PackageName.c_str();
77  BCAccessorContext.bcStorage = BCST_JAVA_CODE;   // Must be BCST_JAVA_CODE
78
79  return RSSlangReflectUtils::GenerateBitCodeAccessor(BCAccessorContext);
80}
81
82bool SlangRS::checkODR(const char *CurInputFile) {
83  for (RSContext::ExportableList::iterator I = mRSContext->exportable_begin(),
84          E = mRSContext->exportable_end();
85       I != E;
86       I++) {
87    RSExportable *RSE = *I;
88    if (RSE->getKind() != RSExportable::EX_TYPE)
89      continue;
90
91    RSExportType *ET = static_cast<RSExportType *>(RSE);
92    if (ET->getClass() != RSExportType::ExportClassRecord)
93      continue;
94
95    RSExportRecordType *ERT = static_cast<RSExportRecordType *>(ET);
96
97    // Artificial record types (create by us not by user in the source) always
98    // conforms the ODR.
99    if (ERT->isArtificial())
100      continue;
101
102    // Key to lookup ERT in ReflectedDefinitions
103    llvm::StringRef RDKey(ERT->getName());
104    ReflectedDefinitionListTy::const_iterator RD =
105        ReflectedDefinitions.find(RDKey);
106
107    if (RD != ReflectedDefinitions.end()) {
108      const RSExportRecordType *Reflected = RD->getValue().first;
109      // There's a record (struct) with the same name reflected before. Enforce
110      // ODR checking - the Reflected must hold *exactly* the same "definition"
111      // as the one defined previously. We say two record types A and B have the
112      // same definition iff:
113      //
114      //  struct A {              struct B {
115      //    Type(a1) a1,            Type(b1) b1,
116      //    Type(a2) a2,            Type(b1) b2,
117      //    ...                     ...
118      //    Type(aN) aN             Type(b3) b3,
119      //  };                      }
120      //  Cond. #1. They have same number of fields, i.e., N = M;
121      //  Cond. #2. for (i := 1 to N)
122      //              Type(ai) = Type(bi) must hold;
123      //  Cond. #3. for (i := 1 to N)
124      //              Name(ai) = Name(bi) must hold;
125      //
126      // where,
127      //  Type(F) = the type of field F and
128      //  Name(F) = the field name.
129
130      bool PassODR = false;
131      // Cond. #1 and Cond. #2
132      if (Reflected->equals(ERT)) {
133        // Cond #3.
134        RSExportRecordType::const_field_iterator AI = Reflected->fields_begin(),
135                                                 BI = ERT->fields_begin();
136
137        for (unsigned i = 0, e = Reflected->getFields().size(); i != e; i++) {
138          if ((*AI)->getName() != (*BI)->getName())
139            break;
140          AI++;
141          BI++;
142        }
143        PassODR = (AI == (Reflected->fields_end()));
144      }
145
146      if (!PassODR) {
147        getDiagnostics().Report(mDiagErrorODR) << Reflected->getName()
148                                               << getInputFileName()
149                                               << RD->getValue().second;
150        return false;
151      }
152    } else {
153      llvm::StringMapEntry<ReflectedDefinitionTy> *ME =
154          llvm::StringMapEntry<ReflectedDefinitionTy>::Create(RDKey.begin(),
155                                                              RDKey.end());
156      ME->setValue(std::make_pair(ERT, CurInputFile));
157
158      if (!ReflectedDefinitions.insert(ME))
159        delete ME;
160
161      // Take the ownership of ERT such that it won't be freed in ~RSContext().
162      ERT->keep();
163    }
164  }
165  return true;
166}
167
168void SlangRS::initDiagnostic() {
169  clang::DiagnosticsEngine &DiagEngine = getDiagnostics();
170
171  if (DiagEngine.setDiagnosticGroupMapping("implicit-function-declaration",
172                                           clang::diag::MAP_ERROR))
173    DiagEngine.Report(clang::diag::warn_unknown_warning_option)
174      << "implicit-function-declaration";
175
176  DiagEngine.setDiagnosticMapping(
177    clang::diag::ext_typecheck_convert_discards_qualifiers,
178    clang::diag::MAP_ERROR,
179    clang::SourceLocation());
180
181  mDiagErrorInvalidOutputDepParameter =
182    DiagEngine.getCustomDiagID(
183      clang::DiagnosticsEngine::Error,
184      "invalid parameter for output dependencies files.");
185
186  mDiagErrorODR =
187    DiagEngine.getCustomDiagID(
188      clang::DiagnosticsEngine::Error,
189      "type '%0' in different translation unit (%1 v.s. %2) "
190      "has incompatible type definition");
191
192  mDiagErrorTargetAPIRange =
193    DiagEngine.getCustomDiagID(
194      clang::DiagnosticsEngine::Error,
195      "target API level '%0' is out of range ('%1' - '%2')");
196}
197
198void SlangRS::initPreprocessor() {
199  clang::Preprocessor &PP = getPreprocessor();
200
201  std::stringstream RSH;
202  RSH << "#define RS_VERSION " << mTargetAPI << std::endl;
203  RSH << "#include \"rs_core." RS_HEADER_SUFFIX "\"" << std::endl;
204  PP.setPredefines(RSH.str());
205}
206
207void SlangRS::initASTContext() {
208  mRSContext = new RSContext(getPreprocessor(),
209                             getASTContext(),
210                             getTargetInfo(),
211                             &mPragmas,
212                             mTargetAPI,
213                             &mGeneratedFileNames);
214}
215
216clang::ASTConsumer
217*SlangRS::createBackend(const clang::CodeGenOptions& CodeGenOpts,
218                        llvm::raw_ostream *OS,
219                        Slang::OutputType OT) {
220    return new RSBackend(mRSContext,
221                         &getDiagnostics(),
222                         CodeGenOpts,
223                         getTargetOptions(),
224                         &mPragmas,
225                         OS,
226                         OT,
227                         getSourceManager(),
228                         mAllowRSPrefix);
229}
230
231bool SlangRS::IsRSHeaderFile(const char *File) {
232#define RS_HEADER_ENTRY(name)  \
233  if (::strcmp(File, #name "."RS_HEADER_SUFFIX) == 0)  \
234    return true;
235ENUM_RS_HEADER()
236#undef RS_HEADER_ENTRY
237  return false;
238}
239
240bool SlangRS::IsFunctionInRSHeaderFile(const clang::FunctionDecl *FD,
241                                       const clang::SourceManager &SourceMgr) {
242  clang::FullSourceLoc FSL(FD->getLocStart(), SourceMgr);
243  clang::PresumedLoc PLoc = SourceMgr.getPresumedLoc(FSL);
244
245  const char *Filename = PLoc.getFilename();
246  if (!Filename) {
247    return false;
248  } else {
249    return IsRSHeaderFile(llvm::sys::path::filename(Filename).data());
250  }
251}
252
253SlangRS::SlangRS()
254  : Slang(), mRSContext(NULL), mAllowRSPrefix(false), mTargetAPI(0) {
255}
256
257bool SlangRS::compile(
258    const std::list<std::pair<const char*, const char*> > &IOFiles,
259    const std::list<std::pair<const char*, const char*> > &DepFiles,
260    const std::vector<std::string> &IncludePaths,
261    const std::vector<std::string> &AdditionalDepTargets,
262    Slang::OutputType OutputType, BitCodeStorageType BitcodeStorage,
263    bool AllowRSPrefix, bool OutputDep,
264    unsigned int TargetAPI,
265    const std::string &JavaReflectionPathBase,
266    const std::string &JavaReflectionPackageName) {
267  if (IOFiles.empty())
268    return true;
269
270  if (OutputDep && (DepFiles.size() != IOFiles.size())) {
271    getDiagnostics().Report(mDiagErrorInvalidOutputDepParameter);
272    return false;
273  }
274
275  std::string RealPackageName;
276
277  const char *InputFile, *OutputFile, *BCOutputFile, *DepOutputFile;
278  std::list<std::pair<const char*, const char*> >::const_iterator
279      IOFileIter = IOFiles.begin(), DepFileIter = DepFiles.begin();
280
281  setIncludePaths(IncludePaths);
282  setOutputType(OutputType);
283  if (OutputDep) {
284    setAdditionalDepTargets(AdditionalDepTargets);
285  }
286
287  mAllowRSPrefix = AllowRSPrefix;
288
289  mTargetAPI = TargetAPI;
290  if (mTargetAPI < SLANG_MINIMUM_TARGET_API ||
291      mTargetAPI > SLANG_MAXIMUM_TARGET_API) {
292    getDiagnostics().Report(mDiagErrorTargetAPIRange) << mTargetAPI
293        << SLANG_MINIMUM_TARGET_API << SLANG_MAXIMUM_TARGET_API;
294    return false;
295  }
296
297  // Skip generation of warnings a second time if we are doing more than just
298  // a single pass over the input file.
299  bool SuppressAllWarnings = (OutputType != Slang::OT_Dependency);
300
301  for (unsigned i = 0, e = IOFiles.size(); i != e; i++) {
302    InputFile = IOFileIter->first;
303    OutputFile = IOFileIter->second;
304
305    reset();
306
307    if (!setInputSource(InputFile))
308      return false;
309
310    if (!setOutput(OutputFile))
311      return false;
312
313    if (Slang::compile() > 0)
314      return false;
315
316    if (OutputType != Slang::OT_Dependency) {
317      if (!reflectToJava(JavaReflectionPathBase,
318                         JavaReflectionPackageName,
319                         &RealPackageName))
320        return false;
321
322      for (std::vector<std::string>::const_iterator
323               I = mGeneratedFileNames.begin(), E = mGeneratedFileNames.end();
324           I != E;
325           I++) {
326        std::string ReflectedName = RSSlangReflectUtils::ComputePackagedPath(
327            JavaReflectionPathBase.c_str(),
328            (RealPackageName + OS_PATH_SEPARATOR_STR + *I).c_str());
329        appendGeneratedFileName(ReflectedName + ".java");
330      }
331
332      if ((OutputType == Slang::OT_Bitcode) &&
333          (BitcodeStorage == BCST_JAVA_CODE) &&
334          !generateBitcodeAccessor(JavaReflectionPathBase,
335                                     RealPackageName.c_str()))
336          return false;
337    }
338
339    if (OutputDep) {
340      BCOutputFile = DepFileIter->first;
341      DepOutputFile = DepFileIter->second;
342
343      setDepTargetBC(BCOutputFile);
344
345      if (!setDepOutput(DepOutputFile))
346        return false;
347
348      if (SuppressAllWarnings) {
349        getDiagnostics().setSuppressAllDiagnostics(true);
350      }
351      if (generateDepFile() > 0)
352        return false;
353      if (SuppressAllWarnings) {
354        getDiagnostics().setSuppressAllDiagnostics(false);
355      }
356
357      DepFileIter++;
358    }
359
360    if (!checkODR(InputFile))
361      return false;
362
363    IOFileIter++;
364  }
365
366  return true;
367}
368
369void SlangRS::reset() {
370  delete mRSContext;
371  mRSContext = NULL;
372  mGeneratedFileNames.clear();
373  Slang::reset();
374  return;
375}
376
377SlangRS::~SlangRS() {
378  delete mRSContext;
379  for (ReflectedDefinitionListTy::iterator I = ReflectedDefinitions.begin(),
380          E = ReflectedDefinitions.end();
381       I != E;
382       I++) {
383    delete I->getValue().first;
384  }
385  return;
386}
387
388}  // namespace slang
389