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