slang.cpp revision ac4e18584b8768b3f68535fa5f16232e03974323
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 <string> 22#include <vector> 23 24#include "clang/AST/ASTConsumer.h" 25#include "clang/AST/ASTContext.h" 26 27#include "clang/Basic/DiagnosticIDs.h" 28#include "clang/Basic/FileManager.h" 29#include "clang/Basic/FileSystemOptions.h" 30#include "clang/Basic/LangOptions.h" 31#include "clang/Basic/SourceManager.h" 32#include "clang/Basic/TargetInfo.h" 33#include "clang/Basic/TargetOptions.h" 34 35#include "clang/Frontend/CodeGenOptions.h" 36#include "clang/Frontend/DiagnosticOptions.h" 37#include "clang/Frontend/DependencyOutputOptions.h" 38#include "clang/Frontend/FrontendDiagnostic.h" 39#include "clang/Frontend/TextDiagnosticPrinter.h" 40#include "clang/Frontend/Utils.h" 41 42#include "clang/Lex/Preprocessor.h" 43#include "clang/Lex/HeaderSearch.h" 44 45#include "clang/Parse/ParseAST.h" 46 47#include "llvm/ADT/IntrusiveRefCntPtr.h" 48 49#include "llvm/Bitcode/ReaderWriter.h" 50 51// More force linking 52#include "llvm/Linker.h" 53 54// Force linking all passes/vmcore stuffs to libslang.so 55#include "llvm/LinkAllPasses.h" 56#include "llvm/LinkAllVMCore.h" 57 58#include "llvm/Support/raw_ostream.h" 59#include "llvm/Support/MemoryBuffer.h" 60#include "llvm/Support/ErrorHandling.h" 61#include "llvm/Support/ManagedStatic.h" 62#include "llvm/Support/Path.h" 63#include "llvm/Support/TargetSelect.h" 64#include "llvm/Support/ToolOutputFile.h" 65 66#include "slang_assert.h" 67#include "slang_backend.h" 68#include "slang_utils.h" 69 70namespace { 71 72struct ForceSlangLinking { 73 ForceSlangLinking() { 74 // We must reference the functions in such a way that compilers will not 75 // delete it all as dead code, even with whole program optimization, 76 // yet is effectively a NO-OP. As the compiler isn't smart enough 77 // to know that getenv() never returns -1, this will do the job. 78 if (std::getenv("bar") != reinterpret_cast<char*>(-1)) 79 return; 80 81 // llvm-rs-link needs following functions existing in libslang. 82 llvm::ParseBitcodeFile(NULL, llvm::getGlobalContext(), NULL); 83 llvm::Linker::LinkModules(NULL, NULL, 0, NULL); 84 85 // llvm-rs-cc need this. 86 new clang::TextDiagnosticPrinter(llvm::errs(), 87 clang::DiagnosticOptions()); 88 } 89} ForceSlangLinking; 90 91} // namespace 92 93namespace slang { 94 95#if defined(__arm__) 96# define DEFAULT_TARGET_TRIPLE_STRING "armv7-none-linux-gnueabi" 97#elif defined(__x86_64__) 98# define DEFAULT_TARGET_TRIPLE_STRING "x86_64-unknown-linux" 99#else 100// let's use x86 as default target 101# define DEFAULT_TARGET_TRIPLE_STRING "i686-unknown-linux" 102#endif 103 104bool Slang::GlobalInitialized = false; 105 106// Language option (define the language feature for compiler such as C99) 107clang::LangOptions Slang::LangOpts; 108 109// Code generation option for the compiler 110clang::CodeGenOptions Slang::CodeGenOpts; 111 112// The named of metadata node that pragma resides (should be synced with 113// bcc.cpp) 114const llvm::StringRef Slang::PragmaMetadataName = "#pragma"; 115 116static inline llvm::tool_output_file * 117OpenOutputFile(const char *OutputFile, 118 unsigned Flags, 119 std::string* Error, 120 clang::DiagnosticsEngine *DiagEngine) 121{ 122 slangAssert((OutputFile != NULL) && (Error != NULL) && 123 (DiagEngine != NULL) && "Invalid parameter!"); 124 125 if (SlangUtils::CreateDirectoryWithParents( 126 llvm::sys::path::parent_path(OutputFile), Error)) { 127 llvm::tool_output_file *F = 128 new llvm::tool_output_file(OutputFile, *Error, Flags); 129 if (F != NULL) 130 return F; 131 } 132 133 // Report error here. 134 DiagEngine->Report(clang::diag::err_fe_error_opening) 135 << OutputFile << *Error; 136 137 return NULL; 138} 139 140void Slang::GlobalInitialization() { 141 if (!GlobalInitialized) { 142 // We only support x86, x64 and ARM target 143 144 // For ARM 145 LLVMInitializeARMTargetInfo(); 146 LLVMInitializeARMTarget(); 147 LLVMInitializeARMAsmPrinter(); 148 149 // For x86 and x64 150 LLVMInitializeX86TargetInfo(); 151 LLVMInitializeX86Target(); 152 LLVMInitializeX86AsmPrinter(); 153 154 // Please refer to include/clang/Basic/LangOptions.h to setup 155 // the options. 156 LangOpts.RTTI = 0; // Turn off the RTTI information support 157 LangOpts.NeXTRuntime = 0; // Turn off the NeXT runtime uses 158 LangOpts.C99 = 1; 159 160 CodeGenOpts.OptimizationLevel = 3; /* -O3 */ 161 162 GlobalInitialized = true; 163 } 164} 165 166void Slang::LLVMErrorHandler(void *UserData, const std::string &Message) { 167 clang::DiagnosticsEngine* DiagEngine = 168 static_cast<clang::DiagnosticsEngine *>(UserData); 169 170 DiagEngine->Report(clang::diag::err_fe_error_backend) << Message; 171 exit(1); 172} 173 174void Slang::createTarget(const std::string &Triple, const std::string &CPU, 175 const std::vector<std::string> &Features) { 176 if (!Triple.empty()) 177 mTargetOpts.Triple = Triple; 178 else 179 mTargetOpts.Triple = DEFAULT_TARGET_TRIPLE_STRING; 180 181 if (!CPU.empty()) 182 mTargetOpts.CPU = CPU; 183 184 if (!Features.empty()) 185 mTargetOpts.Features = Features; 186 187 mTarget.reset(clang::TargetInfo::CreateTargetInfo(*mDiagEngine, 188 mTargetOpts)); 189} 190 191void Slang::createFileManager() { 192 mFileSysOpt.reset(new clang::FileSystemOptions()); 193 mFileMgr.reset(new clang::FileManager(*mFileSysOpt)); 194} 195 196void Slang::createSourceManager() { 197 mSourceMgr.reset(new clang::SourceManager(*mDiagEngine, *mFileMgr)); 198} 199 200void Slang::createPreprocessor() { 201 // Default only search header file in current dir 202 clang::HeaderSearch *HeaderInfo = new clang::HeaderSearch(*mFileMgr, 203 *mDiagEngine); 204 205 mPP.reset(new clang::Preprocessor(*mDiagEngine, 206 LangOpts, 207 mTarget.get(), 208 *mSourceMgr, 209 *HeaderInfo, 210 *this, 211 NULL, 212 /* OwnsHeaderSearch = */true)); 213 // Initialize the preprocessor 214 mPragmas.clear(); 215 mPP->AddPragmaHandler(new PragmaRecorder(&mPragmas)); 216 217 std::vector<clang::DirectoryLookup> SearchList; 218 for (unsigned i = 0, e = mIncludePaths.size(); i != e; i++) { 219 if (const clang::DirectoryEntry *DE = 220 mFileMgr->getDirectory(mIncludePaths[i])) { 221 SearchList.push_back(clang::DirectoryLookup(DE, 222 clang::SrcMgr::C_System, 223 false, 224 false)); 225 } 226 } 227 228 HeaderInfo->SetSearchPaths(SearchList, 229 /* angledDirIdx = */1, 230 /* systemDixIdx = */1, 231 /* noCurDirSearch = */false); 232 233 initPreprocessor(); 234} 235 236void Slang::createASTContext() { 237 mASTContext.reset(new clang::ASTContext(LangOpts, 238 *mSourceMgr, 239 mTarget.get(), 240 mPP->getIdentifierTable(), 241 mPP->getSelectorTable(), 242 mPP->getBuiltinInfo(), 243 /* size_reserve = */0)); 244 initASTContext(); 245} 246 247clang::ASTConsumer * 248Slang::createBackend(const clang::CodeGenOptions& CodeGenOpts, 249 llvm::raw_ostream *OS, OutputType OT) { 250 return new Backend(mDiagEngine, CodeGenOpts, mTargetOpts, 251 &mPragmas, OS, OT); 252} 253 254Slang::Slang() : mInitialized(false), mDiagClient(NULL), mOT(OT_Default) { 255 GlobalInitialization(); 256} 257 258void Slang::init(const std::string &Triple, const std::string &CPU, 259 const std::vector<std::string> &Features, 260 clang::DiagnosticsEngine *DiagEngine, 261 DiagnosticBuffer *DiagClient) { 262 if (mInitialized) 263 return; 264 265 mDiagEngine = DiagEngine; 266 mDiagClient = DiagClient; 267 mDiag.reset(new clang::Diagnostic(mDiagEngine)); 268 initDiagnostic(); 269 llvm::install_fatal_error_handler(LLVMErrorHandler, mDiagEngine); 270 271 createTarget(Triple, CPU, Features); 272 createFileManager(); 273 createSourceManager(); 274 275 mInitialized = true; 276} 277 278clang::Module *Slang::loadModule(clang::SourceLocation ImportLoc, 279 clang::ModuleIdPath Path, 280 clang::Module::NameVisibilityKind Visibility, 281 bool IsInclusionDirective) { 282 //FIXME: Don't we have to implement this? 283 slangAssert(0 && "Not implemented"); 284 return NULL; 285} 286 287bool Slang::setInputSource(llvm::StringRef InputFile, 288 const char *Text, 289 size_t TextLength) { 290 mInputFileName = InputFile.str(); 291 292 // Reset the ID tables if we are reusing the SourceManager 293 mSourceMgr->clearIDTables(); 294 295 // Load the source 296 llvm::MemoryBuffer *SB = 297 llvm::MemoryBuffer::getMemBuffer(Text, Text + TextLength); 298 mSourceMgr->createMainFileIDForMemBuffer(SB); 299 300 if (mSourceMgr->getMainFileID().isInvalid()) { 301 mDiagEngine->Report(clang::diag::err_fe_error_reading) << InputFile; 302 return false; 303 } 304 return true; 305} 306 307bool Slang::setInputSource(llvm::StringRef InputFile) { 308 mInputFileName = InputFile.str(); 309 310 mSourceMgr->clearIDTables(); 311 312 const clang::FileEntry *File = mFileMgr->getFile(InputFile); 313 if (File) 314 mSourceMgr->createMainFileID(File); 315 316 if (mSourceMgr->getMainFileID().isInvalid()) { 317 mDiagEngine->Report(clang::diag::err_fe_error_reading) << InputFile; 318 return false; 319 } 320 321 return true; 322} 323 324bool Slang::setOutput(const char *OutputFile) { 325 llvm::sys::Path OutputFilePath(OutputFile); 326 std::string Error; 327 llvm::tool_output_file *OS = NULL; 328 329 switch (mOT) { 330 case OT_Dependency: 331 case OT_Assembly: 332 case OT_LLVMAssembly: { 333 OS = OpenOutputFile(OutputFile, 0, &Error, mDiagEngine); 334 break; 335 } 336 case OT_Nothing: { 337 break; 338 } 339 case OT_Object: 340 case OT_Bitcode: { 341 OS = OpenOutputFile(OutputFile, llvm::raw_fd_ostream::F_Binary, 342 &Error, mDiagEngine); 343 break; 344 } 345 default: { 346 llvm_unreachable("Unknown compiler output type"); 347 } 348 } 349 350 if (!Error.empty()) 351 return false; 352 353 mOS.reset(OS); 354 355 mOutputFileName = OutputFile; 356 357 return true; 358} 359 360bool Slang::setDepOutput(const char *OutputFile) { 361 llvm::sys::Path OutputFilePath(OutputFile); 362 std::string Error; 363 364 mDOS.reset(OpenOutputFile(OutputFile, 0, &Error, mDiagEngine)); 365 if (!Error.empty() || (mDOS.get() == NULL)) 366 return false; 367 368 mDepOutputFileName = OutputFile; 369 370 return true; 371} 372 373int Slang::generateDepFile() { 374 if (mDiagEngine->hasErrorOccurred()) 375 return 1; 376 if (mDOS.get() == NULL) 377 return 1; 378 379 // Initialize options for generating dependency file 380 clang::DependencyOutputOptions DepOpts; 381 DepOpts.IncludeSystemHeaders = 1; 382 DepOpts.OutputFile = mDepOutputFileName; 383 DepOpts.Targets = mAdditionalDepTargets; 384 DepOpts.Targets.push_back(mDepTargetBCFileName); 385 for (std::vector<std::string>::const_iterator 386 I = mGeneratedFileNames.begin(), E = mGeneratedFileNames.end(); 387 I != E; 388 I++) { 389 DepOpts.Targets.push_back(*I); 390 } 391 mGeneratedFileNames.clear(); 392 393 // Per-compilation needed initialization 394 createPreprocessor(); 395 AttachDependencyFileGen(*mPP.get(), DepOpts); 396 397 // Inform the diagnostic client we are processing a source file 398 mDiagClient->BeginSourceFile(LangOpts, mPP.get()); 399 400 // Go through the source file (no operations necessary) 401 clang::Token Tok; 402 mPP->EnterMainSourceFile(); 403 do { 404 mPP->Lex(Tok); 405 } while (Tok.isNot(clang::tok::eof)); 406 407 mPP->EndSourceFile(); 408 409 // Declare success if no error 410 if (!mDiagEngine->hasErrorOccurred()) 411 mDOS->keep(); 412 413 // Clean up after compilation 414 mPP.reset(); 415 mDOS.reset(); 416 417 return mDiagEngine->hasErrorOccurred() ? 1 : 0; 418} 419 420int Slang::compile() { 421 if (mDiagEngine->hasErrorOccurred()) 422 return 1; 423 if (mOS.get() == NULL) 424 return 1; 425 426 // Here is per-compilation needed initialization 427 createPreprocessor(); 428 createASTContext(); 429 430 mBackend.reset(createBackend(CodeGenOpts, &mOS->os(), mOT)); 431 432 // Inform the diagnostic client we are processing a source file 433 mDiagClient->BeginSourceFile(LangOpts, mPP.get()); 434 435 // The core of the slang compiler 436 ParseAST(*mPP, mBackend.get(), *mASTContext); 437 438 // Inform the diagnostic client we are done with previous source file 439 mDiagClient->EndSourceFile(); 440 441 // Declare success if no error 442 if (!mDiagEngine->hasErrorOccurred()) 443 mOS->keep(); 444 445 // The compilation ended, clear 446 mBackend.reset(); 447 mASTContext.reset(); 448 mPP.reset(); 449 mOS.reset(); 450 451 return mDiagEngine->hasErrorOccurred() ? 1 : 0; 452} 453 454void Slang::reset() { 455 llvm::errs() << mDiagClient->str(); 456 mDiagEngine->Reset(); 457 mDiagClient->reset(); 458} 459 460Slang::~Slang() { 461 llvm::llvm_shutdown(); 462} 463 464} // namespace slang 465