FrontendActions.cpp revision b7a7819473709c01ea024a2dc15e99d38f0f8760
1//===--- FrontendActions.cpp ----------------------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9 10#include "clang/Frontend/FrontendActions.h" 11#include "clang/AST/ASTConsumer.h" 12#include "clang/Lex/HeaderSearch.h" 13#include "clang/Lex/Pragma.h" 14#include "clang/Lex/Preprocessor.h" 15#include "clang/Parse/Parser.h" 16#include "clang/Basic/FileManager.h" 17#include "clang/Frontend/ASTConsumers.h" 18#include "clang/Frontend/ASTUnit.h" 19#include "clang/Frontend/CompilerInstance.h" 20#include "clang/Frontend/FrontendDiagnostic.h" 21#include "clang/Frontend/Utils.h" 22#include "clang/Serialization/ASTWriter.h" 23#include "llvm/ADT/OwningPtr.h" 24#include "llvm/Support/FileSystem.h" 25#include "llvm/Support/MemoryBuffer.h" 26#include "llvm/Support/raw_ostream.h" 27#include "llvm/Support/system_error.h" 28 29using namespace clang; 30 31//===----------------------------------------------------------------------===// 32// Custom Actions 33//===----------------------------------------------------------------------===// 34 35ASTConsumer *InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, 36 StringRef InFile) { 37 return new ASTConsumer(); 38} 39 40void InitOnlyAction::ExecuteAction() { 41} 42 43//===----------------------------------------------------------------------===// 44// AST Consumer Actions 45//===----------------------------------------------------------------------===// 46 47ASTConsumer *ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, 48 StringRef InFile) { 49 if (raw_ostream *OS = CI.createDefaultOutputFile(false, InFile)) 50 return CreateASTPrinter(OS); 51 return 0; 52} 53 54ASTConsumer *ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, 55 StringRef InFile) { 56 return CreateASTDumper(); 57} 58 59ASTConsumer *ASTDumpXMLAction::CreateASTConsumer(CompilerInstance &CI, 60 StringRef InFile) { 61 raw_ostream *OS; 62 if (CI.getFrontendOpts().OutputFile.empty()) 63 OS = &llvm::outs(); 64 else 65 OS = CI.createDefaultOutputFile(false, InFile); 66 if (!OS) return 0; 67 return CreateASTDumperXML(*OS); 68} 69 70ASTConsumer *ASTViewAction::CreateASTConsumer(CompilerInstance &CI, 71 StringRef InFile) { 72 return CreateASTViewer(); 73} 74 75ASTConsumer *DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI, 76 StringRef InFile) { 77 return CreateDeclContextPrinter(); 78} 79 80ASTConsumer *GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, 81 StringRef InFile) { 82 std::string Sysroot; 83 std::string OutputFile; 84 raw_ostream *OS = 0; 85 if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS)) 86 return 0; 87 88 if (!CI.getFrontendOpts().RelocatablePCH) 89 Sysroot.clear(); 90 return new PCHGenerator(CI.getPreprocessor(), OutputFile, 0, Sysroot, OS); 91} 92 93bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI, 94 StringRef InFile, 95 std::string &Sysroot, 96 std::string &OutputFile, 97 raw_ostream *&OS) { 98 Sysroot = CI.getHeaderSearchOpts().Sysroot; 99 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) { 100 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot); 101 return true; 102 } 103 104 // We use createOutputFile here because this is exposed via libclang, and we 105 // must disable the RemoveFileOnSignal behavior. 106 // We use a temporary to avoid race conditions. 107 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true, 108 /*RemoveFileOnSignal=*/false, InFile, 109 /*Extension=*/"", /*useTemporary=*/true); 110 if (!OS) 111 return true; 112 113 OutputFile = CI.getFrontendOpts().OutputFile; 114 return false; 115} 116 117ASTConsumer *GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI, 118 StringRef InFile) { 119 std::string Sysroot; 120 std::string OutputFile; 121 raw_ostream *OS = 0; 122 if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS)) 123 return 0; 124 125 return new PCHGenerator(CI.getPreprocessor(), OutputFile, Module, 126 Sysroot, OS); 127} 128 129/// \brief Collect the set of header includes needed to construct the given 130/// module. 131/// 132/// \param Module The module we're collecting includes from. 133/// 134/// \param Includes Will be augmented with the set of #includes or #imports 135/// needed to load all of the named headers. 136static void collectModuleHeaderIncludes(const LangOptions &LangOpts, 137 clang::Module *Module, 138 llvm::SmallString<256> &Includes) { 139 // Don't collect any headers for unavailable modules. 140 if (!Module->isAvailable()) 141 return; 142 143 // Add includes for each of these headers. 144 for (unsigned I = 0, N = Module->Headers.size(); I != N; ++I) { 145 if (LangOpts.ObjC1) 146 Includes += "#import \""; 147 else 148 Includes += "#include \""; 149 Includes += Module->Headers[I]->getName(); 150 Includes += "\"\n"; 151 } 152 153 if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader()) { 154 if (Module->Parent) { 155 // Include the umbrella header for submodules. 156 if (LangOpts.ObjC1) 157 Includes += "#import \""; 158 else 159 Includes += "#include \""; 160 Includes += UmbrellaHeader->getName(); 161 Includes += "\"\n"; 162 } 163 } else if (const DirectoryEntry *UmbrellaDir = Module->getUmbrellaDir()) { 164 // Add all of the headers we find in this subdirectory (FIXME: recursively!). 165 llvm::error_code EC; 166 llvm::SmallString<128> DirNative; 167 llvm::sys::path::native(UmbrellaDir->getName(), DirNative); 168 for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative.str(), EC), 169 DirEnd; 170 Dir != DirEnd && !EC; Dir.increment(EC)) { 171 // Check whether this entry has an extension typically associated with 172 // headers. 173 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path())) 174 .Cases(".h", ".H", ".hh", ".hpp", true) 175 .Default(false)) 176 continue; 177 178 // Include this header umbrella header for submodules. 179 if (LangOpts.ObjC1) 180 Includes += "#import \""; 181 else 182 Includes += "#include \""; 183 Includes += Dir->path(); 184 Includes += "\"\n"; 185 } 186 } 187 188 // Recurse into submodules. 189 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(), 190 SubEnd = Module->submodule_end(); 191 Sub != SubEnd; ++Sub) 192 collectModuleHeaderIncludes(LangOpts, *Sub, Includes); 193} 194 195bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI, 196 StringRef Filename) { 197 // Find the module map file. 198 const FileEntry *ModuleMap = CI.getFileManager().getFile(Filename); 199 if (!ModuleMap) { 200 CI.getDiagnostics().Report(diag::err_module_map_not_found) 201 << Filename; 202 return false; 203 } 204 205 // Parse the module map file. 206 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo(); 207 if (HS.loadModuleMapFile(ModuleMap)) 208 return false; 209 210 if (CI.getLangOpts().CurrentModule.empty()) { 211 CI.getDiagnostics().Report(diag::err_missing_module_name); 212 213 // FIXME: Eventually, we could consider asking whether there was just 214 // a single module described in the module map, and use that as a 215 // default. Then it would be fairly trivial to just "compile" a module 216 // map with a single module (the common case). 217 return false; 218 } 219 220 // Dig out the module definition. 221 Module = HS.getModule(CI.getLangOpts().CurrentModule, /*AllowSearch=*/false); 222 if (!Module) { 223 CI.getDiagnostics().Report(diag::err_missing_module) 224 << CI.getLangOpts().CurrentModule << Filename; 225 226 return false; 227 } 228 229 // Check whether we can build this module at all. 230 StringRef Feature; 231 if (!Module->isAvailable(CI.getLangOpts(), Feature)) { 232 CI.getDiagnostics().Report(diag::err_module_unavailable) 233 << Module->getFullModuleName() 234 << Feature; 235 236 return false; 237 } 238 239 // Do we have an umbrella header for this module? 240 const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader(); 241 242 // Collect the set of #includes we need to build the module. 243 llvm::SmallString<256> HeaderContents; 244 collectModuleHeaderIncludes(CI.getLangOpts(), Module, HeaderContents); 245 if (UmbrellaHeader && HeaderContents.empty()) { 246 // Simple case: we have an umbrella header and there are no additional 247 // includes, we can just parse the umbrella header directly. 248 setCurrentFile(UmbrellaHeader->getName(), getCurrentFileKind()); 249 return true; 250 } 251 252 FileManager &FileMgr = CI.getFileManager(); 253 llvm::SmallString<128> HeaderName; 254 time_t ModTime; 255 if (UmbrellaHeader) { 256 // Read in the umbrella header. 257 // FIXME: Go through the source manager; the umbrella header may have 258 // been overridden. 259 std::string ErrorStr; 260 llvm::MemoryBuffer *UmbrellaContents 261 = FileMgr.getBufferForFile(UmbrellaHeader, &ErrorStr); 262 if (!UmbrellaContents) { 263 CI.getDiagnostics().Report(diag::err_missing_umbrella_header) 264 << UmbrellaHeader->getName() << ErrorStr; 265 return false; 266 } 267 268 // Combine the contents of the umbrella header with the automatically- 269 // generated includes. 270 llvm::SmallString<256> OldContents = HeaderContents; 271 HeaderContents = UmbrellaContents->getBuffer(); 272 HeaderContents += "\n\n"; 273 HeaderContents += "/* Module includes */\n"; 274 HeaderContents += OldContents; 275 276 // Pretend that we're parsing the umbrella header. 277 HeaderName = UmbrellaHeader->getName(); 278 ModTime = UmbrellaHeader->getModificationTime(); 279 280 delete UmbrellaContents; 281 } else { 282 // Pick an innocuous-sounding name for the umbrella header. 283 HeaderName = Module->Name + ".h"; 284 if (FileMgr.getFile(HeaderName, /*OpenFile=*/false, 285 /*CacheFailure=*/false)) { 286 // Try again! 287 HeaderName = Module->Name + "-module.h"; 288 if (FileMgr.getFile(HeaderName, /*OpenFile=*/false, 289 /*CacheFailure=*/false)) { 290 // Pick something ridiculous and go with it. 291 HeaderName = Module->Name + "-module.hmod"; 292 } 293 } 294 ModTime = time(0); 295 } 296 297 // Remap the contents of the header name we're using to our synthesized 298 // buffer. 299 const FileEntry *HeaderFile = FileMgr.getVirtualFile(HeaderName, 300 HeaderContents.size(), 301 ModTime); 302 llvm::MemoryBuffer *HeaderContentsBuf 303 = llvm::MemoryBuffer::getMemBufferCopy(HeaderContents); 304 CI.getSourceManager().overrideFileContents(HeaderFile, HeaderContentsBuf); 305 306 setCurrentFile(HeaderName, getCurrentFileKind()); 307 return true; 308} 309 310bool GenerateModuleAction::ComputeASTConsumerArguments(CompilerInstance &CI, 311 StringRef InFile, 312 std::string &Sysroot, 313 std::string &OutputFile, 314 raw_ostream *&OS) { 315 // If no output file was provided, figure out where this module would go 316 // in the module cache. 317 if (CI.getFrontendOpts().OutputFile.empty()) { 318 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo(); 319 llvm::SmallString<256> ModuleFileName(HS.getModuleCachePath()); 320 llvm::sys::path::append(ModuleFileName, 321 CI.getLangOpts().CurrentModule + ".pcm"); 322 CI.getFrontendOpts().OutputFile = ModuleFileName.str(); 323 } 324 325 // We use createOutputFile here because this is exposed via libclang, and we 326 // must disable the RemoveFileOnSignal behavior. 327 // We use a temporary to avoid race conditions. 328 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true, 329 /*RemoveFileOnSignal=*/false, InFile, 330 /*Extension=*/"", /*useTemporary=*/true); 331 if (!OS) 332 return true; 333 334 OutputFile = CI.getFrontendOpts().OutputFile; 335 return false; 336} 337 338ASTConsumer *SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, 339 StringRef InFile) { 340 return new ASTConsumer(); 341} 342 343//===----------------------------------------------------------------------===// 344// Preprocessor Actions 345//===----------------------------------------------------------------------===// 346 347void DumpRawTokensAction::ExecuteAction() { 348 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 349 SourceManager &SM = PP.getSourceManager(); 350 351 // Start lexing the specified input file. 352 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID()); 353 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOptions()); 354 RawLex.SetKeepWhitespaceMode(true); 355 356 Token RawTok; 357 RawLex.LexFromRawLexer(RawTok); 358 while (RawTok.isNot(tok::eof)) { 359 PP.DumpToken(RawTok, true); 360 llvm::errs() << "\n"; 361 RawLex.LexFromRawLexer(RawTok); 362 } 363} 364 365void DumpTokensAction::ExecuteAction() { 366 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 367 // Start preprocessing the specified input file. 368 Token Tok; 369 PP.EnterMainSourceFile(); 370 do { 371 PP.Lex(Tok); 372 PP.DumpToken(Tok, true); 373 llvm::errs() << "\n"; 374 } while (Tok.isNot(tok::eof)); 375} 376 377void GeneratePTHAction::ExecuteAction() { 378 CompilerInstance &CI = getCompilerInstance(); 379 if (CI.getFrontendOpts().OutputFile.empty() || 380 CI.getFrontendOpts().OutputFile == "-") { 381 // FIXME: Don't fail this way. 382 // FIXME: Verify that we can actually seek in the given file. 383 llvm::report_fatal_error("PTH requires a seekable file for output!"); 384 } 385 llvm::raw_fd_ostream *OS = 386 CI.createDefaultOutputFile(true, getCurrentFile()); 387 if (!OS) return; 388 389 CacheTokens(CI.getPreprocessor(), OS); 390} 391 392void PreprocessOnlyAction::ExecuteAction() { 393 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 394 395 // Ignore unknown pragmas. 396 PP.AddPragmaHandler(new EmptyPragmaHandler()); 397 398 Token Tok; 399 // Start parsing the specified input file. 400 PP.EnterMainSourceFile(); 401 do { 402 PP.Lex(Tok); 403 } while (Tok.isNot(tok::eof)); 404} 405 406void PrintPreprocessedAction::ExecuteAction() { 407 CompilerInstance &CI = getCompilerInstance(); 408 // Output file may need to be set to 'Binary', to avoid converting Unix style 409 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>). 410 // 411 // Look to see what type of line endings the file uses. If there's a 412 // CRLF, then we won't open the file up in binary mode. If there is 413 // just an LF or CR, then we will open the file up in binary mode. 414 // In this fashion, the output format should match the input format, unless 415 // the input format has inconsistent line endings. 416 // 417 // This should be a relatively fast operation since most files won't have 418 // all of their source code on a single line. However, that is still a 419 // concern, so if we scan for too long, we'll just assume the file should 420 // be opened in binary mode. 421 bool BinaryMode = true; 422 bool InvalidFile = false; 423 const SourceManager& SM = CI.getSourceManager(); 424 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(), 425 &InvalidFile); 426 if (!InvalidFile) { 427 const char *cur = Buffer->getBufferStart(); 428 const char *end = Buffer->getBufferEnd(); 429 const char *next = (cur != end) ? cur + 1 : end; 430 431 // Limit ourselves to only scanning 256 characters into the source 432 // file. This is mostly a sanity check in case the file has no 433 // newlines whatsoever. 434 if (end - cur > 256) end = cur + 256; 435 436 while (next < end) { 437 if (*cur == 0x0D) { // CR 438 if (*next == 0x0A) // CRLF 439 BinaryMode = false; 440 441 break; 442 } else if (*cur == 0x0A) // LF 443 break; 444 445 ++cur, ++next; 446 } 447 } 448 449 raw_ostream *OS = CI.createDefaultOutputFile(BinaryMode, getCurrentFile()); 450 if (!OS) return; 451 452 DoPrintPreprocessedInput(CI.getPreprocessor(), OS, 453 CI.getPreprocessorOutputOpts()); 454} 455 456void PrintPreambleAction::ExecuteAction() { 457 switch (getCurrentFileKind()) { 458 case IK_C: 459 case IK_CXX: 460 case IK_ObjC: 461 case IK_ObjCXX: 462 case IK_OpenCL: 463 case IK_CUDA: 464 break; 465 466 case IK_None: 467 case IK_Asm: 468 case IK_PreprocessedC: 469 case IK_PreprocessedCXX: 470 case IK_PreprocessedObjC: 471 case IK_PreprocessedObjCXX: 472 case IK_AST: 473 case IK_LLVM_IR: 474 // We can't do anything with these. 475 return; 476 } 477 478 CompilerInstance &CI = getCompilerInstance(); 479 llvm::MemoryBuffer *Buffer 480 = CI.getFileManager().getBufferForFile(getCurrentFile()); 481 if (Buffer) { 482 unsigned Preamble = Lexer::ComputePreamble(Buffer, CI.getLangOpts()).first; 483 llvm::outs().write(Buffer->getBufferStart(), Preamble); 484 delete Buffer; 485 } 486} 487