clang API Documentation
00001 //===--- FrontendActions.cpp ----------------------------------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 00010 #include "clang/Frontend/FrontendActions.h" 00011 #include "clang/AST/ASTConsumer.h" 00012 #include "clang/Lex/HeaderSearch.h" 00013 #include "clang/Lex/Pragma.h" 00014 #include "clang/Lex/Preprocessor.h" 00015 #include "clang/Parse/Parser.h" 00016 #include "clang/Basic/FileManager.h" 00017 #include "clang/Frontend/ASTConsumers.h" 00018 #include "clang/Frontend/ASTUnit.h" 00019 #include "clang/Frontend/CompilerInstance.h" 00020 #include "clang/Frontend/FrontendDiagnostic.h" 00021 #include "clang/Frontend/Utils.h" 00022 #include "clang/Serialization/ASTWriter.h" 00023 #include "llvm/ADT/OwningPtr.h" 00024 #include "llvm/Support/FileSystem.h" 00025 #include "llvm/Support/MemoryBuffer.h" 00026 #include "llvm/Support/raw_ostream.h" 00027 #include "llvm/Support/system_error.h" 00028 00029 using namespace clang; 00030 00031 //===----------------------------------------------------------------------===// 00032 // Custom Actions 00033 //===----------------------------------------------------------------------===// 00034 00035 ASTConsumer *InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, 00036 StringRef InFile) { 00037 return new ASTConsumer(); 00038 } 00039 00040 void InitOnlyAction::ExecuteAction() { 00041 } 00042 00043 //===----------------------------------------------------------------------===// 00044 // AST Consumer Actions 00045 //===----------------------------------------------------------------------===// 00046 00047 ASTConsumer *ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, 00048 StringRef InFile) { 00049 if (raw_ostream *OS = CI.createDefaultOutputFile(false, InFile)) 00050 return CreateASTPrinter(OS); 00051 return 0; 00052 } 00053 00054 ASTConsumer *ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, 00055 StringRef InFile) { 00056 return CreateASTDumper(); 00057 } 00058 00059 ASTConsumer *ASTDumpXMLAction::CreateASTConsumer(CompilerInstance &CI, 00060 StringRef InFile) { 00061 raw_ostream *OS; 00062 if (CI.getFrontendOpts().OutputFile.empty()) 00063 OS = &llvm::outs(); 00064 else 00065 OS = CI.createDefaultOutputFile(false, InFile); 00066 if (!OS) return 0; 00067 return CreateASTDumperXML(*OS); 00068 } 00069 00070 ASTConsumer *ASTViewAction::CreateASTConsumer(CompilerInstance &CI, 00071 StringRef InFile) { 00072 return CreateASTViewer(); 00073 } 00074 00075 ASTConsumer *DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI, 00076 StringRef InFile) { 00077 return CreateDeclContextPrinter(); 00078 } 00079 00080 ASTConsumer *GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, 00081 StringRef InFile) { 00082 std::string Sysroot; 00083 std::string OutputFile; 00084 raw_ostream *OS = 0; 00085 if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS)) 00086 return 0; 00087 00088 if (!CI.getFrontendOpts().RelocatablePCH) 00089 Sysroot.clear(); 00090 return new PCHGenerator(CI.getPreprocessor(), OutputFile, 0, Sysroot, OS); 00091 } 00092 00093 bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI, 00094 StringRef InFile, 00095 std::string &Sysroot, 00096 std::string &OutputFile, 00097 raw_ostream *&OS) { 00098 Sysroot = CI.getHeaderSearchOpts().Sysroot; 00099 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) { 00100 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot); 00101 return true; 00102 } 00103 00104 // We use createOutputFile here because this is exposed via libclang, and we 00105 // must disable the RemoveFileOnSignal behavior. 00106 // We use a temporary to avoid race conditions. 00107 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true, 00108 /*RemoveFileOnSignal=*/false, InFile, 00109 /*Extension=*/"", /*useTemporary=*/true); 00110 if (!OS) 00111 return true; 00112 00113 OutputFile = CI.getFrontendOpts().OutputFile; 00114 return false; 00115 } 00116 00117 ASTConsumer *GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI, 00118 StringRef InFile) { 00119 std::string Sysroot; 00120 std::string OutputFile; 00121 raw_ostream *OS = 0; 00122 if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS)) 00123 return 0; 00124 00125 return new PCHGenerator(CI.getPreprocessor(), OutputFile, Module, 00126 Sysroot, OS); 00127 } 00128 00129 /// \brief Collect the set of header includes needed to construct the given 00130 /// module. 00131 /// 00132 /// \param Module The module we're collecting includes from. 00133 /// 00134 /// \param Includes Will be augmented with the set of #includes or #imports 00135 /// needed to load all of the named headers. 00136 static void collectModuleHeaderIncludes(const LangOptions &LangOpts, 00137 FileManager &FileMgr, 00138 ModuleMap &ModMap, 00139 clang::Module *Module, 00140 SmallString<256> &Includes) { 00141 // Don't collect any headers for unavailable modules. 00142 if (!Module->isAvailable()) 00143 return; 00144 00145 // Add includes for each of these headers. 00146 for (unsigned I = 0, N = Module->Headers.size(); I != N; ++I) { 00147 if (LangOpts.ObjC1) 00148 Includes += "#import \""; 00149 else 00150 Includes += "#include \""; 00151 Includes += Module->Headers[I]->getName(); 00152 Includes += "\"\n"; 00153 } 00154 00155 if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader()) { 00156 if (Module->Parent) { 00157 // Include the umbrella header for submodules. 00158 if (LangOpts.ObjC1) 00159 Includes += "#import \""; 00160 else 00161 Includes += "#include \""; 00162 Includes += UmbrellaHeader->getName(); 00163 Includes += "\"\n"; 00164 } 00165 } else if (const DirectoryEntry *UmbrellaDir = Module->getUmbrellaDir()) { 00166 // Add all of the headers we find in this subdirectory. 00167 llvm::error_code EC; 00168 SmallString<128> DirNative; 00169 llvm::sys::path::native(UmbrellaDir->getName(), DirNative); 00170 for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative.str(), EC), 00171 DirEnd; 00172 Dir != DirEnd && !EC; Dir.increment(EC)) { 00173 // Check whether this entry has an extension typically associated with 00174 // headers. 00175 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path())) 00176 .Cases(".h", ".H", ".hh", ".hpp", true) 00177 .Default(false)) 00178 continue; 00179 00180 // If this header is marked 'unavailable' in this module, don't include 00181 // it. 00182 if (const FileEntry *Header = FileMgr.getFile(Dir->path())) 00183 if (ModMap.isHeaderInUnavailableModule(Header)) 00184 continue; 00185 00186 // Include this header umbrella header for submodules. 00187 if (LangOpts.ObjC1) 00188 Includes += "#import \""; 00189 else 00190 Includes += "#include \""; 00191 Includes += Dir->path(); 00192 Includes += "\"\n"; 00193 } 00194 } 00195 00196 // Recurse into submodules. 00197 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(), 00198 SubEnd = Module->submodule_end(); 00199 Sub != SubEnd; ++Sub) 00200 collectModuleHeaderIncludes(LangOpts, FileMgr, ModMap, *Sub, Includes); 00201 } 00202 00203 bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI, 00204 StringRef Filename) { 00205 // Find the module map file. 00206 const FileEntry *ModuleMap = CI.getFileManager().getFile(Filename); 00207 if (!ModuleMap) { 00208 CI.getDiagnostics().Report(diag::err_module_map_not_found) 00209 << Filename; 00210 return false; 00211 } 00212 00213 // Parse the module map file. 00214 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo(); 00215 if (HS.loadModuleMapFile(ModuleMap)) 00216 return false; 00217 00218 if (CI.getLangOpts().CurrentModule.empty()) { 00219 CI.getDiagnostics().Report(diag::err_missing_module_name); 00220 00221 // FIXME: Eventually, we could consider asking whether there was just 00222 // a single module described in the module map, and use that as a 00223 // default. Then it would be fairly trivial to just "compile" a module 00224 // map with a single module (the common case). 00225 return false; 00226 } 00227 00228 // Dig out the module definition. 00229 Module = HS.lookupModule(CI.getLangOpts().CurrentModule, 00230 /*AllowSearch=*/false); 00231 if (!Module) { 00232 CI.getDiagnostics().Report(diag::err_missing_module) 00233 << CI.getLangOpts().CurrentModule << Filename; 00234 00235 return false; 00236 } 00237 00238 // Check whether we can build this module at all. 00239 StringRef Feature; 00240 if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Feature)) { 00241 CI.getDiagnostics().Report(diag::err_module_unavailable) 00242 << Module->getFullModuleName() 00243 << Feature; 00244 00245 return false; 00246 } 00247 00248 // Do we have an umbrella header for this module? 00249 const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader(); 00250 00251 // Collect the set of #includes we need to build the module. 00252 SmallString<256> HeaderContents; 00253 collectModuleHeaderIncludes(CI.getLangOpts(), CI.getFileManager(), 00254 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), 00255 Module, HeaderContents); 00256 if (UmbrellaHeader && HeaderContents.empty()) { 00257 // Simple case: we have an umbrella header and there are no additional 00258 // includes, we can just parse the umbrella header directly. 00259 setCurrentInput(FrontendInputFile(UmbrellaHeader->getName(), 00260 getCurrentFileKind(), 00261 Module->IsSystem)); 00262 return true; 00263 } 00264 00265 FileManager &FileMgr = CI.getFileManager(); 00266 SmallString<128> HeaderName; 00267 time_t ModTime; 00268 if (UmbrellaHeader) { 00269 // Read in the umbrella header. 00270 // FIXME: Go through the source manager; the umbrella header may have 00271 // been overridden. 00272 std::string ErrorStr; 00273 llvm::MemoryBuffer *UmbrellaContents 00274 = FileMgr.getBufferForFile(UmbrellaHeader, &ErrorStr); 00275 if (!UmbrellaContents) { 00276 CI.getDiagnostics().Report(diag::err_missing_umbrella_header) 00277 << UmbrellaHeader->getName() << ErrorStr; 00278 return false; 00279 } 00280 00281 // Combine the contents of the umbrella header with the automatically- 00282 // generated includes. 00283 SmallString<256> OldContents = HeaderContents; 00284 HeaderContents = UmbrellaContents->getBuffer(); 00285 HeaderContents += "\n\n"; 00286 HeaderContents += "/* Module includes */\n"; 00287 HeaderContents += OldContents; 00288 00289 // Pretend that we're parsing the umbrella header. 00290 HeaderName = UmbrellaHeader->getName(); 00291 ModTime = UmbrellaHeader->getModificationTime(); 00292 00293 delete UmbrellaContents; 00294 } else { 00295 // Pick an innocuous-sounding name for the umbrella header. 00296 HeaderName = Module->Name + ".h"; 00297 if (FileMgr.getFile(HeaderName, /*OpenFile=*/false, 00298 /*CacheFailure=*/false)) { 00299 // Try again! 00300 HeaderName = Module->Name + "-module.h"; 00301 if (FileMgr.getFile(HeaderName, /*OpenFile=*/false, 00302 /*CacheFailure=*/false)) { 00303 // Pick something ridiculous and go with it. 00304 HeaderName = Module->Name + "-module.hmod"; 00305 } 00306 } 00307 ModTime = time(0); 00308 } 00309 00310 // Remap the contents of the header name we're using to our synthesized 00311 // buffer. 00312 const FileEntry *HeaderFile = FileMgr.getVirtualFile(HeaderName, 00313 HeaderContents.size(), 00314 ModTime); 00315 llvm::MemoryBuffer *HeaderContentsBuf 00316 = llvm::MemoryBuffer::getMemBufferCopy(HeaderContents); 00317 CI.getSourceManager().overrideFileContents(HeaderFile, HeaderContentsBuf); 00318 setCurrentInput(FrontendInputFile(HeaderName, getCurrentFileKind(), 00319 Module->IsSystem)); 00320 return true; 00321 } 00322 00323 bool GenerateModuleAction::ComputeASTConsumerArguments(CompilerInstance &CI, 00324 StringRef InFile, 00325 std::string &Sysroot, 00326 std::string &OutputFile, 00327 raw_ostream *&OS) { 00328 // If no output file was provided, figure out where this module would go 00329 // in the module cache. 00330 if (CI.getFrontendOpts().OutputFile.empty()) { 00331 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo(); 00332 SmallString<256> ModuleFileName(HS.getModuleCachePath()); 00333 llvm::sys::path::append(ModuleFileName, 00334 CI.getLangOpts().CurrentModule + ".pcm"); 00335 CI.getFrontendOpts().OutputFile = ModuleFileName.str(); 00336 } 00337 00338 // We use createOutputFile here because this is exposed via libclang, and we 00339 // must disable the RemoveFileOnSignal behavior. 00340 // We use a temporary to avoid race conditions. 00341 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true, 00342 /*RemoveFileOnSignal=*/false, InFile, 00343 /*Extension=*/"", /*useTemporary=*/true, 00344 /*CreateMissingDirectories=*/true); 00345 if (!OS) 00346 return true; 00347 00348 OutputFile = CI.getFrontendOpts().OutputFile; 00349 return false; 00350 } 00351 00352 ASTConsumer *SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, 00353 StringRef InFile) { 00354 return new ASTConsumer(); 00355 } 00356 00357 //===----------------------------------------------------------------------===// 00358 // Preprocessor Actions 00359 //===----------------------------------------------------------------------===// 00360 00361 void DumpRawTokensAction::ExecuteAction() { 00362 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 00363 SourceManager &SM = PP.getSourceManager(); 00364 00365 // Start lexing the specified input file. 00366 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID()); 00367 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts()); 00368 RawLex.SetKeepWhitespaceMode(true); 00369 00370 Token RawTok; 00371 RawLex.LexFromRawLexer(RawTok); 00372 while (RawTok.isNot(tok::eof)) { 00373 PP.DumpToken(RawTok, true); 00374 llvm::errs() << "\n"; 00375 RawLex.LexFromRawLexer(RawTok); 00376 } 00377 } 00378 00379 void DumpTokensAction::ExecuteAction() { 00380 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 00381 // Start preprocessing the specified input file. 00382 Token Tok; 00383 PP.EnterMainSourceFile(); 00384 do { 00385 PP.Lex(Tok); 00386 PP.DumpToken(Tok, true); 00387 llvm::errs() << "\n"; 00388 } while (Tok.isNot(tok::eof)); 00389 } 00390 00391 void GeneratePTHAction::ExecuteAction() { 00392 CompilerInstance &CI = getCompilerInstance(); 00393 if (CI.getFrontendOpts().OutputFile.empty() || 00394 CI.getFrontendOpts().OutputFile == "-") { 00395 // FIXME: Don't fail this way. 00396 // FIXME: Verify that we can actually seek in the given file. 00397 llvm::report_fatal_error("PTH requires a seekable file for output!"); 00398 } 00399 llvm::raw_fd_ostream *OS = 00400 CI.createDefaultOutputFile(true, getCurrentFile()); 00401 if (!OS) return; 00402 00403 CacheTokens(CI.getPreprocessor(), OS); 00404 } 00405 00406 void PreprocessOnlyAction::ExecuteAction() { 00407 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 00408 00409 // Ignore unknown pragmas. 00410 PP.AddPragmaHandler(new EmptyPragmaHandler()); 00411 00412 Token Tok; 00413 // Start parsing the specified input file. 00414 PP.EnterMainSourceFile(); 00415 do { 00416 PP.Lex(Tok); 00417 } while (Tok.isNot(tok::eof)); 00418 } 00419 00420 void PrintPreprocessedAction::ExecuteAction() { 00421 CompilerInstance &CI = getCompilerInstance(); 00422 // Output file may need to be set to 'Binary', to avoid converting Unix style 00423 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>). 00424 // 00425 // Look to see what type of line endings the file uses. If there's a 00426 // CRLF, then we won't open the file up in binary mode. If there is 00427 // just an LF or CR, then we will open the file up in binary mode. 00428 // In this fashion, the output format should match the input format, unless 00429 // the input format has inconsistent line endings. 00430 // 00431 // This should be a relatively fast operation since most files won't have 00432 // all of their source code on a single line. However, that is still a 00433 // concern, so if we scan for too long, we'll just assume the file should 00434 // be opened in binary mode. 00435 bool BinaryMode = true; 00436 bool InvalidFile = false; 00437 const SourceManager& SM = CI.getSourceManager(); 00438 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(), 00439 &InvalidFile); 00440 if (!InvalidFile) { 00441 const char *cur = Buffer->getBufferStart(); 00442 const char *end = Buffer->getBufferEnd(); 00443 const char *next = (cur != end) ? cur + 1 : end; 00444 00445 // Limit ourselves to only scanning 256 characters into the source 00446 // file. This is mostly a sanity check in case the file has no 00447 // newlines whatsoever. 00448 if (end - cur > 256) end = cur + 256; 00449 00450 while (next < end) { 00451 if (*cur == 0x0D) { // CR 00452 if (*next == 0x0A) // CRLF 00453 BinaryMode = false; 00454 00455 break; 00456 } else if (*cur == 0x0A) // LF 00457 break; 00458 00459 ++cur, ++next; 00460 } 00461 } 00462 00463 raw_ostream *OS = CI.createDefaultOutputFile(BinaryMode, getCurrentFile()); 00464 if (!OS) return; 00465 00466 DoPrintPreprocessedInput(CI.getPreprocessor(), OS, 00467 CI.getPreprocessorOutputOpts()); 00468 } 00469 00470 void PrintPreambleAction::ExecuteAction() { 00471 switch (getCurrentFileKind()) { 00472 case IK_C: 00473 case IK_CXX: 00474 case IK_ObjC: 00475 case IK_ObjCXX: 00476 case IK_OpenCL: 00477 case IK_CUDA: 00478 break; 00479 00480 case IK_None: 00481 case IK_Asm: 00482 case IK_PreprocessedC: 00483 case IK_PreprocessedCXX: 00484 case IK_PreprocessedObjC: 00485 case IK_PreprocessedObjCXX: 00486 case IK_AST: 00487 case IK_LLVM_IR: 00488 // We can't do anything with these. 00489 return; 00490 } 00491 00492 CompilerInstance &CI = getCompilerInstance(); 00493 llvm::MemoryBuffer *Buffer 00494 = CI.getFileManager().getBufferForFile(getCurrentFile()); 00495 if (Buffer) { 00496 unsigned Preamble = Lexer::ComputePreamble(Buffer, CI.getLangOpts()).first; 00497 llvm::outs().write(Buffer->getBufferStart(), Preamble); 00498 delete Buffer; 00499 } 00500 }