slang.cpp revision 8eac0940b8d13f8c4bad50942bf8527d64ccd12c
1#include "slang.hpp"
2
3#include <stdlib.h>                     /* for getenv */
4
5#include "libslang.h"
6
7#include "llvm/ADT/Twine.h"     /* for class llvm::Twine */
8
9#include "llvm/Target/TargetSelect.h"       /* for function LLVMInitialize[ARM|X86][TargetInfo|Target|AsmPrinter]() */
10
11#include "llvm/Support/MemoryBuffer.h"      /* for class llvm::MemoryBuffer */
12#include "llvm/Support/ErrorHandling.h"     /* for function llvm::install_fatal_error_handler() */
13#include "llvm/Support/ManagedStatic.h"     /* for class llvm::llvm_shutdown */
14
15#include "clang/Basic/TargetInfo.h"     /* for class clang::TargetInfo */
16#include "clang/Basic/LangOptions.h"    /* for class clang::LangOptions */
17#include "clang/Basic/TargetOptions.h"  /* for class clang::TargetOptions */
18
19#include "clang/Frontend/FrontendDiagnostic.h"      /* for clang::diag::* */
20
21#include "clang/Sema/ParseAST.h"        /* for function clang::ParseAST() */
22
23#if defined(__arm__)
24#   define DEFAULT_TARGET_TRIPLE_STRING "armv7-none-linux-gnueabi"
25#elif defined(__x86_64__)
26#   define DEFAULT_TARGET_TRIPLE_STRING "x86_64-unknown-linux"
27#else
28#   define DEFAULT_TARGET_TRIPLE_STRING "i686-unknown-linux"    // let's use x86 as default target
29#endif
30
31namespace slang {
32
33bool Slang::GlobalInitialized = false;
34
35/* Language option (define the language feature for compiler such as C99) */
36LangOptions Slang::LangOpts;
37
38/* Code generation option for the compiler */
39CodeGenOptions Slang::CodeGenOpts;
40
41const std::string Slang::TargetDescription = "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-n32";
42
43/* The named of metadata node that pragma resides (should be synced with bcc.cpp) */
44const llvm::Twine Slang::PragmaMetadataName = "#pragma";
45
46void Slang::GlobalInitialization() {
47    if(!GlobalInitialized) {
48        /* We only support x86, x64 and ARM target */
49
50        /* For ARM */
51        LLVMInitializeARMTargetInfo();
52        LLVMInitializeARMTarget();
53        LLVMInitializeARMAsmPrinter();
54
55        /* For x86 and x64 */
56        LLVMInitializeX86TargetInfo();
57        LLVMInitializeX86Target();
58        LLVMInitializeX86AsmPrinter();
59
60        /* Please refer to clang/include/clang/Basic/LangOptions.h for setting up the options */
61        LangOpts.RTTI = 0;  /* turn off the RTTI information support */
62        LangOpts.NeXTRuntime = 0;   /* turn off the NeXT runtime uses */
63        LangOpts.Bool = 1;  /* turn on 'bool', 'true', 'false' keywords. */
64
65        CodeGenOpts.OptimizationLevel = 3;  /* -O3 */
66
67        GlobalInitialized = true;
68    }
69
70    return;
71}
72
73void Slang::LLVMErrorHandler(void *UserData, const std::string &Message) {
74    Diagnostic* Diags = static_cast<Diagnostic*>(UserData);
75    Diags->Report(clang::diag::err_fe_error_backend) << Message;
76    exit(1);
77}
78
79void Slang::createTarget(const char* Triple, const char* CPU, const char** Features) {
80    if(Triple != NULL)
81        mTargetOpts.Triple = Triple;
82    else
83        mTargetOpts.Triple = DEFAULT_TARGET_TRIPLE_STRING;
84
85    if(CPU != NULL)
86        mTargetOpts.CPU = CPU;
87
88    mTarget.reset(TargetInfo::CreateTargetInfo(*mDiagnostics, mTargetOpts));
89
90    if(Features != NULL)
91        for(int i=0;Features[i]!=NULL;i++)
92            mTargetOpts.Features.push_back(Features[i]);
93
94    return;
95}
96
97void Slang::createPreprocessor() {
98  HeaderSearch* HS = new HeaderSearch(*mFileMgr); /* Default only search header file in current dir */
99
100  mPP.reset(new Preprocessor( *mDiagnostics,
101                              LangOpts,
102                              *mTarget,
103                              *mSourceMgr,
104                              *HS,
105                              NULL,
106                              true /* OwnsHeaderSearch */));
107  /* Initialize the prepocessor */
108  mPragmas.clear();
109  mPP->AddPragmaHandler(NULL, new PragmaRecorder(mPragmas));
110
111  /* Like ApplyHeaderSearchOptions in InitHeaderSearch.cpp */
112  const char*inclDir = getenv("ANDROID_BUILD_TOP");
113  if (inclDir) {
114    char *dirPath = new char[strlen(inclDir) + 33];
115    strcpy(dirPath, inclDir);
116    strcpy(dirPath + strlen(inclDir), "/frameworks/base/libs/rs/scriptc");
117
118    std::vector<DirectoryLookup> SearchList;
119    if (const DirectoryEntry *DE = mFileMgr->getDirectory(dirPath, dirPath + strlen(dirPath))) {
120      SearchList.push_back(DirectoryLookup(DE, SrcMgr::C_System, false, false));
121      HS->SetSearchPaths(SearchList, 1, false);
122    }
123  }
124
125  return;
126}
127
128Slang::Slang(const char* Triple, const char* CPU, const char** Features) :
129    mOutputType(SlangCompilerOutput_Default),
130    mAllowRSPrefix(false)
131{
132    GlobalInitialization();
133
134    createDiagnostic();
135    llvm::install_fatal_error_handler(LLVMErrorHandler, mDiagnostics.get());
136
137    createTarget(Triple, CPU, Features);
138    createFileManager();
139    createSourceManager();
140
141    return;
142}
143
144bool Slang::setInputSource(llvm::StringRef inputFile, const char* text, size_t textLength) {
145    mInputFileName = inputFile.str();
146
147    /* Reset the ID tables if we are reusing the SourceManager */
148    mSourceMgr->clearIDTables();
149
150    /* Load the source */
151    llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getMemBuffer(text, text + textLength);
152    mSourceMgr->createMainFileIDForMemBuffer(SB);
153
154    if(mSourceMgr->getMainFileID().isInvalid()) {
155        mDiagnostics->Report(clang::diag::err_fe_error_reading) << inputFile;
156        return false;
157    }
158
159    return true;
160}
161
162bool Slang::setInputSource(llvm::StringRef inputFile) {
163    mInputFileName = inputFile.str();
164
165    mSourceMgr->clearIDTables();
166
167    const FileEntry* File = mFileMgr->getFile(inputFile);
168    if(File)
169        mSourceMgr->createMainFileID(File, SourceLocation());
170
171    if(mSourceMgr->getMainFileID().isInvalid()) {
172        mDiagnostics->Report(clang::diag::err_fe_error_reading) << inputFile;
173        return false;
174    }
175
176    return true;
177}
178
179void Slang::setOutputType(SlangCompilerOutputTy outputType) {
180    mOutputType = outputType;
181    if( mOutputType != SlangCompilerOutput_Assembly &&
182        mOutputType != SlangCompilerOutput_LL &&
183        mOutputType != SlangCompilerOutput_Bitcode &&
184        mOutputType != SlangCompilerOutput_Nothing &&
185        mOutputType != SlangCompilerOutput_Obj)
186        mOutputType = SlangCompilerOutput_Default;
187    return;
188}
189
190static void _mkdir_given_a_file(const char *file) {
191    char buf[256];
192    char *tmp, *p = NULL;
193    size_t len = strlen(file);
194
195    if (len + 1 <= sizeof(buf))
196        tmp = buf;
197    else
198        tmp = new char [len + 1];
199
200    strcpy(tmp, file);
201
202    if (tmp[len - 1] == '/')
203        tmp[len - 1] = 0;
204
205    for (p = tmp + 1; *p; p++) {
206        if (*p == '/') {
207            *p = 0;
208            mkdir(tmp, S_IRWXU);
209            *p = '/';
210        }
211    }
212
213    if (tmp != buf)
214        delete[] tmp;
215}
216
217bool Slang::setOutput(const char* outputFile) {
218    std::string Error;
219
220    _mkdir_given_a_file(outputFile);
221
222    switch(mOutputType) {
223        case SlangCompilerOutput_Assembly:
224        case SlangCompilerOutput_LL:
225            mOS.reset( new llvm::raw_fd_ostream(outputFile, Error, 0) );
226        break;
227
228        case SlangCompilerOutput_Nothing:
229            mOS.reset();
230        break;
231
232        case SlangCompilerOutput_Obj:
233        case SlangCompilerOutput_Bitcode:
234        default:
235            mOS.reset( new llvm::raw_fd_ostream(outputFile, Error, llvm::raw_fd_ostream::F_Binary) );
236        break;
237    }
238
239    if(!Error.empty()) {
240        mOS.reset();
241        mDiagnostics->Report(clang::diag::err_fe_error_opening) << outputFile << Error;
242        return false;
243    }
244
245    mOutputFileName = outputFile;
246
247    return true;
248}
249
250int Slang::compile() {
251    if((mDiagnostics->getNumErrors() > 0) || (mOS.get() == NULL))
252        return mDiagnostics->getNumErrors();
253
254    /* Here is per-compilation needed initialization */
255    createPreprocessor();
256    createASTContext();
257    createRSContext();
258    //createBackend();
259    createRSBackend();
260
261    /* Inform the diagnostic client we are processing a source file */
262    mDiagClient->BeginSourceFile(LangOpts, mPP.get());
263
264    /* The core of the slang compiler */
265    ParseAST(*mPP, mBackend.get(), *mASTContext);
266
267    /* The compilation ended, clear up */
268    mBackend.reset();
269    mASTContext.reset();
270    mPP.reset();
271
272    /* Inform the diagnostic client we are done with previous source file */
273    mDiagClient->EndSourceFile();
274
275    return mDiagnostics->getNumErrors();
276}
277
278bool Slang::reflectToJava(const char* outputPackageName) {
279    if(mRSContext.get())
280        return mRSContext->reflectToJava(outputPackageName, mInputFileName, mOutputFileName);
281    else
282        return false;
283}
284
285bool Slang::reflectToJavaPath(const char* outputPathName) {
286    if(mRSContext.get())
287        return mRSContext->reflectToJavaPath(outputPathName);
288    else
289        return false;
290}
291
292void Slang::getPragmas(size_t* actualStringCount, size_t maxStringCount, char** strings) {
293    int stringCount = mPragmas.size() * 2;
294
295    if(actualStringCount)
296        *actualStringCount = stringCount;
297    if(stringCount > maxStringCount)
298        stringCount = maxStringCount;
299    if(strings)
300        for(PragmaList::const_iterator it = mPragmas.begin();
301            stringCount > 0;
302            stringCount-=2, it++)
303        {
304            *strings++ = const_cast<char*>(it->first.c_str());
305            *strings++ = const_cast<char*>(it->second.c_str());
306        }
307
308    return;
309}
310
311Slang::~Slang() {
312    llvm::llvm_shutdown();
313    return;
314}
315
316}   /* namespace slang */
317