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