Home | History | Annotate | Download | only in slang
      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.h"
     18 
     19 #include <stdlib.h>
     20 
     21 #include <cstring>
     22 #include <list>
     23 #include <sstream>
     24 #include <string>
     25 #include <utility>
     26 #include <vector>
     27 
     28 #include "clang/AST/ASTConsumer.h"
     29 #include "clang/AST/ASTContext.h"
     30 
     31 #include "clang/Basic/DiagnosticIDs.h"
     32 #include "clang/Basic/DiagnosticOptions.h"
     33 #include "clang/Basic/FileManager.h"
     34 #include "clang/Basic/FileSystemOptions.h"
     35 #include "clang/Basic/SourceLocation.h"
     36 #include "clang/Basic/SourceManager.h"
     37 #include "clang/Basic/TargetInfo.h"
     38 #include "clang/Basic/TargetOptions.h"
     39 
     40 #include "clang/Frontend/DependencyOutputOptions.h"
     41 #include "clang/Frontend/FrontendDiagnostic.h"
     42 #include "clang/Frontend/FrontendOptions.h"
     43 #include "clang/Frontend/PCHContainerOperations.h"
     44 #include "clang/Frontend/TextDiagnosticPrinter.h"
     45 #include "clang/Frontend/Utils.h"
     46 
     47 #include "clang/Lex/HeaderSearch.h"
     48 #include "clang/Lex/HeaderSearchOptions.h"
     49 #include "clang/Lex/Preprocessor.h"
     50 #include "clang/Lex/PreprocessorOptions.h"
     51 
     52 #include "clang/Parse/ParseAST.h"
     53 
     54 #include "clang/Sema/SemaDiagnostic.h"
     55 
     56 #include "llvm/ADT/IntrusiveRefCntPtr.h"
     57 
     58 #include "llvm/Bitcode/ReaderWriter.h"
     59 
     60 // More force linking
     61 #include "llvm/Linker/Linker.h"
     62 
     63 // Force linking all passes/vmcore stuffs to libslang.so
     64 #include "llvm/LinkAllIR.h"
     65 #include "llvm/LinkAllPasses.h"
     66 
     67 #include "llvm/Support/raw_ostream.h"
     68 #include "llvm/Support/MemoryBuffer.h"
     69 #include "llvm/Support/ErrorHandling.h"
     70 #include "llvm/Support/ManagedStatic.h"
     71 #include "llvm/Support/Path.h"
     72 #include "llvm/Support/TargetSelect.h"
     73 #include "llvm/Support/ToolOutputFile.h"
     74 
     75 #include "os_sep.h"
     76 #include "rs_cc_options.h"
     77 #include "slang_assert.h"
     78 #include "slang_backend.h"
     79 
     80 #include "slang_rs_context.h"
     81 #include "slang_rs_export_type.h"
     82 
     83 #include "slang_rs_reflection.h"
     84 #include "slang_rs_reflection_cpp.h"
     85 
     86 
     87 namespace {
     88 
     89 static const char *kRSTriple32 = "renderscript32-none-linux-gnueabi";
     90 static const char *kRSTriple64 = "renderscript64-none-linux-gnueabi";
     91 
     92 }  // namespace
     93 
     94 namespace slang {
     95 
     96 
     97 #define FS_SUFFIX  "fs"
     98 
     99 #define RS_HEADER_SUFFIX  "rsh"
    100 
    101 /* RS_HEADER_ENTRY(name) */
    102 #define ENUM_RS_HEADER()  \
    103   RS_HEADER_ENTRY(rs_allocation_create) \
    104   RS_HEADER_ENTRY(rs_allocation_data) \
    105   RS_HEADER_ENTRY(rs_atomic) \
    106   RS_HEADER_ENTRY(rs_convert) \
    107   RS_HEADER_ENTRY(rs_core) \
    108   RS_HEADER_ENTRY(rs_debug) \
    109   RS_HEADER_ENTRY(rs_for_each) \
    110   RS_HEADER_ENTRY(rs_graphics) \
    111   RS_HEADER_ENTRY(rs_graphics_types) \
    112   RS_HEADER_ENTRY(rs_io) \
    113   RS_HEADER_ENTRY(rs_math) \
    114   RS_HEADER_ENTRY(rs_matrix) \
    115   RS_HEADER_ENTRY(rs_object_info) \
    116   RS_HEADER_ENTRY(rs_object_types) \
    117   RS_HEADER_ENTRY(rs_quaternion) \
    118   RS_HEADER_ENTRY(rs_time) \
    119   RS_HEADER_ENTRY(rs_value_types) \
    120   RS_HEADER_ENTRY(rs_vector_math) \
    121 
    122 
    123 // The named of metadata node that pragma resides (should be synced with
    124 // bcc.cpp)
    125 const llvm::StringRef Slang::PragmaMetadataName = "#pragma";
    126 
    127 static llvm::LLVMContext globalContext;
    128 
    129 llvm::LLVMContext &getGlobalLLVMContext() { return globalContext; }
    130 
    131 static inline llvm::tool_output_file *
    132 OpenOutputFile(const char *OutputFile,
    133                llvm::sys::fs::OpenFlags Flags,
    134                std::error_code &EC,
    135                clang::DiagnosticsEngine *DiagEngine) {
    136   slangAssert((OutputFile != nullptr) &&
    137               (DiagEngine != nullptr) && "Invalid parameter!");
    138 
    139   EC = llvm::sys::fs::create_directories(
    140       llvm::sys::path::parent_path(OutputFile));
    141   if (!EC) {
    142     llvm::tool_output_file *F =
    143           new llvm::tool_output_file(OutputFile, EC, Flags);
    144     if (F != nullptr)
    145       return F;
    146   }
    147 
    148   // Report error here.
    149   DiagEngine->Report(clang::diag::err_fe_error_opening)
    150     << OutputFile << EC.message();
    151 
    152   return nullptr;
    153 }
    154 
    155 void Slang::createTarget(uint32_t BitWidth) {
    156   if (BitWidth == 64) {
    157     mTargetOpts->Triple = kRSTriple64;
    158   } else {
    159     mTargetOpts->Triple = kRSTriple32;
    160   }
    161 
    162   mTarget.reset(clang::TargetInfo::CreateTargetInfo(*mDiagEngine,
    163                                                     mTargetOpts));
    164 }
    165 
    166 void Slang::createFileManager() {
    167   mFileSysOpt.reset(new clang::FileSystemOptions());
    168   mFileMgr.reset(new clang::FileManager(*mFileSysOpt));
    169 }
    170 
    171 void Slang::createSourceManager() {
    172   mSourceMgr.reset(new clang::SourceManager(*mDiagEngine, *mFileMgr));
    173 }
    174 
    175 void Slang::createPreprocessor() {
    176   // Default only search header file in current dir
    177   clang::HeaderSearch *HeaderInfo = new clang::HeaderSearch(&getHeaderSearchOpts(),
    178                                                             *mSourceMgr,
    179                                                             *mDiagEngine,
    180                                                             LangOpts,
    181                                                             mTarget.get());
    182 
    183   mPP.reset(new clang::Preprocessor(&getPreprocessorOpts(),
    184                                     *mDiagEngine,
    185                                     LangOpts,
    186                                     *mSourceMgr,
    187                                     *HeaderInfo,
    188                                     *this,
    189                                     nullptr,
    190                                     /* OwnsHeaderSearch = */true));
    191   // Initialize the preprocessor
    192   mPP->Initialize(getTargetInfo());
    193   clang::FrontendOptions FEOpts;
    194 
    195   auto *Reader = mPCHContainerOperations->getReaderOrNull(
    196       getHeaderSearchOpts().ModuleFormat);
    197   clang::InitializePreprocessor(*mPP, getPreprocessorOpts(), *Reader, FEOpts);
    198 
    199   clang::ApplyHeaderSearchOptions(*HeaderInfo, getHeaderSearchOpts(), LangOpts,
    200       mPP->getTargetInfo().getTriple());
    201 
    202   mPragmas.clear();
    203 
    204   std::vector<clang::DirectoryLookup> SearchList;
    205   for (unsigned i = 0, e = mIncludePaths.size(); i != e; i++) {
    206     if (const clang::DirectoryEntry *DE =
    207             mFileMgr->getDirectory(mIncludePaths[i])) {
    208       SearchList.push_back(clang::DirectoryLookup(DE,
    209                                                   clang::SrcMgr::C_System,
    210                                                   false));
    211     }
    212   }
    213 
    214   HeaderInfo->SetSearchPaths(SearchList,
    215                              /* angledDirIdx = */1,
    216                              /* systemDixIdx = */1,
    217                              /* noCurDirSearch = */false);
    218 
    219   initPreprocessor();
    220 }
    221 
    222 void Slang::createASTContext() {
    223   mASTContext.reset(
    224       new clang::ASTContext(LangOpts, *mSourceMgr, mPP->getIdentifierTable(),
    225                             mPP->getSelectorTable(), mPP->getBuiltinInfo()));
    226   mASTContext->InitBuiltinTypes(getTargetInfo());
    227   initASTContext();
    228 }
    229 
    230 clang::ASTConsumer *
    231 Slang::createBackend(const RSCCOptions &Opts, const clang::CodeGenOptions &CodeGenOpts,
    232                      llvm::raw_ostream *OS, OutputType OT) {
    233   auto *B = new Backend(mRSContext, &getDiagnostics(), Opts,
    234                         getHeaderSearchOpts(), getPreprocessorOpts(),
    235                         CodeGenOpts, getTargetOptions(), &mPragmas, OS, OT,
    236                         getSourceManager(), mAllowRSPrefix, mIsFilterscript);
    237   B->Initialize(getASTContext());
    238   return B;
    239 }
    240 
    241 Slang::Slang(uint32_t BitWidth, clang::DiagnosticsEngine *DiagEngine,
    242              DiagnosticBuffer *DiagClient)
    243     : mDiagEngine(DiagEngine), mDiagClient(DiagClient),
    244       mTargetOpts(new clang::TargetOptions()),
    245       mHSOpts(new clang::HeaderSearchOptions()),
    246       mPPOpts(new clang::PreprocessorOptions()),
    247       mPCHContainerOperations(std::make_shared<clang::PCHContainerOperations>()),
    248       mOT(OT_Default), mRSContext(nullptr), mAllowRSPrefix(false), mTargetAPI(0),
    249       mVerbose(false), mIsFilterscript(false) {
    250   // Please refer to include/clang/Basic/LangOptions.h to setup
    251   // the options.
    252   LangOpts.RTTI = 0;  // Turn off the RTTI information support
    253   LangOpts.LineComment = 1;
    254   LangOpts.C99 = 1;
    255   LangOpts.RenderScript = 1;
    256   LangOpts.LaxVectorConversions = 0;  // Do not bitcast vectors!
    257   LangOpts.CharIsSigned = 1;  // Signed char is our default.
    258 
    259   CodeGenOpts.OptimizationLevel = 3;
    260 
    261   // We must set StackRealignment, because the default is for the actual
    262   // Clang driver to pass this option (-mstackrealign) directly to cc1.
    263   // Since we don't use Clang's driver, we need to similarly supply it.
    264   // If StackRealignment is zero (i.e. the option wasn't set), then the
    265   // backend assumes that it can't adjust the stack in any way, which breaks
    266   // alignment for vector loads/stores.
    267   CodeGenOpts.StackRealignment = 1;
    268 
    269   createTarget(BitWidth);
    270   createFileManager();
    271   createSourceManager();
    272 }
    273 
    274 Slang::~Slang() {
    275   delete mRSContext;
    276   for (ReflectedDefinitionListTy::iterator I = ReflectedDefinitions.begin(),
    277                                            E = ReflectedDefinitions.end();
    278        I != E; I++) {
    279     delete I->getValue().first;
    280   }
    281 }
    282 
    283 clang::ModuleLoadResult Slang::loadModule(
    284     clang::SourceLocation ImportLoc,
    285     clang::ModuleIdPath Path,
    286     clang::Module::NameVisibilityKind Visibility,
    287     bool IsInclusionDirective) {
    288   slangAssert(0 && "Not implemented");
    289   return clang::ModuleLoadResult();
    290 }
    291 
    292 bool Slang::setInputSource(llvm::StringRef InputFile) {
    293   mInputFileName = InputFile.str();
    294 
    295   mSourceMgr->clearIDTables();
    296 
    297   const clang::FileEntry *File = mFileMgr->getFile(InputFile);
    298   if (File) {
    299     mSourceMgr->setMainFileID(mSourceMgr->createFileID(File,
    300         clang::SourceLocation(), clang::SrcMgr::C_User));
    301   }
    302 
    303   if (mSourceMgr->getMainFileID().isInvalid()) {
    304     mDiagEngine->Report(clang::diag::err_fe_error_reading) << InputFile;
    305     return false;
    306   }
    307 
    308   return true;
    309 }
    310 
    311 bool Slang::setOutput(const char *OutputFile) {
    312   std::error_code EC;
    313   llvm::tool_output_file *OS = nullptr;
    314 
    315   switch (mOT) {
    316     case OT_Dependency:
    317     case OT_Assembly:
    318     case OT_LLVMAssembly: {
    319       OS = OpenOutputFile(OutputFile, llvm::sys::fs::F_Text, EC, mDiagEngine);
    320       break;
    321     }
    322     case OT_Nothing: {
    323       break;
    324     }
    325     case OT_Object:
    326     case OT_Bitcode: {
    327       OS = OpenOutputFile(OutputFile, llvm::sys::fs::F_None, EC, mDiagEngine);
    328       break;
    329     }
    330     default: {
    331       llvm_unreachable("Unknown compiler output type");
    332     }
    333   }
    334 
    335   if (EC)
    336     return false;
    337 
    338   mOS.reset(OS);
    339 
    340   mOutputFileName = OutputFile;
    341 
    342   return true;
    343 }
    344 
    345 bool Slang::setDepOutput(const char *OutputFile) {
    346   std::error_code EC;
    347 
    348   mDOS.reset(
    349       OpenOutputFile(OutputFile, llvm::sys::fs::F_Text, EC, mDiagEngine));
    350   if (EC || (mDOS.get() == nullptr))
    351     return false;
    352 
    353   mDepOutputFileName = OutputFile;
    354 
    355   return true;
    356 }
    357 
    358 int Slang::generateDepFile(bool PhonyTarget) {
    359   if (mDiagEngine->hasErrorOccurred())
    360     return 1;
    361   if (mDOS.get() == nullptr)
    362     return 1;
    363 
    364   // Initialize options for generating dependency file
    365   clang::DependencyOutputOptions DepOpts;
    366   DepOpts.IncludeSystemHeaders = 1;
    367   if (PhonyTarget)
    368     DepOpts.UsePhonyTargets = 1;
    369   DepOpts.OutputFile = mDepOutputFileName;
    370   DepOpts.Targets = mAdditionalDepTargets;
    371   DepOpts.Targets.push_back(mDepTargetBCFileName);
    372   for (std::vector<std::string>::const_iterator
    373            I = mGeneratedFileNames.begin(), E = mGeneratedFileNames.end();
    374        I != E;
    375        I++) {
    376     DepOpts.Targets.push_back(*I);
    377   }
    378   mGeneratedFileNames.clear();
    379 
    380   // Per-compilation needed initialization
    381   createPreprocessor();
    382   clang::DependencyFileGenerator::CreateAndAttachToPreprocessor(*mPP.get(), DepOpts);
    383 
    384   // Inform the diagnostic client we are processing a source file
    385   mDiagClient->BeginSourceFile(LangOpts, mPP.get());
    386 
    387   // Go through the source file (no operations necessary)
    388   clang::Token Tok;
    389   mPP->EnterMainSourceFile();
    390   do {
    391     mPP->Lex(Tok);
    392   } while (Tok.isNot(clang::tok::eof));
    393 
    394   mPP->EndSourceFile();
    395 
    396   // Declare success if no error
    397   if (!mDiagEngine->hasErrorOccurred())
    398     mDOS->keep();
    399 
    400   // Clean up after compilation
    401   mPP.reset();
    402   mDOS.reset();
    403 
    404   return mDiagEngine->hasErrorOccurred() ? 1 : 0;
    405 }
    406 
    407 int Slang::compile(const RSCCOptions &Opts) {
    408   if (mDiagEngine->hasErrorOccurred())
    409     return 1;
    410   if (mOS.get() == nullptr)
    411     return 1;
    412 
    413   // Here is per-compilation needed initialization
    414   createPreprocessor();
    415   createASTContext();
    416 
    417   mBackend.reset(createBackend(Opts, CodeGenOpts, &mOS->os(), mOT));
    418 
    419   // Inform the diagnostic client we are processing a source file
    420   mDiagClient->BeginSourceFile(LangOpts, mPP.get());
    421 
    422   // The core of the slang compiler
    423   ParseAST(*mPP, mBackend.get(), *mASTContext);
    424 
    425   // Inform the diagnostic client we are done with previous source file
    426   mDiagClient->EndSourceFile();
    427 
    428   // Declare success if no error
    429   if (!mDiagEngine->hasErrorOccurred())
    430     mOS->keep();
    431 
    432   // The compilation ended, clear
    433   mBackend.reset();
    434   mOS.reset();
    435 
    436   return mDiagEngine->hasErrorOccurred() ? 1 : 0;
    437 }
    438 
    439 void Slang::setDebugMetadataEmission(bool EmitDebug) {
    440   if (EmitDebug)
    441     CodeGenOpts.setDebugInfo(clang::codegenoptions::FullDebugInfo);
    442   else
    443     CodeGenOpts.setDebugInfo(clang::codegenoptions::NoDebugInfo);
    444 }
    445 
    446 void Slang::setOptimizationLevel(llvm::CodeGenOpt::Level OptimizationLevel) {
    447   CodeGenOpts.OptimizationLevel = OptimizationLevel;
    448 }
    449 
    450 bool Slang::isFilterscript(const char *Filename) {
    451   const char *c = strrchr(Filename, '.');
    452   if (c && !strncmp(FS_SUFFIX, c + 1, strlen(FS_SUFFIX) + 1)) {
    453     return true;
    454   } else {
    455     return false;
    456   }
    457 }
    458 
    459 bool Slang::generateJavaBitcodeAccessor(const std::string &OutputPathBase,
    460                                           const std::string &PackageName,
    461                                           const std::string *LicenseNote) {
    462   RSSlangReflectUtils::BitCodeAccessorContext BCAccessorContext;
    463 
    464   BCAccessorContext.rsFileName = getInputFileName().c_str();
    465   BCAccessorContext.bc32FileName = mOutput32FileName.c_str();
    466   BCAccessorContext.bc64FileName = mOutputFileName.c_str();
    467   BCAccessorContext.reflectPath = OutputPathBase.c_str();
    468   BCAccessorContext.packageName = PackageName.c_str();
    469   BCAccessorContext.licenseNote = LicenseNote;
    470   BCAccessorContext.bcStorage = BCST_JAVA_CODE;   // Must be BCST_JAVA_CODE
    471   BCAccessorContext.verbose = false;
    472 
    473   return RSSlangReflectUtils::GenerateJavaBitCodeAccessor(BCAccessorContext);
    474 }
    475 
    476 bool Slang::checkODR(const char *CurInputFile) {
    477   for (RSContext::ExportableList::iterator I = mRSContext->exportable_begin(),
    478           E = mRSContext->exportable_end();
    479        I != E;
    480        I++) {
    481     RSExportable *RSE = *I;
    482     if (RSE->getKind() != RSExportable::EX_TYPE)
    483       continue;
    484 
    485     RSExportType *ET = static_cast<RSExportType *>(RSE);
    486     if (ET->getClass() != RSExportType::ExportClassRecord)
    487       continue;
    488 
    489     RSExportRecordType *ERT = static_cast<RSExportRecordType *>(ET);
    490 
    491     // Artificial record types (create by us not by user in the source) always
    492     // conforms the ODR.
    493     if (ERT->isArtificial())
    494       continue;
    495 
    496     // Key to lookup ERT in ReflectedDefinitions
    497     llvm::StringRef RDKey(ERT->getName());
    498     ReflectedDefinitionListTy::const_iterator RD =
    499         ReflectedDefinitions.find(RDKey);
    500 
    501     if (RD != ReflectedDefinitions.end()) {
    502       const RSExportRecordType *Reflected = RD->getValue().first;
    503 
    504       // See RSExportRecordType::matchODR for the logic
    505       if (!Reflected->matchODR(ERT, true)) {
    506         unsigned DiagID = mDiagEngine->getCustomDiagID(
    507             clang::DiagnosticsEngine::Error,
    508             "type '%0' in different translation unit (%1 v.s. %2) "
    509             "has incompatible type definition");
    510         getDiagnostics().Report(DiagID) << Reflected->getName()
    511                                         << getInputFileName()
    512                                         << RD->getValue().second;
    513         return false;
    514       }
    515     } else {
    516       llvm::StringMapEntry<ReflectedDefinitionTy> *ME =
    517           llvm::StringMapEntry<ReflectedDefinitionTy>::Create(RDKey);
    518       ME->setValue(std::make_pair(ERT, CurInputFile));
    519 
    520       if (!ReflectedDefinitions.insert(ME)) {
    521         slangAssert(false && "Type shouldn't be in map yet!");
    522       }
    523 
    524       // Take the ownership of ERT such that it won't be freed in ~RSContext().
    525       ERT->keep();
    526     }
    527   }
    528   return true;
    529 }
    530 
    531 void Slang::initPreprocessor() {
    532   clang::Preprocessor &PP = getPreprocessor();
    533 
    534   std::stringstream RSH;
    535   RSH << PP.getPredefines();
    536   RSH << "#define RS_VERSION " << mTargetAPI << "\n";
    537   RSH << "#include \"rs_core." RS_HEADER_SUFFIX "\"\n";
    538   PP.setPredefines(RSH.str());
    539 }
    540 
    541 void Slang::initASTContext() {
    542   mRSContext = new RSContext(getPreprocessor(),
    543                              getASTContext(),
    544                              getTargetInfo(),
    545                              &mPragmas,
    546                              mTargetAPI,
    547                              mVerbose);
    548 }
    549 
    550 bool Slang::IsRSHeaderFile(const char *File) {
    551 #define RS_HEADER_ENTRY(name)  \
    552   if (::strcmp(File, #name "." RS_HEADER_SUFFIX) == 0)  \
    553     return true;
    554 ENUM_RS_HEADER()
    555 #undef RS_HEADER_ENTRY
    556   return false;
    557 }
    558 
    559 bool Slang::IsLocInRSHeaderFile(const clang::SourceLocation &Loc,
    560                                   const clang::SourceManager &SourceMgr) {
    561   clang::FullSourceLoc FSL(Loc, SourceMgr);
    562   clang::PresumedLoc PLoc = SourceMgr.getPresumedLoc(FSL);
    563 
    564   const char *Filename = PLoc.getFilename();
    565   if (!Filename) {
    566     return false;
    567   } else {
    568     return IsRSHeaderFile(llvm::sys::path::filename(Filename).data());
    569   }
    570 }
    571 
    572 bool Slang::compile(
    573     const std::list<std::pair<const char*, const char*> > &IOFiles64,
    574     const std::list<std::pair<const char*, const char*> > &IOFiles32,
    575     const std::list<std::pair<const char*, const char*> > &DepFiles,
    576     const RSCCOptions &Opts,
    577     clang::DiagnosticOptions &DiagOpts) {
    578   if (IOFiles32.empty())
    579     return true;
    580 
    581   if (Opts.mEmitDependency && (DepFiles.size() != IOFiles32.size())) {
    582     unsigned DiagID = mDiagEngine->getCustomDiagID(
    583         clang::DiagnosticsEngine::Error,
    584         "invalid parameter for output dependencies files.");
    585     getDiagnostics().Report(DiagID);
    586     return false;
    587   }
    588 
    589   if (Opts.mEmit3264 && (IOFiles64.size() != IOFiles32.size())) {
    590     slangAssert(false && "Should have equal number of 32/64-bit files");
    591     return false;
    592   }
    593 
    594   std::string RealPackageName;
    595 
    596   const char *InputFile, *Output64File, *Output32File, *BCOutputFile,
    597              *DepOutputFile;
    598 
    599   setIncludePaths(Opts.mIncludePaths);
    600   setOutputType(Opts.mOutputType);
    601   if (Opts.mEmitDependency) {
    602     setAdditionalDepTargets(Opts.mAdditionalDepTargets);
    603   }
    604 
    605   setDebugMetadataEmission(Opts.mDebugEmission);
    606 
    607   setOptimizationLevel(Opts.mOptimizationLevel);
    608 
    609   mAllowRSPrefix = Opts.mAllowRSPrefix;
    610 
    611   mTargetAPI = Opts.mTargetAPI;
    612   if (mTargetAPI != SLANG_DEVELOPMENT_TARGET_API &&
    613       (mTargetAPI < SLANG_MINIMUM_TARGET_API ||
    614        mTargetAPI > SLANG_MAXIMUM_TARGET_API)) {
    615     unsigned DiagID = mDiagEngine->getCustomDiagID(
    616         clang::DiagnosticsEngine::Error,
    617         "target API level '%0' is out of range ('%1' - '%2')");
    618     getDiagnostics().Report(DiagID) << mTargetAPI << SLANG_MINIMUM_TARGET_API
    619                                     << SLANG_MAXIMUM_TARGET_API;
    620     return false;
    621   }
    622 
    623   if (mTargetAPI >= SLANG_M_TARGET_API) {
    624     LangOpts.NativeHalfArgsAndReturns = 1;
    625     LangOpts.NativeHalfType = 1;
    626     LangOpts.HalfArgsAndReturns = 1;
    627   }
    628 
    629   mVerbose = Opts.mVerbose;
    630 
    631   // Skip generation of warnings a second time if we are doing more than just
    632   // a single pass over the input file.
    633   bool SuppressAllWarnings = (Opts.mOutputType != Slang::OT_Dependency);
    634 
    635   std::list<std::pair<const char*, const char*> >::const_iterator
    636       IOFile64Iter = IOFiles64.begin(),
    637       IOFile32Iter = IOFiles32.begin(),
    638       DepFileIter = DepFiles.begin();
    639 
    640   for (unsigned i = 0, e = IOFiles32.size(); i != e; i++) {
    641     InputFile = IOFile64Iter->first;
    642     Output64File = IOFile64Iter->second;
    643     Output32File = IOFile32Iter->second;
    644 
    645     if (!setInputSource(InputFile))
    646       return false;
    647 
    648     if (!setOutput(Output64File))
    649       return false;
    650 
    651     // For use with 64-bit compilation/reflection. This only sets the filename of
    652     // the 32-bit bitcode file, and doesn't actually verify it already exists.
    653     mOutput32FileName = Output32File;
    654 
    655     mIsFilterscript = isFilterscript(InputFile);
    656 
    657     CodeGenOpts.MainFileName = mInputFileName;
    658 
    659     if (Slang::compile(Opts) > 0)
    660       return false;
    661 
    662     if (!Opts.mJavaReflectionPackageName.empty()) {
    663       mRSContext->setReflectJavaPackageName(Opts.mJavaReflectionPackageName);
    664     }
    665     const std::string &RealPackageName =
    666         mRSContext->getReflectJavaPackageName();
    667 
    668     bool doReflection = true;
    669     if (Opts.mEmit3264 && (Opts.mBitWidth == 32)) {
    670       // Skip reflection on the 32-bit path if we are going to emit it on the
    671       // 64-bit path.
    672       doReflection = false;
    673     }
    674     if (Opts.mOutputType != Slang::OT_Dependency && doReflection) {
    675 
    676       if (Opts.mBitcodeStorage == BCST_CPP_CODE) {
    677         const std::string &outputFileName = (Opts.mBitWidth == 64) ?
    678                                             mOutputFileName : mOutput32FileName;
    679         RSReflectionCpp R(mRSContext, Opts.mJavaReflectionPathBase,
    680                           getInputFileName(), outputFileName);
    681         if (!R.reflect()) {
    682             return false;
    683         }
    684       } else {
    685         if (!Opts.mRSPackageName.empty()) {
    686           mRSContext->setRSPackageName(Opts.mRSPackageName);
    687         }
    688 
    689         std::vector<std::string> generatedFileNames;
    690         RSReflectionJava R(mRSContext, &generatedFileNames,
    691                            Opts.mJavaReflectionPathBase, getInputFileName(),
    692                            mOutputFileName,
    693                            Opts.mBitcodeStorage == BCST_JAVA_CODE);
    694         if (!R.reflect()) {
    695           // TODO Is this needed or will the error message have been printed
    696           // already? and why not for the C++ case?
    697           fprintf(stderr, "RSContext::reflectToJava : failed to do reflection "
    698                           "(%s)\n",
    699                   R.getLastError());
    700           return false;
    701         }
    702 
    703         for (std::vector<std::string>::const_iterator
    704                  I = generatedFileNames.begin(), E = generatedFileNames.end();
    705              I != E;
    706              I++) {
    707           std::string ReflectedName = RSSlangReflectUtils::ComputePackagedPath(
    708               Opts.mJavaReflectionPathBase.c_str(),
    709               (RealPackageName + OS_PATH_SEPARATOR_STR + *I).c_str());
    710           appendGeneratedFileName(ReflectedName + ".java");
    711         }
    712 
    713         if ((Opts.mOutputType == Slang::OT_Bitcode) &&
    714             (Opts.mBitcodeStorage == BCST_JAVA_CODE) &&
    715             !generateJavaBitcodeAccessor(Opts.mJavaReflectionPathBase,
    716                                          RealPackageName.c_str(),
    717                                          mRSContext->getLicenseNote())) {
    718           return false;
    719         }
    720       }
    721     }
    722 
    723     if (Opts.mEmitDependency) {
    724       BCOutputFile = DepFileIter->first;
    725       DepOutputFile = DepFileIter->second;
    726 
    727       setDepTargetBC(BCOutputFile);
    728 
    729       if (!setDepOutput(DepOutputFile))
    730         return false;
    731 
    732       if (SuppressAllWarnings) {
    733         getDiagnostics().setSuppressAllDiagnostics(true);
    734       }
    735       if (generateDepFile(Opts.mEmitPhonyDependency) > 0)
    736         return false;
    737       if (SuppressAllWarnings) {
    738         getDiagnostics().setSuppressAllDiagnostics(false);
    739       }
    740 
    741       DepFileIter++;
    742     }
    743 
    744     if (!checkODR(InputFile))
    745       return false;
    746 
    747     IOFile64Iter++;
    748     IOFile32Iter++;
    749   }
    750   return true;
    751 }
    752 
    753 }  // namespace slang
    754